@osmosis-ai/core 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.
Files changed (49) hide show
  1. package/dist/api/index.d.ts +12 -0
  2. package/dist/api/index.js +87 -0
  3. package/dist/api/index.js.map +1 -0
  4. package/dist/capture/index.d.ts +10 -0
  5. package/dist/capture/index.js +52 -0
  6. package/dist/capture/index.js.map +1 -0
  7. package/dist/distill/index.d.ts +35 -0
  8. package/dist/distill/index.js +41 -0
  9. package/dist/distill/index.js.map +1 -0
  10. package/dist/fitness/index.d.ts +14 -0
  11. package/dist/fitness/index.js +39 -0
  12. package/dist/fitness/index.js.map +1 -0
  13. package/dist/index.d.ts +10 -0
  14. package/dist/index.js +17 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/retrieval/index.d.ts +11 -0
  17. package/dist/retrieval/index.js +51 -0
  18. package/dist/retrieval/index.js.map +1 -0
  19. package/dist/seeds/index.d.ts +5 -0
  20. package/dist/seeds/index.js +131 -0
  21. package/dist/seeds/index.js.map +1 -0
  22. package/dist/store/index.d.ts +43 -0
  23. package/dist/store/index.js +230 -0
  24. package/dist/store/index.js.map +1 -0
  25. package/dist/types/index.d.ts +53 -0
  26. package/dist/types/index.js +2 -0
  27. package/dist/types/index.js.map +1 -0
  28. package/dist/validation/index.d.ts +119 -0
  29. package/dist/validation/index.js +55 -0
  30. package/dist/validation/index.js.map +1 -0
  31. package/package.json +23 -0
  32. package/src/__tests__/api.test.ts +103 -0
  33. package/src/__tests__/capture.test.ts +113 -0
  34. package/src/__tests__/distill.test.ts +83 -0
  35. package/src/__tests__/fitness.test.ts +58 -0
  36. package/src/__tests__/retrieval.test.ts +83 -0
  37. package/src/__tests__/store.test.ts +262 -0
  38. package/src/__tests__/types.test.ts +92 -0
  39. package/src/api/index.ts +94 -0
  40. package/src/capture/index.ts +71 -0
  41. package/src/distill/index.ts +64 -0
  42. package/src/fitness/index.ts +56 -0
  43. package/src/index.ts +51 -0
  44. package/src/retrieval/index.ts +61 -0
  45. package/src/seeds/index.ts +146 -0
  46. package/src/store/index.ts +250 -0
  47. package/src/types/index.ts +76 -0
  48. package/src/validation/index.ts +63 -0
  49. package/tsconfig.json +20 -0
