aiwcli 0.12.2 → 0.12.3

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 (34) hide show
  1. package/dist/templates/_shared/.claude/commands/handoff.md +44 -78
  2. package/dist/templates/_shared/hooks-ts/session_end.ts +16 -11
  3. package/dist/templates/_shared/hooks-ts/session_start.ts +4 -1
  4. package/dist/templates/_shared/lib-ts/base/inference.ts +72 -23
  5. package/dist/templates/_shared/lib-ts/base/state-io.ts +12 -7
  6. package/dist/templates/_shared/lib-ts/context/context-store.ts +35 -74
  7. package/dist/templates/_shared/lib-ts/types.ts +64 -63
  8. package/dist/templates/_shared/scripts/resolve_context.ts +14 -5
  9. package/dist/templates/_shared/scripts/resume_handoff.ts +16 -13
  10. package/dist/templates/_shared/scripts/save_handoff.ts +30 -31
  11. package/dist/templates/_shared/workflows/handoff.md +28 -6
  12. package/dist/templates/cc-native/.claude/commands/rlm/ask.md +136 -0
  13. package/dist/templates/cc-native/.claude/commands/rlm/index.md +21 -0
  14. package/dist/templates/cc-native/.claude/commands/rlm/overview.md +56 -0
  15. package/dist/templates/cc-native/TEMPLATE-SCHEMA.md +4 -4
  16. package/dist/templates/cc-native/_cc-native/{plan-review.config.json → cc-native.config.json} +12 -0
  17. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.ts +1 -1
  18. package/dist/templates/cc-native/_cc-native/lib-ts/config.ts +3 -3
  19. package/dist/templates/cc-native/_cc-native/lib-ts/review-pipeline.ts +26 -4
  20. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/CLAUDE.md +480 -0
  21. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/embedding-indexer.ts +287 -0
  22. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/hyde.ts +148 -0
  23. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/index.ts +54 -0
  24. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/logger.ts +58 -0
  25. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/ollama-client.ts +208 -0
  26. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/retrieval-pipeline.ts +460 -0
  27. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-indexer.ts +447 -0
  28. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-loader.ts +280 -0
  29. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-searcher.ts +274 -0
  30. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/types.ts +201 -0
  31. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/vector-store.ts +278 -0
  32. package/dist/templates/cc-native/_cc-native/lib-ts/types.ts +2 -1
  33. package/oclif.manifest.json +1 -1
  34. package/package.json +1 -1
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TranscriptLoader — Loads and formats transcript segments for deep reading.
4
+ *
5
+ * Given a session JSONL file path + optional line range, streams the file,
6
+ * filters to human-readable content (user + assistant messages), summarizes
7
+ * tool calls, and truncates to ~50K chars max.
8
+ *
9
+ * Usage:
10
+ * bun transcript-loader.ts <jsonl-path>
11
+ * bun transcript-loader.ts <jsonl-path> --lines=46-120
12
+ */
13
+
14
+ import { createReadStream } from "fs";
15
+ import { createInterface } from "readline";
16
+ import { basename } from "path";
17
+ import { MAX_LOADER_CHARS, type LoadedSegment } from "./types.js";
18
+ import { logInfo, logWarn, logError } from "./logger.js";
19
+
20
+ const HOOK_NAME = "rlm_loader";
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // CLI entry
24
+ // ---------------------------------------------------------------------------
25
+
26
+ const args = process.argv.slice(2);
27
+ const jsonlPath = args.find((a) => !a.startsWith("--"));
28
+ const linesArg = args.find((a) => a.startsWith("--lines="));
29
+ let lineRange: [number, number] | null = null;
30
+ if (linesArg) {
31
+ const [start, end] = linesArg.split("=")[1].split("-").map(Number);
32
+ if (!isNaN(start) && !isNaN(end) && start >= 1 && end >= start) {
33
+ lineRange = [start, end];
34
+ }
35
+ }
36
+
37
+ if (jsonlPath && !process.env.RLM_LIB_MODE) {
38
+ loadTranscript(jsonlPath, lineRange)
39
+ .then((seg) => {
40
+ process.stdout.write(seg.content);
41
+ if (seg.truncated) {
42
+ logInfo(HOOK_NAME, "Output truncated at 50K chars", { stderr: true });
43
+ }
44
+ })
45
+ .catch((e) => {
46
+ logError(HOOK_NAME, `Load failed: ${e}`, { stderr: true });
47
+ process.exitCode = 1;
48
+ });
49
+ }
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // Loader
53
+ // ---------------------------------------------------------------------------
54
+
55
+ async function loadTranscript(
56
+ filePath: string,
57
+ range: [number, number] | null = null,
58
+ maxChars: number = MAX_LOADER_CHARS,
59
+ ): Promise<LoadedSegment> {
60
+ const parts: string[] = [];
61
+ let totalChars = 0;
62
+ let truncated = false;
63
+ let lineNum = 0;
64
+ let sessionId = "";
65
+ let project = "";
66
+
67
+ const rl = createInterface({
68
+ input: createReadStream(filePath, { encoding: "utf-8" }),
69
+ crlfDelay: Infinity,
70
+ });
71
+
72
+ try {
73
+ for await (const line of rl) {
74
+ lineNum++;
75
+
76
+ // Skip lines outside range
77
+ if (range) {
78
+ if (lineNum < range[0]) continue;
79
+ if (lineNum > range[1]) break;
80
+ }
81
+
82
+ if (!line.trim()) continue;
83
+
84
+ let obj: Record<string, unknown>;
85
+ try {
86
+ obj = JSON.parse(line);
87
+ } catch {
88
+ continue;
89
+ }
90
+
91
+ // Capture session metadata
92
+ if (!sessionId && obj.sessionId) {
93
+ sessionId = obj.sessionId as string;
94
+ }
95
+
96
+ const type = obj.type as string | undefined;
97
+ const timestamp = obj.timestamp as string | undefined;
98
+
99
+ if (type === "user") {
100
+ const msg = obj.message as Record<string, unknown> | undefined;
101
+ if (!msg) continue;
102
+ const content = extractContent(msg);
103
+ if (!content) continue;
104
+
105
+ const formatted = formatMessage("USER", timestamp, content);
106
+ if (totalChars + formatted.length > maxChars) {
107
+ truncated = true;
108
+ break;
109
+ }
110
+ parts.push(formatted);
111
+ totalChars += formatted.length;
112
+ } else if (type === "assistant") {
113
+ const msg = obj.message as Record<string, unknown> | undefined;
114
+ if (!msg) continue;
115
+ const { text, toolUses } = extractAssistantContent(msg);
116
+
117
+ if (text || toolUses.length > 0) {
118
+ const formatted = formatAssistantMessage(timestamp, text, toolUses);
119
+ if (totalChars + formatted.length > maxChars) {
120
+ truncated = true;
121
+ // Add what we can
122
+ const remaining = maxChars - totalChars;
123
+ if (remaining > 100) {
124
+ parts.push(formatted.slice(0, remaining) + "\n... [truncated]");
125
+ }
126
+ break;
127
+ }
128
+ parts.push(formatted);
129
+ totalChars += formatted.length;
130
+ }
131
+ }
132
+ }
133
+ } finally {
134
+ rl.close();
135
+ }
136
+
137
+ // Derive project from path
138
+ const pathParts = filePath.replace(/\\/g, "/").split("/");
139
+ const projectsIdx = pathParts.indexOf("projects");
140
+ if (projectsIdx >= 0 && projectsIdx + 1 < pathParts.length) {
141
+ project = pathParts[projectsIdx + 1];
142
+ }
143
+
144
+ return {
145
+ session_id: sessionId || basename(filePath, ".jsonl"),
146
+ project,
147
+ line_range: range,
148
+ content: parts.join("\n\n"),
149
+ truncated,
150
+ };
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Content extraction
155
+ // ---------------------------------------------------------------------------
156
+
157
+ function extractContent(msg: Record<string, unknown>): string | null {
158
+ const content = msg.content;
159
+ if (typeof content === "string") return content;
160
+ if (Array.isArray(content)) {
161
+ const texts: string[] = [];
162
+ for (const block of content) {
163
+ if (typeof block === "string") {
164
+ texts.push(block);
165
+ } else if (typeof block === "object" && block !== null) {
166
+ const b = block as Record<string, unknown>;
167
+ if (b.type === "text" && typeof b.text === "string") {
168
+ texts.push(b.text);
169
+ }
170
+ // tool_result blocks — include short text content
171
+ if (b.type === "tool_result" && typeof b.content === "string") {
172
+ texts.push(`[Tool result: ${b.content.slice(0, 200)}]`);
173
+ }
174
+ }
175
+ }
176
+ return texts.length > 0 ? texts.join("\n") : null;
177
+ }
178
+ return null;
179
+ }
180
+
181
+ interface ToolUse {
182
+ name: string;
183
+ inputSummary: string;
184
+ }
185
+
186
+ function extractAssistantContent(msg: Record<string, unknown>): {
187
+ text: string;
188
+ toolUses: ToolUse[];
189
+ } {
190
+ const content = msg.content;
191
+ let text = "";
192
+ const toolUses: ToolUse[] = [];
193
+
194
+ if (typeof content === "string") {
195
+ text = content;
196
+ } else if (Array.isArray(content)) {
197
+ const texts: string[] = [];
198
+ for (const block of content) {
199
+ if (typeof block !== "object" || block === null) continue;
200
+ const b = block as Record<string, unknown>;
201
+ if (b.type === "text" && typeof b.text === "string") {
202
+ texts.push(b.text);
203
+ }
204
+ if (b.type === "tool_use") {
205
+ const name = (b.name as string) || "unknown";
206
+ const input = b.input as Record<string, unknown> | undefined;
207
+ toolUses.push({
208
+ name,
209
+ inputSummary: summarizeToolInput(name, input),
210
+ });
211
+ }
212
+ }
213
+ text = texts.join("\n");
214
+ }
215
+
216
+ return { text, toolUses };
217
+ }
218
+
219
+ function summarizeToolInput(toolName: string, input?: Record<string, unknown>): string {
220
+ if (!input) return "";
221
+ switch (toolName) {
222
+ case "Read":
223
+ return input.file_path ? `${input.file_path}` : "";
224
+ case "Write":
225
+ return input.file_path ? `${input.file_path}` : "";
226
+ case "Edit":
227
+ return input.file_path ? `${input.file_path}` : "";
228
+ case "Bash":
229
+ return input.command ? `${(input.command as string).slice(0, 80)}` : "";
230
+ case "Glob":
231
+ return input.pattern ? `${input.pattern}` : "";
232
+ case "Grep":
233
+ return input.pattern ? `/${input.pattern}/` : "";
234
+ case "Task":
235
+ return input.description ? `${input.description}` : "";
236
+ case "WebSearch":
237
+ return input.query ? `"${input.query}"` : "";
238
+ case "WebFetch":
239
+ return input.url ? `${input.url}` : "";
240
+ default:
241
+ return Object.keys(input).slice(0, 3).join(", ");
242
+ }
243
+ }
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // Formatting
247
+ // ---------------------------------------------------------------------------
248
+
249
+ function formatMessage(role: string, timestamp: string | undefined, content: string): string {
250
+ const ts = timestamp ? `[${timestamp}]` : "";
251
+ return `--- ${role} ${ts} ---\n${content}`;
252
+ }
253
+
254
+ function formatAssistantMessage(
255
+ timestamp: string | undefined,
256
+ text: string,
257
+ toolUses: ToolUse[],
258
+ ): string {
259
+ const ts = timestamp ? `[${timestamp}]` : "";
260
+ const parts: string[] = [`--- ASSISTANT ${ts} ---`];
261
+
262
+ if (text) {
263
+ parts.push(text);
264
+ }
265
+
266
+ if (toolUses.length > 0) {
267
+ const toolLines = toolUses.map(
268
+ (t) => ` -> ${t.name}${t.inputSummary ? `: ${t.inputSummary}` : ""}`
269
+ );
270
+ parts.push("Tools used:\n" + toolLines.join("\n"));
271
+ }
272
+
273
+ return parts.join("\n");
274
+ }
275
+
276
+ // ---------------------------------------------------------------------------
277
+ // Exports
278
+ // ---------------------------------------------------------------------------
279
+
280
+ export { loadTranscript };
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TranscriptSearcher — Keyword/regex search over RLM session indexes.
4
+ *
5
+ * Reads cached index files one-at-a-time from ~/.claude/rlm-index/,
6
+ * scores each against query terms, and returns ranked results.
7
+ *
8
+ * Usage:
9
+ * bun transcript-searcher.ts "plan review"
10
+ * bun transcript-searcher.ts "plan review" --top=20
11
+ * bun transcript-searcher.ts "plan review" --project=aiwcli
12
+ */
13
+
14
+ import { readdir, readFile } from "fs/promises";
15
+ import { existsSync } from "fs";
16
+ import { join } from "path";
17
+ import { logInfo, logWarn, logError, logDebug } from "./logger.js";
18
+
19
+ const HOOK_NAME = "rlm_searcher";
20
+ import {
21
+ CURRENT_SCHEMA_VERSION,
22
+ CLAUDE_PROJECTS_DIR,
23
+ RLM_INDEX_DIR,
24
+ TOP_N_HEAP,
25
+ WEIGHT,
26
+ type SessionIndex,
27
+ type SearchResult,
28
+ type IndexSegment,
29
+ } from "./types.js";
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // CLI entry
33
+ // ---------------------------------------------------------------------------
34
+
35
+ const args = process.argv.slice(2);
36
+ const query = args.find((a) => !a.startsWith("--"));
37
+ const topArg = args.find((a) => a.startsWith("--top="));
38
+ const topN = topArg ? parseInt(topArg.split("=")[1], 10) : 10;
39
+ const projectArg = args.find((a) => a.startsWith("--project="));
40
+ const projectFilter = projectArg ? projectArg.split("=")[1] : null;
41
+
42
+ if (query && !process.env.RLM_LIB_MODE) {
43
+ search(query, { topN, projectFilter })
44
+ .then((results) => {
45
+ if (typeof results === "string") {
46
+ logWarn(HOOK_NAME, results, { stderr: true });
47
+ process.exitCode = 1;
48
+ } else {
49
+ logInfo(HOOK_NAME, `Search returned ${results.length} results`);
50
+ process.stdout.write(JSON.stringify(results, null, 2) + "\n");
51
+ }
52
+ })
53
+ .catch((e) => {
54
+ logError(HOOK_NAME, `Search failed: ${e}`, { stderr: true });
55
+ process.exitCode = 1;
56
+ });
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Search
61
+ // ---------------------------------------------------------------------------
62
+
63
+ interface SearchOptions {
64
+ topN?: number;
65
+ projectFilter?: string | null;
66
+ }
67
+
68
+ async function search(
69
+ queryStr: string,
70
+ opts: SearchOptions = {},
71
+ ): Promise<SearchResult[] | string> {
72
+ const { topN = 10, projectFilter = null } = opts;
73
+
74
+ if (!existsSync(RLM_INDEX_DIR)) {
75
+ return "No indexes found. Run `/rlm:index` first to build the transcript index.";
76
+ }
77
+
78
+ const queryTerms = tokenize(queryStr);
79
+ if (queryTerms.length === 0) {
80
+ return "Query is empty after tokenization.";
81
+ }
82
+
83
+ // Build optional regex from query
84
+ let queryRegex: RegExp | null = null;
85
+ try {
86
+ queryRegex = new RegExp(queryStr, "i");
87
+ } catch {
88
+ // Not a valid regex — fall back to keyword-only matching
89
+ }
90
+
91
+ const heap: SearchResult[] = [];
92
+ let indexCount = 0;
93
+
94
+ let projectDirs: string[];
95
+ try {
96
+ projectDirs = await readdir(RLM_INDEX_DIR);
97
+ } catch {
98
+ return "Cannot read index directory.";
99
+ }
100
+
101
+ for (const project of projectDirs) {
102
+ if (projectFilter && !project.toLowerCase().includes(projectFilter.toLowerCase())) {
103
+ continue;
104
+ }
105
+
106
+ const projectPath = join(RLM_INDEX_DIR, project);
107
+ let files: string[];
108
+ try {
109
+ files = await readdir(projectPath);
110
+ } catch {
111
+ continue;
112
+ }
113
+
114
+ for (const file of files) {
115
+ if (!file.endsWith(".index.json")) continue;
116
+
117
+ let idx: SessionIndex;
118
+ try {
119
+ const raw = await readFile(join(projectPath, file), "utf-8");
120
+ idx = JSON.parse(raw) as SessionIndex;
121
+ } catch {
122
+ continue;
123
+ }
124
+
125
+ // Skip stale schema
126
+ if (idx.schema_version !== CURRENT_SCHEMA_VERSION) continue;
127
+
128
+ indexCount++;
129
+ const { score, matchingSegments } = scoreIndex(idx, queryTerms, queryRegex);
130
+
131
+ if (score > 0) {
132
+ const sessionId = file.replace(".index.json", "");
133
+ const sourcePath = join(CLAUDE_PROJECTS_DIR, project, `${sessionId}.jsonl`);
134
+ const result: SearchResult = {
135
+ session_id: idx.session_id || sessionId,
136
+ project: idx.project || project,
137
+ date: idx.date,
138
+ summary: idx.summary,
139
+ score,
140
+ matching_segments: matchingSegments,
141
+ source_path: sourcePath,
142
+ source_exists: existsSync(sourcePath),
143
+ index_path: join(projectPath, file),
144
+ };
145
+
146
+ insertSorted(heap, result, TOP_N_HEAP);
147
+ }
148
+ }
149
+ }
150
+
151
+ if (indexCount === 0) {
152
+ return "No indexes found. Run `/rlm:index` first to build the transcript index.";
153
+ }
154
+
155
+ return heap.slice(0, topN);
156
+ }
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // Scoring
160
+ // ---------------------------------------------------------------------------
161
+
162
+ /** Max segment score contribution per query term to prevent inflation. */
163
+ const MAX_SEGMENT_HITS_PER_TERM = 2;
164
+
165
+ function scoreIndex(
166
+ idx: SessionIndex,
167
+ queryTerms: string[],
168
+ queryRegex: RegExp | null,
169
+ ): { score: number; matchingSegments: IndexSegment[] } {
170
+ let score = 0;
171
+ const matchingSegments: IndexSegment[] = [];
172
+
173
+ for (const term of queryTerms) {
174
+ // Summary
175
+ if (idx.summary.toLowerCase().includes(term)) {
176
+ score += WEIGHT.summary;
177
+ }
178
+
179
+ // Keywords
180
+ for (const kw of idx.keywords) {
181
+ if (kw.includes(term)) {
182
+ score += WEIGHT.keywords;
183
+ break;
184
+ }
185
+ }
186
+
187
+ // Files touched
188
+ for (const f of idx.files_touched) {
189
+ if (f.toLowerCase().includes(term)) {
190
+ score += WEIGHT.filesTouched;
191
+ break;
192
+ }
193
+ }
194
+
195
+ // Commands
196
+ for (const cmd of idx.commands_run) {
197
+ if (cmd.toLowerCase().includes(term)) {
198
+ score += WEIGHT.commandsRun;
199
+ break;
200
+ }
201
+ }
202
+
203
+ // Tool calls
204
+ for (const tool of idx.tool_calls) {
205
+ if (tool.toLowerCase().includes(term)) {
206
+ score += WEIGHT.toolCalls;
207
+ break;
208
+ }
209
+ }
210
+
211
+ // Segments — score and collect matching, capped per term
212
+ let segHits = 0;
213
+ for (const seg of idx.segments) {
214
+ if (segHits >= MAX_SEGMENT_HITS_PER_TERM) break;
215
+ const segMatch =
216
+ seg.topic.toLowerCase().includes(term) ||
217
+ seg.keywords.some((k) => k.includes(term));
218
+ if (segMatch) {
219
+ score += WEIGHT.segmentTopic;
220
+ segHits++;
221
+ if (!matchingSegments.includes(seg)) {
222
+ matchingSegments.push(seg);
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ // Regex bonus on summary
229
+ if (queryRegex && queryRegex.test(idx.summary)) {
230
+ score += WEIGHT.summary * 0.5;
231
+ }
232
+
233
+ // Recency boost: sessions from last 7 days get 1.5x, last 30 days 1.2x
234
+ if (idx.first_timestamp) {
235
+ const ageMs = Date.now() - new Date(idx.first_timestamp).getTime();
236
+ if (!isNaN(ageMs)) {
237
+ const ageDays = ageMs / (1000 * 60 * 60 * 24);
238
+ if (ageDays < 7) score *= 1.5;
239
+ else if (ageDays < 30) score *= 1.2;
240
+ }
241
+ }
242
+
243
+ return { score, matchingSegments: matchingSegments.slice(0, 5) };
244
+ }
245
+
246
+ // ---------------------------------------------------------------------------
247
+ // Tokenization
248
+ // ---------------------------------------------------------------------------
249
+
250
+ function tokenize(query: string): string[] {
251
+ return query
252
+ .toLowerCase()
253
+ .split(/\s+/)
254
+ .map((t) => t.replace(/[^a-z0-9_-]/g, ""))
255
+ .filter((t) => t.length >= 2);
256
+ }
257
+
258
+ // ---------------------------------------------------------------------------
259
+ // Sorted insertion (descending by score, capped at maxSize)
260
+ // ---------------------------------------------------------------------------
261
+
262
+ function insertSorted(arr: SearchResult[], item: SearchResult, maxSize: number): void {
263
+ // Find insertion point (descending order)
264
+ let i = 0;
265
+ while (i < arr.length && arr[i].score >= item.score) i++;
266
+ arr.splice(i, 0, item);
267
+ if (arr.length > maxSize) arr.pop();
268
+ }
269
+
270
+ // ---------------------------------------------------------------------------
271
+ // Exports
272
+ // ---------------------------------------------------------------------------
273
+
274
+ export { search, scoreIndex, tokenize, type SearchOptions };