@voidwire/lore 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Rudy Ruiz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,159 @@
1
+ # lore
2
+
3
+ Unified knowledge CLI — search, list, and capture your indexed knowledge fabric.
4
+
5
+ ## Philosophy
6
+
7
+ - **Unified** — Single entry point for all knowledge operations
8
+ - **Library-first** — Import functions directly, CLI is a thin wrapper
9
+ - **Composable** — JSON output pipes to jq, grep, other Unix tools
10
+ - **Zero duplication** — Re-exports from lore-search and lore-capture
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ cd llmcli-tools/packages/lore
16
+ bun link
17
+ ```
18
+
19
+ ## CLI Usage
20
+
21
+ ```bash
22
+ lore search <query> # Search all sources
23
+ lore search <source> <query> # Search specific source
24
+ lore search --sources # List indexed sources
25
+
26
+ lore list <domain> # List domain entries
27
+ lore list --domains # List available domains
28
+
29
+ lore capture task|knowledge|note # Capture knowledge
30
+ ```
31
+
32
+ ### Search Options
33
+
34
+ - `--limit <n>` — Maximum results (default: 20)
35
+ - `--since <date>` — Filter by date (today, yesterday, this-week, YYYY-MM-DD)
36
+ - `--sources` — List indexed sources with counts
37
+
38
+ ### List Options
39
+
40
+ - `--limit <n>` — Maximum entries
41
+ - `--format <fmt>` — Output format: json (default), jsonl, human
42
+ - `--domains` — List available domains
43
+
44
+ ### Capture Types
45
+
46
+ ```bash
47
+ # Task completion
48
+ lore capture task --project=myproject --name="Task name" \
49
+ --problem="What was solved" --solution="How it was solved"
50
+
51
+ # Knowledge insight
52
+ lore capture knowledge --context=myproject \
53
+ --text="Insight learned" --type=learning
54
+
55
+ # Quick note
56
+ lore capture note --text="Remember this" --tags=tag1,tag2
57
+ ```
58
+
59
+ ## Library Usage
60
+
61
+ The real power is programmatic access:
62
+
63
+ ```typescript
64
+ import {
65
+ // Search (from lore-search)
66
+ search,
67
+ listSources,
68
+ type SearchResult,
69
+ type SearchOptions,
70
+
71
+ // List (local)
72
+ list,
73
+ listDomains,
74
+ DOMAINS,
75
+ type Domain,
76
+ type ListResult,
77
+
78
+ // Capture (from lore-capture)
79
+ captureKnowledge,
80
+ captureTask,
81
+ captureNote,
82
+ type KnowledgeInput,
83
+ type TaskInput,
84
+ type NoteInput,
85
+ } from "lore";
86
+
87
+ // Search
88
+ const results = search("authentication", { limit: 10 });
89
+
90
+ // List
91
+ const devProjects = list("development");
92
+
93
+ // Capture
94
+ captureKnowledge({
95
+ context: "myproject",
96
+ text: "Important insight",
97
+ type: "learning",
98
+ });
99
+ ```
100
+
101
+ ## Domains
102
+
103
+ 15 domains available for `lore list`:
104
+
105
+ | Domain | Description |
106
+ |--------|-------------|
107
+ | development | Development projects |
108
+ | tasks | Flux tasks and ideas |
109
+ | events | Events by project |
110
+ | blogs | Blog posts |
111
+ | commits | Git commits |
112
+ | explorations | Project explorations |
113
+ | readmes | Project READMEs |
114
+ | obsidian | Obsidian vault notes |
115
+ | captures | Quick captures |
116
+ | books | Books read |
117
+ | movies | Movies watched |
118
+ | podcasts | Podcast subscriptions |
119
+ | interests | Personal interests |
120
+ | people | People and relationships |
121
+ | habits | Habit tracking |
122
+
123
+ ## Knowledge Types
124
+
125
+ For `lore capture knowledge --type`:
126
+
127
+ - `decision` — Architectural or design decisions
128
+ - `learning` — Something learned during work
129
+ - `gotcha` — Pitfall or gotcha to remember
130
+ - `preference` — User preference discovered
131
+ - `project` — Project-level insight
132
+ - `conversation` — Insight from conversation
133
+ - `knowledge` — General knowledge
134
+
135
+ ## Architecture
136
+
137
+ ```
138
+ lore/
139
+ ├── index.ts # Re-exports from lib/
140
+ ├── cli.ts # Unified CLI (search|list|capture)
141
+ ├── lib/
142
+ │ ├── search.ts # FTS5 search (SQLite)
143
+ │ ├── list.ts # Domain listing
144
+ │ └── capture.ts # JSONL capture
145
+ └── package.json # Zero dependencies
146
+ ```
147
+
148
+ Self-contained package. No workspace dependencies. Ready for npm publish.
149
+
150
+ ## Data Locations
151
+
152
+ - `~/.local/share/lore/lore.db` — SQLite FTS5 database (search, list)
153
+ - `~/.local/share/lore/log.jsonl` — Capture event log
154
+
155
+ ## Exit Codes
156
+
157
+ - `0` — Success
158
+ - `1` — Validation error (missing args, invalid domain)
159
+ - `2` — Runtime error (database not found)
package/cli.ts ADDED
@@ -0,0 +1,433 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * lore - Unified knowledge CLI
4
+ *
5
+ * Philosophy:
6
+ * - Single entry point for knowledge operations
7
+ * - Search, list, and capture indexed knowledge
8
+ * - JSON output for composability
9
+ *
10
+ * Usage:
11
+ * lore search <query> Search all sources
12
+ * lore search <source> <query> Search specific source
13
+ * lore list <domain> List domain entries
14
+ * lore capture task|knowledge|note Capture knowledge
15
+ *
16
+ * Exit codes:
17
+ * 0 - Success
18
+ * 1 - Validation error
19
+ * 2 - Runtime error
20
+ */
21
+
22
+ import {
23
+ search,
24
+ listSources,
25
+ list,
26
+ listDomains,
27
+ captureTask,
28
+ captureKnowledge,
29
+ captureNote,
30
+ DOMAINS,
31
+ type SearchResult,
32
+ type ListResult,
33
+ type ListEntry,
34
+ type Domain,
35
+ type TaskInput,
36
+ type KnowledgeInput,
37
+ type NoteInput,
38
+ type KnowledgeCaptureType,
39
+ } from "./index";
40
+
41
+ // ============================================================================
42
+ // Argument Parsing
43
+ // ============================================================================
44
+
45
+ function parseArgs(args: string[]): Map<string, string> {
46
+ const parsed = new Map<string, string>();
47
+ let i = 0;
48
+
49
+ while (i < args.length) {
50
+ const arg = args[i];
51
+
52
+ if (arg.startsWith("--")) {
53
+ const key = arg.slice(2);
54
+
55
+ if (key.includes("=")) {
56
+ const [k, v] = key.split("=", 2);
57
+ parsed.set(k, v);
58
+ i++;
59
+ } else if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
60
+ parsed.set(key, args[i + 1]);
61
+ i += 2;
62
+ } else {
63
+ parsed.set(key, "true");
64
+ i++;
65
+ }
66
+ } else {
67
+ i++;
68
+ }
69
+ }
70
+
71
+ return parsed;
72
+ }
73
+
74
+ function getPositionalArgs(args: string[]): string[] {
75
+ return args.filter((arg) => !arg.startsWith("--"));
76
+ }
77
+
78
+ function hasFlag(args: string[], flag: string): boolean {
79
+ return args.includes(`--${flag}`) || args.includes(`-${flag.charAt(0)}`);
80
+ }
81
+
82
+ function parseList(value: string | undefined): string[] | undefined {
83
+ if (!value) return undefined;
84
+ const items = value
85
+ .split(",")
86
+ .map((s) => s.trim())
87
+ .filter(Boolean);
88
+ return items.length > 0 ? items : undefined;
89
+ }
90
+
91
+ // ============================================================================
92
+ // Output Helpers
93
+ // ============================================================================
94
+
95
+ interface OutputResult {
96
+ success: boolean;
97
+ [key: string]: unknown;
98
+ }
99
+
100
+ function output(result: OutputResult): void {
101
+ console.log(JSON.stringify(result, null, 2));
102
+ }
103
+
104
+ function fail(error: string, code: number = 1): never {
105
+ output({ success: false, error });
106
+ console.error(`❌ ${error}`);
107
+ process.exit(code);
108
+ }
109
+
110
+ // ============================================================================
111
+ // Search Command
112
+ // ============================================================================
113
+
114
+ function handleSearch(args: string[]): void {
115
+ const parsed = parseArgs(args);
116
+ const positional = getPositionalArgs(args);
117
+
118
+ // Handle --sources flag
119
+ if (hasFlag(args, "sources")) {
120
+ const sources = listSources();
121
+ output({ success: true, sources });
122
+ console.error(`✅ ${sources.length} sources indexed`);
123
+ process.exit(0);
124
+ }
125
+
126
+ if (positional.length === 0) {
127
+ fail("Missing search query. Use: lore search <query>");
128
+ }
129
+
130
+ // Determine source and query
131
+ let source: string | undefined;
132
+ let query: string;
133
+
134
+ if (positional.length === 1) {
135
+ query = positional[0];
136
+ } else {
137
+ source = positional[0];
138
+ query = positional.slice(1).join(" ");
139
+ }
140
+
141
+ const limit = parsed.has("limit") ? parseInt(parsed.get("limit")!, 10) : 20;
142
+ const since = parsed.get("since");
143
+
144
+ try {
145
+ const results = search(query, { source, limit, since });
146
+ output({
147
+ success: true,
148
+ results,
149
+ count: results.length,
150
+ });
151
+ console.error(
152
+ `✅ ${results.length} result${results.length !== 1 ? "s" : ""} found`,
153
+ );
154
+ process.exit(0);
155
+ } catch (error) {
156
+ const message = error instanceof Error ? error.message : "Unknown error";
157
+ fail(message, 2);
158
+ }
159
+ }
160
+
161
+ // ============================================================================
162
+ // List Command
163
+ // ============================================================================
164
+
165
+ function formatHumanOutput(result: ListResult): string {
166
+ const lines: string[] = [`${result.domain} (${result.count} entries):`, ""];
167
+
168
+ for (const entry of result.entries) {
169
+ lines.push(` ${entry.title}`);
170
+ if (entry.metadata.description) {
171
+ lines.push(` ${entry.metadata.description}`);
172
+ }
173
+ }
174
+
175
+ return lines.join("\n");
176
+ }
177
+
178
+ function handleList(args: string[]): void {
179
+ const parsed = parseArgs(args);
180
+ const positional = getPositionalArgs(args);
181
+
182
+ // Handle --domains flag
183
+ if (hasFlag(args, "domains")) {
184
+ output({ success: true, domains: listDomains() });
185
+ console.error(`✅ ${DOMAINS.length} domains available`);
186
+ process.exit(0);
187
+ }
188
+
189
+ if (positional.length === 0) {
190
+ fail(`Missing domain. Available: ${DOMAINS.join(", ")}`);
191
+ }
192
+
193
+ const domain = positional[0] as Domain;
194
+
195
+ if (!DOMAINS.includes(domain)) {
196
+ fail(`Invalid domain: ${domain}. Available: ${DOMAINS.join(", ")}`);
197
+ }
198
+
199
+ const limit = parsed.has("limit")
200
+ ? parseInt(parsed.get("limit")!, 10)
201
+ : undefined;
202
+ const format = parsed.get("format") || "json";
203
+
204
+ try {
205
+ const result = list(domain, { limit });
206
+
207
+ if (format === "human") {
208
+ console.log(formatHumanOutput(result));
209
+ } else if (format === "jsonl") {
210
+ for (const entry of result.entries) {
211
+ console.log(JSON.stringify(entry));
212
+ }
213
+ } else {
214
+ output({
215
+ success: true,
216
+ domain: result.domain,
217
+ entries: result.entries,
218
+ count: result.count,
219
+ });
220
+ }
221
+
222
+ console.error(`✅ ${result.count} entries in ${domain}`);
223
+ process.exit(0);
224
+ } catch (error) {
225
+ const message = error instanceof Error ? error.message : "Unknown error";
226
+ fail(message, 2);
227
+ }
228
+ }
229
+
230
+ // ============================================================================
231
+ // Capture Command
232
+ // ============================================================================
233
+
234
+ function handleCaptureTask(args: string[]): void {
235
+ const parsed = parseArgs(args);
236
+
237
+ const required = ["project", "name", "problem", "solution"];
238
+ const missing = required.filter((f) => !parsed.has(f));
239
+ if (missing.length > 0) {
240
+ fail(`Missing required fields: ${missing.join(", ")}`);
241
+ }
242
+
243
+ const input: TaskInput = {
244
+ project: parsed.get("project")!,
245
+ name: parsed.get("name")!,
246
+ problem: parsed.get("problem")!,
247
+ solution: parsed.get("solution")!,
248
+ code: parsed.get("code"),
249
+ discoveries: parseList(parsed.get("discoveries")),
250
+ deviations: parsed.get("deviations"),
251
+ pattern: parsed.get("pattern"),
252
+ keywords: parseList(parsed.get("keywords")),
253
+ tech: parseList(parsed.get("tech")),
254
+ difficulty: parsed.get("difficulty"),
255
+ };
256
+
257
+ const result = captureTask(input);
258
+ output(result);
259
+
260
+ if (result.success) {
261
+ console.error("✅ Task logged");
262
+ process.exit(0);
263
+ } else {
264
+ console.error(`❌ ${result.error}`);
265
+ process.exit(2);
266
+ }
267
+ }
268
+
269
+ function handleCaptureKnowledge(args: string[]): void {
270
+ const parsed = parseArgs(args);
271
+
272
+ const required = ["context", "text", "type"];
273
+ const missing = required.filter((f) => !parsed.has(f));
274
+ if (missing.length > 0) {
275
+ fail(`Missing required fields: ${missing.join(", ")}`);
276
+ }
277
+
278
+ const input: KnowledgeInput = {
279
+ context: parsed.get("context")!,
280
+ text: parsed.get("text")!,
281
+ type: parsed.get("type")! as KnowledgeCaptureType,
282
+ };
283
+
284
+ const result = captureKnowledge(input);
285
+ output(result);
286
+
287
+ if (result.success) {
288
+ console.error("✅ Knowledge logged");
289
+ process.exit(0);
290
+ } else {
291
+ console.error(`❌ ${result.error}`);
292
+ process.exit(1);
293
+ }
294
+ }
295
+
296
+ function handleCaptureNote(args: string[]): void {
297
+ const parsed = parseArgs(args);
298
+
299
+ if (!parsed.has("text")) {
300
+ fail("Missing required field: text");
301
+ }
302
+
303
+ const input: NoteInput = {
304
+ text: parsed.get("text")!,
305
+ tags: parseList(parsed.get("tags")),
306
+ context: parsed.get("context"),
307
+ };
308
+
309
+ const result = captureNote(input);
310
+ output(result);
311
+
312
+ if (result.success) {
313
+ console.error("✅ Note logged");
314
+ process.exit(0);
315
+ } else {
316
+ console.error(`❌ ${result.error}`);
317
+ process.exit(2);
318
+ }
319
+ }
320
+
321
+ function handleCapture(args: string[]): void {
322
+ if (args.length === 0) {
323
+ fail("Missing capture type. Use: task, knowledge, or note");
324
+ }
325
+
326
+ const captureType = args[0];
327
+ const captureArgs = args.slice(1);
328
+
329
+ switch (captureType) {
330
+ case "task":
331
+ handleCaptureTask(captureArgs);
332
+ break;
333
+ case "knowledge":
334
+ handleCaptureKnowledge(captureArgs);
335
+ break;
336
+ case "note":
337
+ handleCaptureNote(captureArgs);
338
+ break;
339
+ default:
340
+ fail(
341
+ `Unknown capture type: ${captureType}. Use: task, knowledge, or note`,
342
+ );
343
+ }
344
+ }
345
+
346
+ // ============================================================================
347
+ // Help & Main
348
+ // ============================================================================
349
+
350
+ function showHelp(): void {
351
+ console.log(`
352
+ lore - Unified knowledge CLI
353
+
354
+ Philosophy:
355
+ Single entry point for your knowledge fabric.
356
+ Search, list, and capture indexed knowledge.
357
+ JSON output for composability with jq, grep, etc.
358
+
359
+ Usage:
360
+ lore search <query> Search all sources
361
+ lore search <source> <query> Search specific source
362
+ lore search --sources List indexed sources
363
+ lore list <domain> List domain entries
364
+ lore list --domains List available domains
365
+ lore capture task|knowledge|note Capture knowledge
366
+
367
+ Search Options:
368
+ --limit <n> Maximum results (default: 20)
369
+ --since <date> Filter by date (today, yesterday, this-week, YYYY-MM-DD)
370
+ --sources List indexed sources with counts
371
+
372
+ List Options:
373
+ --limit <n> Maximum entries
374
+ --format <fmt> Output format: json (default), jsonl, human
375
+ --domains List available domains
376
+
377
+ Capture Types:
378
+ task Log task completion
379
+ --project Project name (required)
380
+ --name Task name (required)
381
+ --problem Problem solved (required)
382
+ --solution Solution pattern (required)
383
+
384
+ knowledge Log insight
385
+ --context Context/project name (required)
386
+ --text Insight text (required)
387
+ --type Type: decision, learning, gotcha, preference (required)
388
+
389
+ note Quick note
390
+ --text Note content (required)
391
+ --tags Comma-separated tags
392
+ --context Optional context
393
+
394
+ Examples:
395
+ lore search "authentication"
396
+ lore search blogs "typescript patterns"
397
+ lore list development
398
+ lore list commits --limit 10 --format human
399
+ lore capture knowledge --context=lore --text="Unified CLI works" --type=learning
400
+ `);
401
+ process.exit(0);
402
+ }
403
+
404
+ function main(): void {
405
+ const args = process.argv.slice(2);
406
+
407
+ if (args.length === 0 || hasFlag(args, "help") || args[0] === "-h") {
408
+ showHelp();
409
+ }
410
+
411
+ const command = args[0];
412
+ const commandArgs = args.slice(1);
413
+
414
+ switch (command) {
415
+ case "search":
416
+ handleSearch(commandArgs);
417
+ break;
418
+ case "list":
419
+ handleList(commandArgs);
420
+ break;
421
+ case "capture":
422
+ handleCapture(commandArgs);
423
+ break;
424
+ case "--help":
425
+ case "-h":
426
+ showHelp();
427
+ break;
428
+ default:
429
+ fail(`Unknown command: ${command}. Use: search, list, or capture`);
430
+ }
431
+ }
432
+
433
+ main();
package/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * lore - Library exports
3
+ *
4
+ * Unified knowledge CLI: search, list, and capture indexed knowledge.
5
+ * Self-contained package with zero workspace dependencies.
6
+ *
7
+ * Usage:
8
+ * import { search, list, captureKnowledge } from "lore";
9
+ */
10
+
11
+ // Search
12
+ export {
13
+ search,
14
+ listSources,
15
+ type SearchResult,
16
+ type SearchOptions,
17
+ } from "./lib/search";
18
+
19
+ // List
20
+ export {
21
+ list,
22
+ listDomains,
23
+ DOMAINS,
24
+ type Domain,
25
+ type ListOptions,
26
+ type ListEntry,
27
+ type ListResult,
28
+ } from "./lib/list";
29
+
30
+ // Capture
31
+ export {
32
+ captureKnowledge,
33
+ captureTask,
34
+ captureNote,
35
+ type CaptureResult,
36
+ type KnowledgeInput,
37
+ type KnowledgeCaptureType,
38
+ type TaskInput,
39
+ type NoteInput,
40
+ type CaptureEvent,
41
+ } from "./lib/capture";
package/lib/capture.ts ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * lib/capture.ts - Knowledge capture functions
3
+ *
4
+ * Pure functions for capturing tasks, insights, and notes.
5
+ * Writes to ~/.local/share/lore/log.jsonl
6
+ */
7
+
8
+ import { appendFileSync, mkdirSync, existsSync } from "fs";
9
+ import { join } from "path";
10
+ import { homedir } from "os";
11
+
12
+ export interface CaptureResult {
13
+ success: boolean;
14
+ error?: string;
15
+ }
16
+
17
+ export type KnowledgeCaptureType =
18
+ | "project"
19
+ | "conversation"
20
+ | "decision"
21
+ | "learning"
22
+ | "gotcha"
23
+ | "preference"
24
+ | "knowledge";
25
+
26
+ export interface KnowledgeInput {
27
+ context: string;
28
+ text: string;
29
+ type: KnowledgeCaptureType;
30
+ }
31
+
32
+ export interface TaskInput {
33
+ project: string;
34
+ name: string;
35
+ problem: string;
36
+ solution: string;
37
+ code?: string;
38
+ discoveries?: string[];
39
+ deviations?: string;
40
+ pattern?: string;
41
+ keywords?: string[];
42
+ tech?: string[];
43
+ difficulty?: string;
44
+ }
45
+
46
+ export interface NoteInput {
47
+ text: string;
48
+ tags?: string[];
49
+ context?: string;
50
+ }
51
+
52
+ interface TaskEvent {
53
+ event: "captured";
54
+ type: "task";
55
+ timestamp: string;
56
+ data: {
57
+ project: string;
58
+ task_name: string;
59
+ problem_solved: string;
60
+ solution_pattern: string;
61
+ code_snippet?: string;
62
+ discoveries?: string[];
63
+ deviations?: string;
64
+ reusable_pattern?: string;
65
+ keywords?: string[];
66
+ tech_used?: string[];
67
+ difficulty_notes?: string;
68
+ };
69
+ }
70
+
71
+ interface KnowledgeEvent {
72
+ event: "captured";
73
+ type: "knowledge";
74
+ timestamp: string;
75
+ data: {
76
+ context: string;
77
+ capture: string;
78
+ type: KnowledgeCaptureType;
79
+ };
80
+ }
81
+
82
+ interface NoteEvent {
83
+ event: "captured";
84
+ type: "note";
85
+ timestamp: string;
86
+ data: {
87
+ content: string;
88
+ tags?: string[];
89
+ context?: string;
90
+ };
91
+ }
92
+
93
+ type CaptureEvent = TaskEvent | KnowledgeEvent | NoteEvent;
94
+
95
+ function getLogPath(): string {
96
+ const dataHome =
97
+ process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
98
+ return join(dataHome, "lore", "log.jsonl");
99
+ }
100
+
101
+ function ensureLogDirectory(): void {
102
+ const logPath = getLogPath();
103
+ const logDir = join(logPath, "..");
104
+
105
+ if (!existsSync(logDir)) {
106
+ mkdirSync(logDir, { recursive: true });
107
+ }
108
+ }
109
+
110
+ function getTimestamp(): string {
111
+ return new Date().toISOString();
112
+ }
113
+
114
+ function writeEvent(event: CaptureEvent): CaptureResult {
115
+ ensureLogDirectory();
116
+
117
+ const logPath = getLogPath();
118
+ const eventWithTimestamp = { ...event, timestamp: getTimestamp() };
119
+ const jsonLine = JSON.stringify(eventWithTimestamp) + "\n";
120
+
121
+ try {
122
+ appendFileSync(logPath, jsonLine, "utf8");
123
+ return { success: true };
124
+ } catch (error) {
125
+ return {
126
+ success: false,
127
+ error: `Failed to write event to ${logPath}: ${error}`,
128
+ };
129
+ }
130
+ }
131
+
132
+ const VALID_KNOWLEDGE_TYPES: KnowledgeCaptureType[] = [
133
+ "project",
134
+ "conversation",
135
+ "decision",
136
+ "learning",
137
+ "gotcha",
138
+ "preference",
139
+ "knowledge",
140
+ ];
141
+
142
+ /**
143
+ * Capture a knowledge insight
144
+ */
145
+ export function captureKnowledge(input: KnowledgeInput): CaptureResult {
146
+ if (!VALID_KNOWLEDGE_TYPES.includes(input.type)) {
147
+ return {
148
+ success: false,
149
+ error: `Invalid type: ${input.type}. Must be one of: ${VALID_KNOWLEDGE_TYPES.join(", ")}`,
150
+ };
151
+ }
152
+
153
+ const event: KnowledgeEvent = {
154
+ event: "captured",
155
+ type: "knowledge",
156
+ timestamp: "",
157
+ data: {
158
+ context: input.context,
159
+ capture: input.text,
160
+ type: input.type,
161
+ },
162
+ };
163
+
164
+ return writeEvent(event);
165
+ }
166
+
167
+ /**
168
+ * Capture a task completion
169
+ */
170
+ export function captureTask(input: TaskInput): CaptureResult {
171
+ const event: TaskEvent = {
172
+ event: "captured",
173
+ type: "task",
174
+ timestamp: "",
175
+ data: {
176
+ project: input.project,
177
+ task_name: input.name,
178
+ problem_solved: input.problem,
179
+ solution_pattern: input.solution,
180
+ code_snippet: input.code,
181
+ discoveries: input.discoveries,
182
+ deviations: input.deviations,
183
+ reusable_pattern: input.pattern,
184
+ keywords: input.keywords,
185
+ tech_used: input.tech,
186
+ difficulty_notes: input.difficulty,
187
+ },
188
+ };
189
+
190
+ return writeEvent(event);
191
+ }
192
+
193
+ /**
194
+ * Capture a quick note
195
+ */
196
+ export function captureNote(input: NoteInput): CaptureResult {
197
+ const event: NoteEvent = {
198
+ event: "captured",
199
+ type: "note",
200
+ timestamp: "",
201
+ data: {
202
+ content: input.text,
203
+ tags: input.tags,
204
+ context: input.context,
205
+ },
206
+ };
207
+
208
+ return writeEvent(event);
209
+ }
210
+
211
+ export type { CaptureEvent };
package/lib/list.ts ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * lib/list.ts - Domain listing functions
3
+ *
4
+ * Browse indexed domains without search queries.
5
+ * Uses Bun's built-in SQLite for zero external dependencies.
6
+ */
7
+
8
+ import { Database } from "bun:sqlite";
9
+ import { homedir } from "os";
10
+ import { existsSync } from "fs";
11
+
12
+ // Domain types - sources that can be listed
13
+ export type Domain =
14
+ | "development"
15
+ | "tasks"
16
+ | "events"
17
+ | "blogs"
18
+ | "commits"
19
+ | "explorations"
20
+ | "readmes"
21
+ | "obsidian"
22
+ | "captures"
23
+ | "books"
24
+ | "movies"
25
+ | "podcasts"
26
+ | "interests"
27
+ | "people"
28
+ | "habits";
29
+
30
+ export const DOMAINS: Domain[] = [
31
+ "development",
32
+ "tasks",
33
+ "events",
34
+ "blogs",
35
+ "commits",
36
+ "explorations",
37
+ "readmes",
38
+ "obsidian",
39
+ "captures",
40
+ "books",
41
+ "movies",
42
+ "podcasts",
43
+ "interests",
44
+ "people",
45
+ "habits",
46
+ ];
47
+
48
+ // Domains that query the 'personal' source with type filter
49
+ const PERSONAL_SUBTYPES: Partial<Record<Domain, string>> = {
50
+ books: "book",
51
+ movies: "movie",
52
+ podcasts: "podcast",
53
+ interests: "interest",
54
+ people: "person",
55
+ habits: "habit",
56
+ };
57
+
58
+ export interface ListOptions {
59
+ limit?: number;
60
+ }
61
+
62
+ export interface ListEntry {
63
+ title: string;
64
+ content: string;
65
+ metadata: Record<string, unknown>;
66
+ }
67
+
68
+ export interface ListResult {
69
+ domain: Domain;
70
+ entries: ListEntry[];
71
+ count: number;
72
+ }
73
+
74
+ // Database path following XDG spec
75
+ function getDatabasePath(): string {
76
+ return `${homedir()}/.local/share/lore/lore.db`;
77
+ }
78
+
79
+ interface RawRow {
80
+ title: string;
81
+ content: string;
82
+ metadata: string;
83
+ }
84
+
85
+ /**
86
+ * Query entries by source
87
+ */
88
+ function queryBySource(
89
+ db: Database,
90
+ source: string,
91
+ limit?: number,
92
+ ): ListEntry[] {
93
+ const sql = limit
94
+ ? `SELECT title, content, metadata FROM search WHERE source = ? LIMIT ?`
95
+ : `SELECT title, content, metadata FROM search WHERE source = ?`;
96
+
97
+ const stmt = limit ? db.prepare(sql) : db.prepare(sql);
98
+ const rows = (limit ? stmt.all(source, limit) : stmt.all(source)) as RawRow[];
99
+
100
+ return rows.map((row) => ({
101
+ title: row.title,
102
+ content: row.content,
103
+ metadata: JSON.parse(row.metadata || "{}"),
104
+ }));
105
+ }
106
+
107
+ /**
108
+ * Query personal entries by subtype
109
+ */
110
+ function queryPersonalType(
111
+ db: Database,
112
+ type: string,
113
+ limit?: number,
114
+ ): ListEntry[] {
115
+ // Query personal source, then filter by type in metadata
116
+ const sql = limit
117
+ ? `SELECT title, content, metadata FROM search WHERE source = 'personal' LIMIT ?`
118
+ : `SELECT title, content, metadata FROM search WHERE source = 'personal'`;
119
+
120
+ const stmt = db.prepare(sql);
121
+ const rows = (limit ? stmt.all(limit * 10) : stmt.all()) as RawRow[]; // Over-fetch for filtering
122
+
123
+ const filtered = rows
124
+ .map((row) => ({
125
+ title: row.title,
126
+ content: row.content,
127
+ metadata: JSON.parse(row.metadata || "{}"),
128
+ }))
129
+ .filter((entry) => entry.metadata.type === type);
130
+
131
+ return limit ? filtered.slice(0, limit) : filtered;
132
+ }
133
+
134
+ /**
135
+ * List all entries in a domain
136
+ *
137
+ * @param domain - The domain to list (development, tasks, blogs, etc.)
138
+ * @param options - Optional limit
139
+ * @returns ListResult with entries and count
140
+ * @throws Error if database doesn't exist or domain is invalid
141
+ */
142
+ export function list(domain: Domain, options: ListOptions = {}): ListResult {
143
+ if (!DOMAINS.includes(domain)) {
144
+ throw new Error(
145
+ `Invalid domain: ${domain}. Valid domains: ${DOMAINS.join(", ")}`,
146
+ );
147
+ }
148
+
149
+ const dbPath = getDatabasePath();
150
+
151
+ if (!existsSync(dbPath)) {
152
+ throw new Error(`Database not found: ${dbPath}. Run lore-index-all first.`);
153
+ }
154
+
155
+ const db = new Database(dbPath, { readonly: true });
156
+
157
+ try {
158
+ let entries: ListEntry[];
159
+
160
+ // Check if this is a personal subtype domain
161
+ const personalType = PERSONAL_SUBTYPES[domain];
162
+ if (personalType) {
163
+ entries = queryPersonalType(db, personalType, options.limit);
164
+ } else {
165
+ entries = queryBySource(db, domain, options.limit);
166
+ }
167
+
168
+ return {
169
+ domain,
170
+ entries,
171
+ count: entries.length,
172
+ };
173
+ } finally {
174
+ db.close();
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Get available domains
180
+ */
181
+ export function listDomains(): Domain[] {
182
+ return [...DOMAINS];
183
+ }
package/lib/search.ts ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * lib/search.ts - SQLite FTS5 query functions
3
+ *
4
+ * Pure functions for querying the Lore FTS5 database.
5
+ * Uses Bun's built-in SQLite for zero external dependencies.
6
+ */
7
+
8
+ import { Database } from "bun:sqlite";
9
+ import { homedir } from "os";
10
+ import { existsSync } from "fs";
11
+
12
+ export interface SearchResult {
13
+ source: string;
14
+ title: string;
15
+ content: string;
16
+ metadata: string;
17
+ rank: number;
18
+ }
19
+
20
+ export interface SearchOptions {
21
+ source?: string;
22
+ limit?: number;
23
+ since?: string;
24
+ }
25
+
26
+ function getDatabasePath(): string {
27
+ return `${homedir()}/.local/share/lore/lore.db`;
28
+ }
29
+
30
+ /**
31
+ * Search the Lore FTS5 database
32
+ *
33
+ * @param query - FTS5 search query (supports AND, OR, NOT, phrases)
34
+ * @param options - Optional source filter and result limit
35
+ * @returns Array of search results ranked by relevance
36
+ * @throws Error if database doesn't exist or query fails
37
+ */
38
+ export function search(
39
+ query: string,
40
+ options: SearchOptions = {},
41
+ ): SearchResult[] {
42
+ const dbPath = getDatabasePath();
43
+
44
+ if (!existsSync(dbPath)) {
45
+ throw new Error(`Database not found: ${dbPath}. Run lore-db-init first.`);
46
+ }
47
+
48
+ const db = new Database(dbPath, { readonly: true });
49
+
50
+ try {
51
+ const limit = options.limit ?? 20;
52
+
53
+ const conditions: string[] = ["search MATCH ?"];
54
+ const params: (string | number)[] = [query];
55
+
56
+ if (options.source) {
57
+ conditions.push("source = ?");
58
+ params.push(options.source);
59
+ }
60
+
61
+ if (options.since) {
62
+ conditions.push(
63
+ "json_extract(metadata, '$.date') IS NOT NULL AND json_extract(metadata, '$.date') != 'unknown' AND json_extract(metadata, '$.date') >= ?",
64
+ );
65
+ params.push(options.since);
66
+ }
67
+
68
+ params.push(limit);
69
+
70
+ const sql = `
71
+ SELECT source, title, snippet(search, 2, '→', '←', '...', 32) as content, metadata, rank
72
+ FROM search
73
+ WHERE ${conditions.join(" AND ")}
74
+ ORDER BY rank
75
+ LIMIT ?
76
+ `;
77
+
78
+ const stmt = db.prepare(sql);
79
+ const results = stmt.all(...params) as SearchResult[];
80
+
81
+ return results;
82
+ } finally {
83
+ db.close();
84
+ }
85
+ }
86
+
87
+ /**
88
+ * List all available sources in the database
89
+ *
90
+ * @returns Array of source names with entry counts
91
+ */
92
+ export function listSources(): { source: string; count: number }[] {
93
+ const dbPath = getDatabasePath();
94
+
95
+ if (!existsSync(dbPath)) {
96
+ throw new Error(`Database not found: ${dbPath}. Run lore-db-init first.`);
97
+ }
98
+
99
+ const db = new Database(dbPath, { readonly: true });
100
+
101
+ try {
102
+ const stmt = db.prepare(`
103
+ SELECT source, COUNT(*) as count
104
+ FROM search
105
+ GROUP BY source
106
+ ORDER BY count DESC
107
+ `);
108
+ return stmt.all() as { source: string; count: number }[];
109
+ } finally {
110
+ db.close();
111
+ }
112
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@voidwire/lore",
3
+ "version": "0.1.0",
4
+ "description": "Unified knowledge CLI - Search, list, and capture your indexed knowledge",
5
+ "type": "module",
6
+ "main": "./index.ts",
7
+ "bin": {
8
+ "lore": "./cli.ts"
9
+ },
10
+ "exports": {
11
+ ".": "./index.ts",
12
+ "./cli": "./cli.ts"
13
+ },
14
+ "files": [
15
+ "index.ts",
16
+ "cli.ts",
17
+ "lib/**/*.ts",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "test": "bun test"
23
+ },
24
+ "keywords": [
25
+ "knowledge",
26
+ "search",
27
+ "capture",
28
+ "fts5",
29
+ "sqlite",
30
+ "cli",
31
+ "llcli"
32
+ ],
33
+ "author": "nickpending <nickpending@users.noreply.github.com>",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/nickpending/llmcli-tools.git",
38
+ "directory": "packages/lore"
39
+ },
40
+ "homepage": "https://github.com/nickpending/llmcli-tools/tree/main/packages/lore#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/nickpending/llmcli-tools/issues"
43
+ },
44
+ "engines": {
45
+ "bun": ">=1.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "bun-types": "latest"
49
+ }
50
+ }