@@ -0,0 +1,12 @@
1
+ import { type Server } from 'node:http';
2
+ import { AtomStore } from '../store/index.js';
3
+ /**
4
+ * Create an HTTP server for the AtomStore.
5
+ *
6
+ * Routes:
7
+ * POST /atoms — create atom (validates, dedup, insert)
8
+ * GET /atoms — list/filter atoms (?type=, ?tool_name=)
9
+ * GET /atoms/search?q= — text search
10
+ * GET /atoms/:id — get single atom
11
+ */
12
+ export declare function createServer(store: AtomStore, port?: number): Server;
@@ -0,0 +1,87 @@
1
+ import { createServer as createHttpServer } from 'node:http';
2
+ function json(res, status, data) {
3
+ res.writeHead(status, { 'Content-Type': 'application/json' });
4
+ res.end(JSON.stringify(data));
5
+ }
6
+ function readBody(req) {
7
+ return new Promise((resolve, reject) => {
8
+ const chunks = [];
9
+ req.on('data', (c) => chunks.push(c));
10
+ req.on('end', () => resolve(Buffer.concat(chunks).toString()));
11
+ req.on('error', reject);
12
+ });
13
+ }
14
+ /**
15
+ * Create an HTTP server for the AtomStore.
16
+ *
17
+ * Routes:
18
+ * POST /atoms — create atom (validates, dedup, insert)
19
+ * GET /atoms — list/filter atoms (?type=, ?tool_name=)
20
+ * GET /atoms/search?q= — text search
21
+ * GET /atoms/:id — get single atom
22
+ */
23
+ export function createServer(store, port = 3917) {
24
+ const server = createHttpServer(async (req, res) => {
25
+ const url = new URL(req.url ?? '/', `http://localhost:${port}`);
26
+ const path = url.pathname;
27
+ const method = req.method ?? 'GET';
28
+ try {
29
+ // POST /atoms
30
+ if (method === 'POST' && path === '/atoms') {
31
+ const body = JSON.parse(await readBody(req));
32
+ let atom;
33
+ if (body.type === 'tool') {
34
+ atom = store.createToolAtom(body);
35
+ }
36
+ else if (body.type === 'negative') {
37
+ atom = store.createNegativeAtom(body);
38
+ }
39
+ else {
40
+ atom = store.createAtom(body);
41
+ }
42
+ return json(res, 201, atom);
43
+ }
44
+ // GET /atoms/search?q=...
45
+ if (method === 'GET' && path === '/atoms/search') {
46
+ const q = url.searchParams.get('q') ?? '';
47
+ return json(res, 200, store.search(q));
48
+ }
49
+ // GET /atoms/:id
50
+ const idMatch = path.match(/^\/atoms\/([^/]+)$/);
51
+ if (method === 'GET' && idMatch) {
52
+ const atom = store.getById(idMatch[1]);
53
+ if (!atom)
54
+ return json(res, 404, { error: 'Not found' });
55
+ return json(res, 200, atom);
56
+ }
57
+ // GET /atoms?type=&tool_name=&since=
58
+ if (method === 'GET' && path === '/atoms') {
59
+ const type = url.searchParams.get('type');
60
+ const toolName = url.searchParams.get('tool_name');
61
+ const since = url.searchParams.get('since');
62
+ let atoms;
63
+ if (toolName) {
64
+ atoms = store.queryByToolName(toolName);
65
+ }
66
+ else if (type) {
67
+ atoms = store.queryByType(type);
68
+ }
69
+ else {
70
+ atoms = store.getAll();
71
+ }
72
+ if (since) {
73
+ atoms = atoms.filter(a => a.updated_at > since);
74
+ }
75
+ return json(res, 200, atoms);
76
+ }
77
+ json(res, 404, { error: 'Not found' });
78
+ }
79
+ catch (err) {
80
+ const status = err.name === 'ZodError' ? 400 : 500;
81
+ json(res, status, { error: err.message ?? 'Internal error' });
82
+ }
83
+ });
84
+ server.listen(port);
85
+ return server;
86
+ }
87
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAA0D,MAAM,WAAW,CAAC;AAIrH,SAAS,IAAI,CAAC,GAAmB,EAAE,MAAc,EAAE,IAAa;IAC9D,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAC9D,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC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G,CAAC,WAAW,CAAC,CAAC;gBACnD,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBAE5C,IAAI,KAAK,CAAC;gBACV,IAAI,QAAQ,EAAE,CAAC;oBACb,KAAK,GAAG,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;gBAC1C,CAAC;qBAAM,IAAI,IAAI,EAAE,CAAC;oBAChB,KAAK,GAAG,KAAK,CAAC,WAAW,CAAC,IAAW,CAAC,CAAC;gBACzC,CAAC;qBAAM,CAAC;oBACN,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;gBACzB,CAAC;gBAED,IAAI,KAAK,EAAE,CAAC;oBACV,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,GAAG,KAAK,CAAC,CAAC;gBAClD,CAAC;gBAED,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;YAC/B,CAAC;YAED,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;QACzC,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;YACnD,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,IAAI,gBAAgB,EAAE,CAAC,CAAC;QAChE,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACpB,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { OutcomeSignals } from '../types/index.js';
2
+ import { AtomStore } from '../store/index.js';
3
+ /**
4
+ * Capture a tool call and persist it as a ToolAtom in the local store.
5
+ */
6
+ export declare function captureToolCall(store: AtomStore, toolName: string, params: Record<string, unknown>, result: unknown, error?: string | null, latencyMs?: number | null): string;
7
+ /**
8
+ * Capture outcome signals for a task and persist as a base atom.
9
+ */
10
+ export declare function captureOutcome(store: AtomStore, taskId: string, signals: OutcomeSignals): string;
@@ -0,0 +1,52 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * Capture a tool call and persist it as a ToolAtom in the local store.
4
+ */
5
+ export function captureToolCall(store, toolName, params, result, error, latencyMs) {
6
+ const paramsHash = createHash('sha256').update(JSON.stringify(params)).digest('hex').slice(0, 16);
7
+ const outcome = error ? 'failure' : 'success';
8
+ const atom = store.createToolAtom({
9
+ type: 'tool',
10
+ observation: error
11
+ ? `Tool "${toolName}" failed: ${error}`
12
+ : `Tool "${toolName}" succeeded`,
13
+ context: JSON.stringify({ params_summary: Object.keys(params), has_result: result != null }),
14
+ confidence: error ? 0.3 : 0.7,
15
+ fitness_score: error ? 0.2 : 0.8,
16
+ trust_tier: 'local',
17
+ source_agent_hash: 'local',
18
+ decay_rate: 0.99,
19
+ tool_name: toolName,
20
+ params_hash: paramsHash,
21
+ outcome,
22
+ error_signature: error ?? null,
23
+ latency_ms: latencyMs ?? null,
24
+ reliability_score: error ? 0.0 : 1.0,
25
+ });
26
+ return atom.id;
27
+ }
28
+ /**
29
+ * Capture outcome signals for a task and persist as a base atom.
30
+ */
31
+ export function captureOutcome(store, taskId, signals) {
32
+ // Score using PRD v1 weights:
33
+ // completion without error (0.3), no revisit within 1hr (0.2),
34
+ // human acceptance (0.3), convergence speed (0.1), error-free (0.1)
35
+ const score = (signals.completed_without_error ? 0.3 : 0) +
36
+ (!signals.revisited_within_1hr ? 0.2 : 0) +
37
+ (signals.human_accepted === true ? 0.3 : signals.human_accepted === null ? 0.15 : 0) +
38
+ Math.max(0, 0.1 * (1 - signals.convergence_steps / 20)) +
39
+ (signals.error_free ? 0.1 : 0);
40
+ const atom = store.createAtom({
41
+ type: 'context',
42
+ observation: `Task ${taskId} outcome: score=${score.toFixed(3)}`,
43
+ context: JSON.stringify(signals),
44
+ confidence: score,
45
+ fitness_score: score,
46
+ trust_tier: 'local',
47
+ source_agent_hash: 'local',
48
+ decay_rate: 0.99,
49
+ });
50
+ return atom.id;
51
+ }
52
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/capture/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAc,MAAM,aAAa,CAAC;AAIrD;;GAEG;AACH,MAAM,UAAU,eAAe,CAC7B,KAAgB,EAChB,QAAgB,EAChB,MAA+B,EAC/B,MAAe,EACf,KAAqB,EACrB,SAAyB;IAEzB,MAAM,UAAU,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAClG,MAAM,OAAO,GAAY,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;IAEvD,MAAM,IAAI,GAAG,KAAK,CAAC,cAAc,CAAC;QAChC,IAAI,EAAE,MAAM;QACZ,WAAW,EAAE,KAAK;YAChB,CAAC,CAAC,SAAS,QAAQ,aAAa,KAAK,EAAE;YACvC,CAAC,CAAC,SAAS,QAAQ,aAAa;QAClC,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,cAAc,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,MAAM,IAAI,IAAI,EAAE,CAAC;QAC5F,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;QAC7B,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;QAChC,UAAU,EAAE,OAAO;Q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C,UAAU,EAAE,KAAK;QACjB,aAAa,EAAE,KAAK;QACpB,UAAU,EAAE,OAAO;QACnB,iBAAiB,EAAE,OAAO;QAC1B,UAAU,EAAE,IAAI;KACjB,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC,EAAE,CAAC;AACjB,CAAC"}
@@ -0,0 +1,35 @@
1
+ import type { KnowledgeAtom } from '../types/index.js';
2
+ export interface ToolTrace {
3
+ toolName: string;
4
+ params: Record<string, unknown>;
5
+ result: unknown;
6
+ error: string | null;
7
+ latencyMs: number;
8
+ outcome: 'success' | 'failure' | 'partial';
9
+ agentId: string;
10
+ timestamp: string;
11
+ }
12
+ export type DistillFn = (trace: ToolTrace) => Promise<KnowledgeAtom | null>;
13
+ /**
14
+ * Stub distillation — returns null. Will be replaced with LLM call later.
15
+ */
16
+ export declare function distillTrace(_trace: ToolTrace): Promise<KnowledgeAtom | null>;
17
+ export declare class BatchDistiller {
18
+ private buffer;
19
+ private readonly batchSize;
20
+ private readonly distillFn;
21
+ constructor(options?: {
22
+ batchSize?: number;
23
+ distillFn?: DistillFn;
24
+ });
25
+ /** Add a trace to the buffer. Returns true if batch is full. */
26
+ add(trace: ToolTrace): boolean;
27
+ /** Number of pending traces */
28
+ get pending(): number;
29
+ /** Check if batch is ready to process */
30
+ get ready(): boolean;
31
+ /** Flush and process the current batch. Returns distilled atoms (nulls filtered). */
32
+ flush(): Promise<KnowledgeAtom[]>;
33
+ /** Drain all traces without processing */
34
+ drain(): ToolTrace[];
35
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Stub distillation — returns null. Will be replaced with LLM call later.
3
+ */
4
+ export async function distillTrace(_trace) {
5
+ // Stub: actual LLM distillation will be implemented in a later phase
6
+ return null;
7
+ }
8
+ // ── BatchDistiller ───────────────────────────────────────────
9
+ export class BatchDistiller {
10
+ buffer = [];
11
+ batchSize;
12
+ distillFn;
13
+ constructor(options) {
14
+ this.batchSize = options?.batchSize ?? 10;
15
+ this.distillFn = options?.distillFn ?? distillTrace;
16
+ }
17
+ /** Add a trace to the buffer. Returns true if batch is full. */
18
+ add(trace) {
19
+ this.buffer.push(trace);
20
+ return this.buffer.length >= this.batchSize;
21
+ }
22
+ /** Number of pending traces */
23
+ get pending() {
24
+ return this.buffer.length;
25
+ }
26
+ /** Check if batch is ready to process */
27
+ get ready() {
28
+ return this.buffer.length >= this.batchSize;
29
+ }
30
+ /** Flush and process the current batch. Returns distilled atoms (nulls filtered). */
31
+ async flush() {
32
+ const batch = this.buffer.splice(0);
33
+ const results = await Promise.all(batch.map(t => this.distillFn(t)));
34
+ return results.filter((a) => a !== null);
35
+ }
36
+ /** Drain all traces without processing */
37
+ drain() {
38
+ return this.buffer.splice(0);
39
+ }
40
+ }
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/distill/index.ts"],"names":[],"mappings":"AAiBA;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,MAAiB;IAClD,qEAAqE;IACrE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,gEAAgE;AAChE,MAAM,OAAO,cAAc;IACjB,MAAM,GAAgB,EAAE,CAAC;IAChB,SAAS,CAAS;IAClB,SAAS,CAAY;IAEtC,YAAY,OAAuD;QACjE,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,EAAE,CAAC;QAC1C,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,YAAY,CAAC;IACtD,CAAC;IAED,gEAAgE;IAChE,GAAG,CAAC,KAAgB;QAClB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC;IAC9C,CAAC;IAED,+BAA+B;IAC/B,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED,yCAAyC;IACzC,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC;IAC9C,CAAC;IAED,qFAAqF;IACrF,KAAK,CAAC,KAAK;QACT,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACrE,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAsB,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;IAC/D,CAAC;IAED,0CAA0C;IAC1C,KAAK;QACH,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC;CACF"}
@@ -0,0 +1,14 @@
1
+ import type { AtomStore } from '../store/index.js';
2
+ /**
3
+ * Calculate fitness for a single atom using the PRD formula:
4
+ * fitness = usage_rate × success_ratio × recency_factor
5
+ *
6
+ * - usage_rate = use_count / max(1, max_use_count_across_all) — normalized
7
+ * - success_ratio = success_after_use / max(1, success_after_use + failure_after_use)
8
+ * - recency_factor = exp(-λ × days_since_last_use), λ = 0.05
9
+ */
10
+ export declare function computeFitness(useCount: number, successAfterUse: number, failureAfterUse: number, lastUsed: string | null, maxUseCount: number, now?: Date): number;
11
+ /**
12
+ * Batch-recalculate fitness for all atoms in the store.
13
+ */
14
+ export declare function recalculateFitness(store: AtomStore): void;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Calculate fitness for a single atom using the PRD formula:
3
+ * fitness = usage_rate × success_ratio × recency_factor
4
+ *
5
+ * - usage_rate = use_count / max(1, max_use_count_across_all) — normalized
6
+ * - success_ratio = success_after_use / max(1, success_after_use + failure_after_use)
7
+ * - recency_factor = exp(-λ × days_since_last_use), λ = 0.05
8
+ */
9
+ export function computeFitness(useCount, successAfterUse, failureAfterUse, lastUsed, maxUseCount, now = new Date()) {
10
+ const usageRate = maxUseCount > 0 ? useCount / maxUseCount : 0;
11
+ const total = successAfterUse + failureAfterUse;
12
+ const successRatio = total > 0 ? successAfterUse / total : 0.5; // neutral if unused
13
+ const daysSinceUse = lastUsed
14
+ ? Math.max(0, (now.getTime() - new Date(lastUsed).getTime()) / (1000 * 60 * 60 * 24))
15
+ : 30; // default to 30 days if never used
16
+ const lambda = 0.05;
17
+ const recencyFactor = Math.exp(-lambda * daysSinceUse);
18
+ return Math.min(1, Math.max(0, usageRate * successRatio * recencyFactor));
19
+ }
20
+ /**
21
+ * Batch-recalculate fitness for all atoms in the store.
22
+ */
23
+ export function recalculateFitness(store) {
24
+ const atoms = store.getAll();
25
+ // Find max use_count for normalization
26
+ let maxUseCount = 1;
27
+ for (const atom of atoms) {
28
+ const uc = atom.use_count ?? 0;
29
+ if (uc > maxUseCount)
30
+ maxUseCount = uc;
31
+ }
32
+ const now = new Date();
33
+ for (const atom of atoms) {
34
+ const a = atom;
35
+ const score = computeFitness(a.use_count ?? 0, a.success_after_use ?? 0, a.failure_after_use ?? 0, a.last_used ?? null, maxUseCount, now);
36
+ store.updateFitnessScore(atom.id, score);
37
+ }
38
+ }
39
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/fitness/index.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAC5B,QAAgB,EAChB,eAAuB,EACvB,eAAuB,EACvB,QAAuB,EACvB,WAAmB,EACnB,MAAY,IAAI,IAAI,EAAE;IAEtB,MAAM,SAAS,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,MAAM,KAAK,GAAG,eAAe,GAAG,eAAe,CAAC;IAChD,MAAM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AAI,CAAC,EACxB,CAAC,CAAC,iBAAiB,IAAI,CAAC,EACxB,CAAC,CAAC,SAAS,IAAI,IAAI,EACnB,WAAW,EACX,GAAG,CACJ,CAAC;QACF,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC"}
@@ -0,0 +1,10 @@
1
+ export type { KnowledgeAtom, ToolAtom, NegativeAtom, PatternAtom, SkillAtom, ContextAtom, AnyAtom, OutcomeSignals, CreateAtom, CreateToolAtom, CreateNegativeAtom, AtomType, TrustTier, Outcome, Severity, } from './types/index.js';
2
+ export { AtomStore, jaccardSimilarity } from './store/index.js';
3
+ export { captureToolCall, captureOutcome } from './capture/index.js';
4
+ export { CreateAtomSchema, CreateToolAtomSchema, CreateNegativeAtomSchema, OutcomeSignalsSchema, validateCreateAtom, validateCreateToolAtom, validateCreateNegativeAtom, } from './validation/index.js';
5
+ export { computeFitness, recalculateFitness } from './fitness/index.js';
6
+ export { createServer } from './api/index.js';
7
+ export { searchAtoms, getTopAtoms } from './retrieval/index.js';
8
+ export { distillTrace, BatchDistiller } from './distill/index.js';
9
+ export type { ToolTrace, DistillFn } from './distill/index.js';
10
+ export { seedAtoms } from './seeds/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ // Store
2
+ export { AtomStore, jaccardSimilarity } from './store/index.js';
3
+ // Capture
4
+ export { captureToolCall, captureOutcome } from './capture/index.js';
5
+ // Validation
6
+ export { CreateAtomSchema, CreateToolAtomSchema, CreateNegativeAtomSchema, OutcomeSignalsSchema, validateCreateAtom, validateCreateToolAtom, validateCreateNegativeAtom, } from './validation/index.js';
7
+ // Fitness
8
+ export { computeFitness, recalculateFitness } from './fitness/index.js';
9
+ // API
10
+ export { createServer } from './api/index.js';
11
+ // Retrieval
12
+ export { searchAtoms, getTopAtoms } from './retrieval/index.js';
13
+ // Distill
14
+ export { distillTrace, BatchDistiller } from './distill/index.js';
15
+ // Seeds
16
+ export { seedAtoms } from './seeds/index.js';
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAmBA,QAAQ;AACR,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAEhE,UAAU;AACV,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAErE,aAAa;AACb,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,wBAAwB,EACxB,oBAAoB,EACpB,kBAAkB,EAClB,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,uBAAuB,CAAC;AAE/B,UAAU;AACV,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExE,MAAM;AACN,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C,YAAY;AACZ,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEhE,UAAU;AACV,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGlE,QAAQ;AACR,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { KnowledgeAtom, AtomType } from '../types/index.js';
2
+ import type { AtomStore } from '../store/index.js';
3
+ /**
4
+ * Search atoms using FTS5 full-text search, ranked by relevance × fitness_score.
5
+ * Falls back to LIKE search if FTS table doesn't exist.
6
+ */
7
+ export declare function searchAtoms(store: AtomStore, query: string, limit?: number): KnowledgeAtom[];
8
+ /**
9
+ * Get top atoms by fitness score, optionally filtered by type.
10
+ */
11
+ export declare function getTopAtoms(store: AtomStore, type?: AtomType, limit?: number): KnowledgeAtom[];
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Search atoms using FTS5 full-text search, ranked by relevance × fitness_score.
3
+ * Falls back to LIKE search if FTS table doesn't exist.
4
+ */
5
+ export function searchAtoms(store, query, limit = 10) {
6
+ const db = store.db;
7
+ // Ensure FTS5 table exists
8
+ try {
9
+ db.exec(`
10
+ CREATE VIRTUAL TABLE IF NOT EXISTS atoms_fts USING fts5(
11
+ id UNINDEXED, observation, context, content=atoms, content_rowid=rowid
12
+ );
13
+ `);
14
+ // Rebuild FTS index from current atoms
15
+ db.exec(`INSERT OR REPLACE INTO atoms_fts(atoms_fts) VALUES('rebuild')`);
16
+ }
17
+ catch {
18
+ // FTS5 not available, fall back to LIKE
19
+ return store.search(query).slice(0, limit);
20
+ }
21
+ try {
22
+ // Escape FTS5 special chars
23
+ const escaped = query.replace(/['"*()]/g, ' ').trim();
24
+ if (!escaped)
25
+ return [];
26
+ const rows = db.prepare(`
27
+ SELECT a.*, bm25(atoms_fts) as rank
28
+ FROM atoms_fts f
29
+ JOIN atoms a ON a.id = f.id
30
+ WHERE atoms_fts MATCH ?
31
+ ORDER BY (bm25(atoms_fts) * -1) * a.fitness_score DESC
32
+ LIMIT ?
33
+ `).all(escaped, limit);
34
+ return rows.map(({ rank, ...atom }) => atom);
35
+ }
36
+ catch {
37
+ // Fall back to LIKE search
38
+ return store.search(query).slice(0, limit);
39
+ }
40
+ }
41
+ /**
42
+ * Get top atoms by fitness score, optionally filtered by type.
43
+ */
44
+ export function getTopAtoms(store, type, limit = 10) {
45
+ const db = store.db;
46
+ if (type) {
47
+ return db.prepare('SELECT * FROM atoms WHERE type = ? ORDER BY fitness_score DESC LIMIT ?').all(type, limit);
48
+ }
49
+ return db.prepare('SELECT * FROM atoms ORDER BY fitness_score DESC LIMIT ?').all(limit);
50
+ }
51
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/retrieval/index.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,KAAgB,EAAE,KAAa,EAAE,QAAgB,EAAE;IAC7E,MAAM,EAAE,G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GAAG,CAAC,KAAK,CAAoB,CAAC;AAClC,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { AtomStore } from '../store/index.js';
2
+ /**
3
+ * Seed the store with 15 realistic knowledge atoms from common OpenClaw agent experiences.
4
+ */
5
+ export declare function seedAtoms(store: AtomStore): void;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Seed the store with 15 realistic knowledge atoms from common OpenClaw agent experiences.
3
+ */
4
+ export function seedAtoms(store) {
5
+ // 1. browser.screenshot fails on lazy-loaded pages
6
+ store.createToolAtom({
7
+ type: 'tool',
8
+ observation: 'browser.screenshot fails on lazy-loaded pages — images appear blank. Add a 2s delay or scroll first to trigger loading.',
9
+ context: JSON.stringify({ tool: 'browser.screenshot', workaround: 'delay 2000ms or scroll to trigger lazy load' }),
10
+ confidence: 0.9, fitness_score: 0.85, trust_tier: 'local', source_agent_hash: 'seed',
11
+ decay_rate: 0.99, tool_name: 'browser.screenshot', params_hash: 'seed',
12
+ outcome: 'failure', error_signature: 'blank screenshot on lazy-loaded content', latency_ms: 3200, reliability_score: 0.4,
13
+ });
14
+ // 2. exec with long-running commands needs timeout
15
+ store.createToolAtom({
16
+ type: 'tool',
17
+ observation: 'exec commands that run >60s will be killed by default timeout. Always pass explicit timeout parameter for builds, tests, or installs.',
18
+ context: JSON.stringify({ tool: 'exec', tip: 'set timeout: 120+ for npm install, builds' }),
19
+ confidence: 0.95, fitness_score: 0.9, trust_tier: 'local', source_agent_hash: 'seed',
20
+ decay_rate: 0.99, tool_name: 'exec', params_hash: 'seed',
21
+ outcome: 'failure', error_signature: 'process killed by timeout', latency_ms: 60000, reliability_score: 0.3,
22
+ });
23
+ // 3. web_fetch returns truncated content
24
+ store.createToolAtom({
25
+ type: 'tool',
26
+ observation: 'web_fetch returns truncated content for pages >50KB. Use maxChars parameter or fetch specific sections with CSS selectors.',
27
+ context: JSON.stringify({ tool: 'web_fetch', limit: '50KB default' }),
28
+ confidence: 0.85, fitness_score: 0.8, trust_tier: 'local', source_agent_hash: 'seed',
29
+ decay_rate: 0.99, tool_name: 'web_fetch', params_hash: 'seed',
30
+ outcome: 'partial', error_signature: null, latency_ms: 2500, reliability_score: 0.6,
31
+ });
32
+ // 4. API rate limiting
33
+ store.createNegativeAtom({
34
+ type: 'negative',
35
+ observation: 'Calling external APIs without rate limiting causes retry storms — exponential backoff quickly burns through quotas.',
36
+ context: JSON.stringify({ pattern: 'retry storm', fix: 'add exponential backoff with jitter' }),
37
+ confidence: 0.9, fitness_score: 0.85, trust_tier: 'local', source_agent_hash: 'seed',
38
+ decay_rate: 0.99, anti_pattern: 'unbounded API retries without backoff',
39
+ failure_cluster_size: 5, error_type: 'rate_limit_exceeded', severity: 'high',
40
+ });
41
+ // 5. git push without pull
42
+ store.createNegativeAtom({
43
+ type: 'negative',
44
+ observation: 'git push without pulling first causes force-push disasters when remote has diverged. Always git pull --rebase before push.',
45
+ context: JSON.stringify({ pattern: 'force push', fix: 'git pull --rebase origin <branch> first' }),
46
+ confidence: 0.95, fitness_score: 0.9, trust_tier: 'local', source_agent_hash: 'seed',
47
+ decay_rate: 0.99, anti_pattern: 'git push without checking remote state',
48
+ failure_cluster_size: 3, error_type: 'rejected_non_fast_forward', severity: 'critical',
49
+ });
50
+ // 6. browser.navigate needs network idle
51
+ store.createToolAtom({
52
+ type: 'tool',
53
+ observation: 'browser.navigate often returns before page is fully loaded. Wait for network idle or a specific element before interacting.',
54
+ context: JSON.stringify({ tool: 'browser.navigate', tip: 'use snapshot after navigate to confirm load' }),
55
+ confidence: 0.85, fitness_score: 0.8, trust_tier: 'local', source_agent_hash: 'seed',
56
+ decay_rate: 0.99, tool_name: 'browser.navigate', params_hash: 'seed',
57
+ outcome: 'partial', error_signature: null, latency_ms: 1500, reliability_score: 0.5,
58
+ });
59
+ // 7. Agent iteration pattern
60
+ store.createAtom({
61
+ type: 'pattern',
62
+ observation: 'When an agent iterates more than 3 times on the same approach, it usually means the approach is wrong. Step back and try a different strategy.',
63
+ context: JSON.stringify({ threshold: 3, action: 'change approach' }),
64
+ confidence: 0.8, fitness_score: 0.75, trust_tier: 'local', source_agent_hash: 'seed', decay_rate: 0.99,
65
+ });
66
+ // 8. Playwright vs Puppeteer
67
+ store.createAtom({
68
+ type: 'context',
69
+ observation: 'Playwright is faster than Puppeteer for parallel page loads and has better auto-waiting. Prefer it for browser automation tasks.',
70
+ context: JSON.stringify({ comparison: 'playwright > puppeteer for parallel' }),
71
+ confidence: 0.7, fitness_score: 0.65, trust_tier: 'local', source_agent_hash: 'seed', decay_rate: 0.99,
72
+ });
73
+ // 9. File read with offset for large files
74
+ store.createToolAtom({
75
+ type: 'tool',
76
+ observation: 'Read tool truncates at 2000 lines or 50KB. For large files, use offset/limit parameters to paginate through content.',
77
+ context: JSON.stringify({ tool: 'Read', tip: 'use offset to continue reading' }),
78
+ confidence: 0.9, fitness_score: 0.85, trust_tier: 'local', source_agent_hash: 'seed',
79
+ decay_rate: 0.99, tool_name: 'Read', params_hash: 'seed',
80
+ outcome: 'success', error_signature: null, latency_ms: 50, reliability_score: 0.9,
81
+ });
82
+ // 10. TypeScript project references
83
+ store.createAtom({
84
+ type: 'context',
85
+ observation: 'In monorepos with TypeScript project references, build packages in dependency order. Core before dependent packages.',
86
+ context: JSON.stringify({ tip: 'tsc --build for composite projects' }),
87
+ confidence: 0.85, fitness_score: 0.8, trust_tier: 'local', source_agent_hash: 'seed', decay_rate: 0.99,
88
+ });
89
+ // 11. exec command chaining
90
+ store.createToolAtom({
91
+ type: 'tool',
92
+ observation: 'Use && to chain exec commands rather than separate calls — reduces latency and ensures sequential execution with early exit on failure.',
93
+ context: JSON.stringify({ tool: 'exec', tip: 'chain with && for atomic operations' }),
94
+ confidence: 0.8, fitness_score: 0.75, trust_tier: 'local', source_agent_hash: 'seed',
95
+ decay_rate: 0.99, tool_name: 'exec', params_hash: 'seed-chain',
96
+ outcome: 'success', error_signature: null, latency_ms: 100, reliability_score: 0.9,
97
+ });
98
+ // 12. Don't rm -rf without confirmation
99
+ store.createNegativeAtom({
100
+ type: 'negative',
101
+ observation: 'Never use rm -rf on user directories without explicit confirmation. Use trash command or move to temp location first.',
102
+ context: JSON.stringify({ pattern: 'destructive delete', fix: 'use trash or ask first' }),
103
+ confidence: 0.95, fitness_score: 0.95, trust_tier: 'local', source_agent_hash: 'seed',
104
+ decay_rate: 0.99, anti_pattern: 'rm -rf without confirmation',
105
+ failure_cluster_size: 2, error_type: 'data_loss', severity: 'critical',
106
+ });
107
+ // 13. browser snapshot refs
108
+ store.createToolAtom({
109
+ type: 'tool',
110
+ observation: 'browser.snapshot refs change between calls. Always take a fresh snapshot before clicking — stale refs cause "element not found" errors.',
111
+ context: JSON.stringify({ tool: 'browser.snapshot', tip: 'snapshot immediately before act' }),
112
+ confidence: 0.9, fitness_score: 0.85, trust_tier: 'local', source_agent_hash: 'seed',
113
+ decay_rate: 0.99, tool_name: 'browser.snapshot', params_hash: 'seed',
114
+ outcome: 'failure', error_signature: 'element ref not found', latency_ms: 200, reliability_score: 0.5,
115
+ });
116
+ // 14. JSON parse errors in web_fetch
117
+ store.createAtom({
118
+ type: 'pattern',
119
+ observation: 'When web_fetch returns markdown, don\'t try to JSON.parse it. Check content type first or wrap in try/catch with fallback.',
120
+ context: JSON.stringify({ pattern: 'content type mismatch' }),
121
+ confidence: 0.8, fitness_score: 0.75, trust_tier: 'local', source_agent_hash: 'seed', decay_rate: 0.99,
122
+ });
123
+ // 15. Vitest vs Jest in ESM projects
124
+ store.createAtom({
125
+ type: 'context',
126
+ observation: 'Vitest works natively with ESM and TypeScript. Jest requires extensive configuration for ESM. Use Vitest for modern TS projects.',
127
+ context: JSON.stringify({ comparison: 'vitest > jest for ESM+TS' }),
128
+ confidence: 0.75, fitness_score: 0.7, trust_tier: 'local', source_agent_hash: 'seed', decay_rate: 0.99,
129
+ });
130
+ }
131
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/seeds/index.ts"],"names":[],"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K,CAAC,UAAU,CAAC;QACf,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,kIAAkI;QAC/I,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,UAAU,EAAE,0BAA0B,EAAE,CAAC;QACnE,UAAU,EAAE,IAAI,EAAE,aAAa,EAAE,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI;KACvG,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,43 @@
1
+ import type { KnowledgeAtom, ToolAtom, NegativeAtom, CreateAtom, CreateToolAtom, CreateNegativeAtom, AtomType } from '../types/index.js';
2
+ /**
3
+ * Jaccard similarity between two strings (based on word bigrams).
4
+ */
5
+ export declare function jaccardSimilarity(a: string, b: string): number;
6
+ export declare class AtomStore {
7
+ private db;
8
+ constructor(dbPath?: string);
9
+ /** Run schema migrations */
10
+ migrate(): void;
11
+ /** Find atoms with similar observation text */
12
+ findSimilar(observation: string, threshold?: number): KnowledgeAtom[];
13
+ /** Insert a base/pattern/skill/context atom (with validation and dedup) */
14
+ createAtom(data: CreateAtom): KnowledgeAtom;
15
+ /** Insert a ToolAtom (with validation and dedup) */
16
+ createToolAtom(data: CreateToolAtom): ToolAtom;
17
+ /** Insert a NegativeAtom (with validation and dedup) */
18
+ createNegativeAtom(data: CreateNegativeAtom): NegativeAtom;
19
+ /** Merge: keep higher fitness, increment evidence_count */
20
+ private _mergeAtom;
21
+ /** Get atom by ID */
22
+ getById(id: string): KnowledgeAtom | null;
23
+ /** Query atoms by type */
24
+ queryByType(type: AtomType): KnowledgeAtom[];
25
+ /** Query tool atoms by tool_name */
26
+ queryByToolName(toolName: string): ToolAtom[];
27
+ /** Query atoms with confidence >= threshold */
28
+ queryByConfidence(threshold: number): KnowledgeAtom[];
29
+ /** Full-text search on observation */
30
+ search(query: string): KnowledgeAtom[];
31
+ /** Update fitness score for a specific atom */
32
+ updateFitnessScore(id: string, newScore: number): void;
33
+ /** Record a usage event */
34
+ recordUsage(id: string, success: boolean): void;
35
+ /** Apply decay: multiply fitness_score by decay_rate for all atoms */
36
+ applyDecay(): number;
37
+ /** Delete atom by ID */
38
+ deleteAtom(id: string): boolean;
39
+ /** Get all atoms */
40
+ getAll(): KnowledgeAtom[];
41
+ /** Close the database */
42
+ close(): void;
43
+ }