cheatingkit 0.0.0-stage → 0.0.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/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # ck
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CheatingKit local session CLI. Install Bun, then run `bun add -g cheatingkit@0.0.0`. The command is `ck`.
4
+
5
+ Release: 0.0.0; build: 0.0.0.5; commit: fc94ac0.
package/bin/ck.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ import "../src/cli/index.ts"
@@ -0,0 +1,35 @@
1
+ version: 1
2
+ database:
3
+ path: ~/.cheatingkit/sessions.db
4
+ journalMode: WAL
5
+ harnesses:
6
+ claudeCode:
7
+ enabled: true
8
+ path: ~/.claude/projects
9
+ codex:
10
+ enabled: true
11
+ path: ~/.codex/sessions
12
+ hermes:
13
+ enabled: true
14
+ path: ~/.hermes
15
+ models:
16
+ enabled: true
17
+ embedding:
18
+ id: Xenova/all-MiniLM-L6-v2
19
+ revision: 751bff37182d3f1213fa05d7196b954e230abad9
20
+ cachePath: ~/.cheatingkit/models/hf
21
+ dtype: q8
22
+ batchSize: 24
23
+ labels:
24
+ - coding
25
+ - cybersecurity
26
+ - malware
27
+ - privacy
28
+ - finance
29
+ - general
30
+ leadUpMessages: 4
31
+ updates:
32
+ check: true
33
+ intervalHours: 24
34
+ repository: matthewdonsemail-lab/cheatingkit
35
+ track: stable
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "cheatingkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "Local conversation index and context CLI for coding harnesses",
5
+ "type": "module",
6
+ "bin": {
7
+ "ck": "bin/ck.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src/cli",
12
+ "cheatingkit.yaml",
13
+ "release.json",
14
+ "README.md"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/matthewdonsemail-lab/cheatingkit.git"
19
+ },
20
+ "license": "MIT",
21
+ "dependencies": {
22
+ "@clack/prompts": "^1.9.0",
23
+ "@huggingface/transformers": "^4.3.2",
24
+ "@modelcontextprotocol/sdk": "^1.32.2",
25
+ "effect": "^4.1.5",
26
+ "yaml": "^2.9.1"
27
+ }
28
+ }
package/release.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "0.0.0",
3
+ "build": "0.0.0.5",
4
+ "commit": "fc94ac0",
5
+ "source": "main"
6
+ }
@@ -0,0 +1,40 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+ import YAML from 'yaml'
5
+
6
+ const template = new URL('../../../cheatingkit.yaml', import.meta.url)
7
+
8
+ export function configPath(env = process.env) {
9
+ return env.CHEATINGKIT_CONFIG || join(homedir(), '.cheatingkit', 'config.yaml')
10
+ }
11
+
12
+ export function expandPath(path) {
13
+ if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
14
+ return isAbsolute(path) ? path : resolve(path)
15
+ }
16
+
17
+ export function loadConfig(path = configPath()) {
18
+ const source = existsSync(path) ? path : template
19
+ const body = YAML.parse(readFileSync(source, 'utf8'))
20
+ if (body?.version !== 1 || !body?.database?.path || !body?.harnesses) throw new Error(`Invalid configuration: ${source}`)
21
+ return body
22
+ }
23
+
24
+ export function ensureConfig(path = configPath()) {
25
+ if (!existsSync(path)) {
26
+ mkdirSync(dirname(path), { recursive: true })
27
+ writeFileSync(path, readFileSync(template))
28
+ }
29
+ return path
30
+ }
31
+
32
+ export function configEnvironment(config) {
33
+ return {
34
+ ...process.env,
35
+ CHEATINGKIT_DB: expandPath(config.database.path),
36
+ CHEATINGKIT_CLAUDE_DIR: config.harnesses.claudeCode?.enabled ? expandPath(config.harnesses.claudeCode.path) : '',
37
+ CHEATINGKIT_CODEX_DIR: config.harnesses.codex?.enabled ? expandPath(config.harnesses.codex.path) : '',
38
+ CHEATINGKIT_HERMES_DIR: config.harnesses.hermes?.enabled ? expandPath(config.harnesses.hermes.path) : '',
39
+ }
40
+ }
@@ -0,0 +1,37 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+
5
+ export function harnessHomes(env = process.env) {
6
+ const home = env.USERPROFILE || env.HOME || homedir()
7
+ return {
8
+ claudeCode: env.CHEATINGKIT_CLAUDE_DIR || join(home, '.claude', 'projects'),
9
+ codex: env.CHEATINGKIT_CODEX_DIR || join(home, '.codex', 'sessions'),
10
+ hermes: env.CHEATINGKIT_HERMES_DIR || env.HERMES_HOME || join(home, '.hermes'),
11
+ }
12
+ }
13
+
14
+ export function walkJsonl(root) {
15
+ if (!existsSync(root)) return []
16
+ const files = []
17
+ const pending = [root]
18
+ while (pending.length) {
19
+ const dir = pending.pop()
20
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
21
+ const path = join(dir, entry.name)
22
+ if (entry.isDirectory()) pending.push(path)
23
+ else if (entry.isFile() && entry.name.endsWith('.jsonl')) files.push(path)
24
+ }
25
+ }
26
+ return files.sort()
27
+ }
28
+
29
+ export function detectHarnesses(env = process.env) {
30
+ const homes = harnessHomes(env)
31
+ const hermesDatabase = join(homes.hermes, 'state.db')
32
+ return [
33
+ { id: 'claudeCode', label: 'Claude Code', path: homes.claudeCode, present: env.CHEATINGKIT_CLAUDE_DIR !== '' && existsSync(homes.claudeCode), kind: 'jsonl' },
34
+ { id: 'codex', label: 'Codex', path: homes.codex, present: env.CHEATINGKIT_CODEX_DIR !== '' && existsSync(homes.codex), kind: 'jsonl' },
35
+ { id: 'hermes', label: 'Hermes', path: hermesDatabase, present: env.CHEATINGKIT_HERMES_DIR !== '' && existsSync(hermesDatabase) && statSync(hermesDatabase).isFile(), kind: 'sqlite' },
36
+ ]
37
+ }
@@ -0,0 +1,211 @@
1
+ import { openSync, readSync, closeSync, statSync } from 'node:fs'
2
+ import { basename } from 'node:path'
3
+ import { Database } from 'bun:sqlite'
4
+ import { detectHarnesses, walkJsonl } from './detect.js'
5
+
6
+ const sessionKey = (path) => basename(path, '.jsonl').match(/[0-9a-f]{8}-[0-9a-f-]{27,}$/i)?.[0] || basename(path, '.jsonl')
7
+ const iso = (value) => typeof value === 'number' ? new Date(value < 1e11 ? value * 1000 : value).toISOString() : typeof value === 'string' ? value : null
8
+ const asJson = (value) => value == null ? null : typeof value === 'string' ? value : JSON.stringify(value)
9
+ const textOf = (value) => typeof value === 'string' ? value : Array.isArray(value) ? value.map((item) => item?.text || item?.content || '').filter((item) => typeof item === 'string').join('\n') : null
10
+ const warningOf = (text) => typeof text === 'string' && /\b(cyber(?:security)?|malware|exploit|phishing|credential theft|safety)\b/i.test(text) && /\b(warn(?:ing)?|refus(?:e|al|ing)|cannot (?:assist|help)|can't (?:assist|help)|won't (?:assist|help))\b/i.test(text)
11
+
12
+ function writer(db) {
13
+ const session = db.prepare(`INSERT INTO sessions(harness,sessionId,sourcePath,startedAt,updatedAt,cwd,currentModel)
14
+ VALUES(?,?,?,?,?,?,?) ON CONFLICT(harness,sessionId) DO UPDATE SET
15
+ updatedAt=COALESCE(excluded.updatedAt,sessions.updatedAt), cwd=COALESCE(excluded.cwd,sessions.cwd),
16
+ currentModel=COALESCE(excluded.currentModel,sessions.currentModel)`)
17
+ const message = db.prepare(`INSERT INTO messages(harness,sessionId,sourceId,sourcePosition,timestamp,role,body,model,rawType)
18
+ VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(harness,sessionId,sourceId) DO UPDATE SET
19
+ body=excluded.body, model=COALESCE(excluded.model,messages.model), timestamp=COALESCE(excluded.timestamp,messages.timestamp)`)
20
+ const tool = db.prepare(`INSERT INTO toolCalls(harness,sessionId,sourceId,messageId,timestamp,name,input,output)
21
+ VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(harness,sessionId,sourceId) DO UPDATE SET
22
+ output=COALESCE(excluded.output,toolCalls.output)`)
23
+ const output = db.prepare('UPDATE toolCalls SET output=? WHERE harness=? AND sessionId=? AND sourceId=?')
24
+ const event = db.prepare('INSERT OR IGNORE INTO timeline(harness,sessionId,sourceId,timestamp,kind,detail) VALUES(?,?,?,?,?,?)')
25
+ const priorModel = db.prepare('SELECT currentModel FROM sessions WHERE harness=? AND sessionId=?')
26
+ const raw = db.prepare('INSERT OR IGNORE INTO sourceRecords(harness,sourcePath,sourcePosition,sessionId,rawJson) VALUES(?,?,?,?,?)')
27
+ return { session, message, tool, output, event, priorModel, raw }
28
+ }
29
+
30
+ function storeModel(w, harness, id, sourceId, timestamp, model) {
31
+ if (!model || typeof model !== 'string' || model.startsWith('<')) return
32
+ const prior = w.priorModel.get(harness, id)?.currentModel
33
+ if (prior !== model) {
34
+ w.event.run(harness, id, `${sourceId}:model`, timestamp, 'modelChange', prior ? `${prior} → ${model}` : `Started with ${model}`)
35
+ w.session.run(harness, id, '', timestamp, timestamp, null, model)
36
+ }
37
+ }
38
+
39
+ function put(w, harness, id, path, position, sourceId, timestamp, role, body, model, rawType) {
40
+ w.session.run(harness, id, path, timestamp, timestamp, null, null)
41
+ w.message.run(harness, id, sourceId, position, timestamp, role, asJson(body), model || null, rawType)
42
+ if (model) storeModel(w, harness, id, sourceId, timestamp, model)
43
+ if (role === 'assistant' && warningOf(textOf(body))) w.event.run(harness, id, sourceId, timestamp, 'cyberWarning', 'Potential cyber safety or refusal warning in assistant message')
44
+ }
45
+
46
+ function claudeLine(w, path, row, position) {
47
+ const id = row.sessionId || sessionKey(path)
48
+ const timestamp = iso(row.timestamp)
49
+ const sourceId = row.uuid || `${position}`
50
+ if (row.type !== 'user' && row.type !== 'assistant') return false
51
+ const msg = row.message || {}
52
+ put(w, 'claudeCode', id, path, position, sourceId, timestamp, row.type, msg.content, msg.model, row.type)
53
+ for (const [index, block] of (Array.isArray(msg.content) ? msg.content : []).entries()) {
54
+ if (block.type === 'tool_use') w.tool.run('claudeCode', id, block.id || `${sourceId}:${index}`, sourceId, timestamp, block.name || 'tool', asJson(block.input), null)
55
+ if (block.type === 'tool_result' && block.tool_use_id) w.output.run(asJson(block.content), 'claudeCode', id, block.tool_use_id)
56
+ }
57
+ return true
58
+ }
59
+
60
+ function codexLine(w, path, row, position) {
61
+ const payload = row.payload || {}
62
+ const id = sessionKey(path)
63
+ const timestamp = iso(row.timestamp)
64
+ const sourceId = `${position}`
65
+ if (row.type === 'session_meta') {
66
+ w.session.run('codex', id, path, timestamp, timestamp, payload.cwd || null, null)
67
+ return false
68
+ }
69
+ if (row.type === 'turn_context' && payload.model) {
70
+ w.session.run('codex', id, path, timestamp, timestamp, payload.cwd || null, null)
71
+ storeModel(w, 'codex', id, sourceId, timestamp, payload.model)
72
+ return false
73
+ }
74
+ if (row.type !== 'response_item') return false
75
+ if (payload.type === 'message') {
76
+ put(w, 'codex', id, path, position, payload.id || sourceId, timestamp, payload.role || 'unknown', payload.content || payload.input_text, payload.model, payload.type)
77
+ return true
78
+ }
79
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
80
+ w.session.run('codex', id, path, timestamp, timestamp, null, null)
81
+ w.tool.run('codex', id, payload.call_id || sourceId, payload.id || null, timestamp, payload.name || 'tool', asJson(payload.arguments || payload.input), null)
82
+ return true
83
+ }
84
+ if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') {
85
+ if (payload.call_id) w.output.run(asJson(payload.output), 'codex', id, payload.call_id)
86
+ return true
87
+ }
88
+ return false
89
+ }
90
+
91
+ function importJsonl(db, harness, path) {
92
+ const stats = statSync(path)
93
+ const previous = db.prepare('SELECT offsetBytes FROM sourceCursors WHERE sourcePath=?').get(path)?.offsetBytes || 0
94
+ if (stats.size < previous) throw new Error('Source was truncated; keep the original transcript and rebuild the local index before reimporting')
95
+ const start = previous
96
+ const fd = openSync(path, 'r')
97
+ const w = writer(db)
98
+ let offset = start
99
+ let carried = Buffer.alloc(0)
100
+ let count = 0
101
+ db.exec('BEGIN IMMEDIATE')
102
+ try {
103
+ while (offset < stats.size) {
104
+ const buffer = Buffer.allocUnsafe(Math.min(1024 * 1024, stats.size - offset))
105
+ const length = readSync(fd, buffer, 0, buffer.length, offset)
106
+ if (!length) break
107
+ const combined = Buffer.concat([carried, buffer.subarray(0, length)])
108
+ let lineStart = 0
109
+ for (let i = 0; i < combined.length; i++) {
110
+ if (combined[i] !== 10) continue
111
+ const position = offset - carried.length + lineStart
112
+ const raw = combined.subarray(lineStart, i).toString('utf8').trim()
113
+ if (raw) {
114
+ try {
115
+ const row = JSON.parse(raw)
116
+ w.raw.run(harness, path, position, row.sessionId || sessionKey(path), raw)
117
+ if (harness === 'claudeCode' ? claudeLine(w, path, row, position) : codexLine(w, path, row, position)) count++
118
+ } catch (error) { throw new Error(`Invalid JSONL at byte ${position}: ${error.message}`) }
119
+ }
120
+ lineStart = i + 1
121
+ }
122
+ carried = combined.subarray(lineStart)
123
+ offset += length
124
+ }
125
+ const committed = offset - carried.length
126
+ db.prepare(`INSERT INTO sourceCursors(sourcePath,harness,offsetBytes,sourceSize,sourceModifiedMs,updatedAt)
127
+ VALUES(?,?,?,?,?,?) ON CONFLICT(sourcePath) DO UPDATE SET offsetBytes=excluded.offsetBytes,
128
+ sourceSize=excluded.sourceSize,sourceModifiedMs=excluded.sourceModifiedMs,updatedAt=excluded.updatedAt`)
129
+ .run(path, harness, committed, stats.size, stats.mtimeMs, new Date().toISOString())
130
+ db.exec('COMMIT')
131
+ return count
132
+ } catch (error) {
133
+ db.exec('ROLLBACK')
134
+ throw error
135
+ } finally {
136
+ closeSync(fd)
137
+ }
138
+ }
139
+
140
+ function columns(db, table) {
141
+ return new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((row) => row.name))
142
+ }
143
+
144
+ function importHermes(db, path) {
145
+ const source = new Database(path, { readonly: true })
146
+ try {
147
+ const sessions = columns(source, 'sessions')
148
+ const messages = columns(source, 'messages')
149
+ if (!sessions.has('id') || !messages.has('id') || !messages.has('session_id')) throw new Error('Unsupported Hermes state.db schema')
150
+ const checkpoint = db.prepare('SELECT offsetBytes FROM sourceCursors WHERE sourcePath=?').get(path)?.offsetBytes || 0
151
+ const w = writer(db)
152
+ let maxId = checkpoint
153
+ let count = 0
154
+ const rows = source.prepare(`SELECT id, ${sessions.has('started_at') ? 'started_at' : 'NULL'} AS startedAt,
155
+ ${sessions.has('model') ? 'model' : 'NULL'} AS model, ${sessions.has('cwd') ? 'cwd' : 'NULL'} AS cwd FROM sessions`).all()
156
+ db.exec('BEGIN IMMEDIATE')
157
+ try {
158
+ for (const row of rows) {
159
+ const stamp = iso(row.startedAt)
160
+ w.session.run('hermes', String(row.id), path, stamp, stamp, row.cwd || null, null)
161
+ if (row.model) storeModel(w, 'hermes', String(row.id), `session:${row.id}`, stamp, row.model)
162
+ }
163
+ const selected = ['id', 'session_id', 'role', 'content', 'timestamp', 'tool_calls', 'tool_name', 'tool_call_id', 'active'].filter((name) => messages.has(name))
164
+ for (const row of source.prepare(`SELECT ${selected.join(',')} FROM messages WHERE id > ? ORDER BY id`).iterate(checkpoint)) {
165
+ const id = String(row.session_id)
166
+ const timestamp = iso(row.timestamp)
167
+ const sourceId = String(row.id)
168
+ const content = typeof row.content === 'string' && row.content.startsWith('\0json:') ? JSON.parse(row.content.slice(6)) : row.content
169
+ w.raw.run('hermes', path, row.id, id, JSON.stringify(row))
170
+ put(w, 'hermes', id, path, row.id, sourceId, timestamp, row.role || 'unknown', content, null, 'message')
171
+ if (row.tool_calls) {
172
+ let calls = []
173
+ try { calls = JSON.parse(row.tool_calls) } catch {}
174
+ for (const [index, call] of (Array.isArray(calls) ? calls : []).entries()) {
175
+ w.tool.run('hermes', id, call.id || `${sourceId}:${index}`, sourceId, timestamp, call.function?.name || call.name || 'tool', asJson(call.function?.arguments || call.arguments), null)
176
+ }
177
+ }
178
+ if (row.role === 'tool' && row.tool_call_id) w.output.run(asJson(content), 'hermes', id, row.tool_call_id)
179
+ maxId = row.id
180
+ count++
181
+ }
182
+ const stats = statSync(path)
183
+ db.prepare(`INSERT INTO sourceCursors(sourcePath,harness,offsetBytes,sourceSize,sourceModifiedMs,updatedAt)
184
+ VALUES(?,?,?,?,?,?) ON CONFLICT(sourcePath) DO UPDATE SET offsetBytes=excluded.offsetBytes,
185
+ sourceSize=excluded.sourceSize,sourceModifiedMs=excluded.sourceModifiedMs,updatedAt=excluded.updatedAt`)
186
+ .run(path, 'hermes', maxId, stats.size, stats.mtimeMs, new Date().toISOString())
187
+ db.exec('COMMIT')
188
+ return count
189
+ } catch (error) {
190
+ db.exec('ROLLBACK')
191
+ throw error
192
+ }
193
+ } finally {
194
+ source.close()
195
+ }
196
+ }
197
+
198
+ export function ingest(db, env = process.env, report = () => {}) {
199
+ const results = []
200
+ for (const harness of detectHarnesses(env).filter((item) => item.present)) {
201
+ let count = 0
202
+ const files = harness.kind === 'jsonl' ? walkJsonl(harness.path) : [harness.path]
203
+ for (const path of files) {
204
+ try { count += harness.kind === 'jsonl' ? importJsonl(db, harness.id, path) : importHermes(db, path) }
205
+ catch (error) { report(`${harness.label}: ${path}: ${error.message}`) }
206
+ }
207
+ results.push({ harness: harness.label, files: files.length, imported: count })
208
+ report(`${harness.label}: ${files.length} source${files.length === 1 ? '' : 's'}, ${count} new record${count === 1 ? '' : 's'}`)
209
+ }
210
+ return results
211
+ }
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env bun
2
+ import * as clack from '@clack/prompts'
3
+ import { Effect } from 'effect'
4
+ import { spawnSync } from 'node:child_process'
5
+ import { writeFileSync } from 'node:fs'
6
+ import YAML from 'yaml'
7
+ import { configEnvironment, configPath, ensureConfig, expandPath, loadConfig } from './config/client.js'
8
+ import { detectHarnesses } from './harnesses/detect.js'
9
+ import { ingest } from './harnesses/ingest.js'
10
+ import { labelMessages } from './models/label.js'
11
+ import { openDatabase } from './storage/client.js'
12
+ import { checkUpdates, installedVersion } from './updates/client.js'
13
+
14
+ const command = process.argv[2] || 'help'
15
+
16
+ async function updateNotice(config) {
17
+ try {
18
+ const update = await checkUpdates(config)
19
+ if (update.status === 'newer') console.log(`ck ${update.version} is available (${update.track}): ck update --apply`)
20
+ } catch {}
21
+ }
22
+
23
+ const run = Effect.gen(function* () {
24
+ if (command === 'help' || command === '--help') {
25
+ console.log('ck setup | detect | ingest | label | sessions | timeline | areas | leadups | version | updates | update [--track stable|nightly] [--apply]')
26
+ return
27
+ }
28
+ if (command === 'version' || command === '--version' || command === '-v') {
29
+ const { version, build, commit } = installedVersion()
30
+ console.log(build ? `ck ${version} (build ${build}, ${commit})` : `ck ${version} (development checkout)`)
31
+ return
32
+ }
33
+ if (command === 'setup') {
34
+ clack.intro('CheatingKit local setup')
35
+ const path = ensureConfig()
36
+ const config = loadConfig(path)
37
+ const env = configEnvironment(config)
38
+ const found = detectHarnesses(env)
39
+ for (const item of found) clack.log.info(`${item.label}: ${item.present ? 'found' : 'not found'} (${item.path})`)
40
+ const db = yield* Effect.try(() => openDatabase(expandPath(config.database.path)))
41
+ clack.log.success(`SQLite database ready: ${expandPath(config.database.path)}`)
42
+ db.close()
43
+ const proceed = yield* Effect.promise(() => clack.confirm({ message: 'Import available local sessions now?', initialValue: true }))
44
+ if (clack.isCancel(proceed)) { clack.cancel('Setup stopped'); return }
45
+ if (proceed) {
46
+ const handle = yield* Effect.try(() => openDatabase(expandPath(config.database.path)))
47
+ try { yield* Effect.try(() => ingest(handle, env, (line) => clack.log.info(line))) } finally { handle.close() }
48
+ if (config.models?.enabled) {
49
+ const classify = yield* Effect.promise(() => clack.confirm({ message: 'Run the local CPU model over imported messages now?', initialValue: true }))
50
+ if (!clack.isCancel(classify) && classify) {
51
+ const labeled = yield* Effect.try(() => openDatabase(expandPath(config.database.path)))
52
+ try { yield* Effect.tryPromise(() => labelMessages(labeled, config, (line) => clack.log.info(line))) }
53
+ finally { labeled.close() }
54
+ }
55
+ }
56
+ }
57
+ clack.outro(`Configuration: ${path}. Run 'bun run cli ingest' after new conversations.`)
58
+ yield* Effect.promise(() => updateNotice(config))
59
+ return
60
+ }
61
+ const config = loadConfig()
62
+ const env = configEnvironment(config)
63
+ if (command === 'detect') {
64
+ for (const item of detectHarnesses(env)) console.log(`${item.label}\t${item.present ? 'found' : 'missing'}\t${item.path}`)
65
+ return
66
+ }
67
+ if (command === 'updates') {
68
+ const state = yield* Effect.tryPromise(() => checkUpdates(config, true))
69
+ console.log(JSON.stringify(state, null, 2))
70
+ return
71
+ }
72
+ if (command === 'update') {
73
+ const trackAt = process.argv.indexOf('--track')
74
+ const track = trackAt >= 0 ? process.argv[trackAt + 1] : config.updates?.track || 'stable'
75
+ if (!['stable', 'nightly'].includes(track)) throw new Error('Track must be stable or nightly')
76
+ if (trackAt >= 0) {
77
+ const path = ensureConfig()
78
+ config.updates = { ...config.updates, track }
79
+ writeFileSync(path, YAML.stringify(config))
80
+ }
81
+ const state = yield* Effect.tryPromise(() => checkUpdates(config, true))
82
+ console.log(JSON.stringify(state, null, 2))
83
+ if (!process.argv.includes('--apply')) return
84
+ if (!state.version) throw new Error(`No ${track} release is available`)
85
+ if (state.version === installedVersion().version) { console.log(`ck ${state.version} is already installed.`); return }
86
+ const installed = spawnSync('bun', ['add', '-g', `cheatingkit@${state.version}`], { stdio: 'inherit' })
87
+ if (installed.error) throw installed.error
88
+ if (installed.status !== 0) throw new Error(`Bun install exited ${installed.status}`)
89
+ console.log(`Installed ck ${state.version}; run ck --version to verify.`)
90
+ return
91
+ }
92
+ const db = yield* Effect.try(() => openDatabase(expandPath(config.database.path)))
93
+ try {
94
+ if (command === 'ingest') {
95
+ yield* Effect.try(() => ingest(db, env, console.log))
96
+ } else if (command === 'label') {
97
+ const result = yield* Effect.tryPromise(() => labelMessages(db, config, console.log))
98
+ console.log(JSON.stringify(result))
99
+ } else if (command === 'sessions') {
100
+ const rows = db.prepare(`SELECT harness,sessionId,currentModel,updatedAt,
101
+ (SELECT count(*) FROM messages m WHERE m.harness=s.harness AND m.sessionId=s.sessionId) AS messages
102
+ FROM sessions s ORDER BY updatedAt DESC LIMIT 50`).all()
103
+ console.table(rows)
104
+ } else if (command === 'timeline') {
105
+ const rows = db.prepare('SELECT harness,sessionId,timestamp,kind,detail FROM timeline ORDER BY timestamp DESC LIMIT 100').all()
106
+ console.table(rows)
107
+ } else if (command === 'areas') {
108
+ const rows = db.prepare('SELECT label,count(*) AS messages,round(avg(score),3) AS averageScore FROM messageLabels GROUP BY label ORDER BY messages DESC').all()
109
+ console.table(rows)
110
+ } else if (command === 'leadups') {
111
+ const rows = db.prepare(`SELECT w.harness,w.sessionId,w.warningSourceId,w.distance,l.label,l.score,m.body
112
+ FROM warningLeadUps w JOIN messages m ON m.harness=w.harness AND m.sessionId=w.sessionId AND m.sourceId=w.sourceId
113
+ LEFT JOIN messageLabels l ON l.harness=m.harness AND l.sessionId=m.sessionId AND l.sourceId=m.sourceId
114
+ ORDER BY w.harness,w.sessionId,w.warningSourceId,w.distance LIMIT 100`).all()
115
+ console.table(rows.map((row) => ({ ...row, body: String(row.body || '').slice(0, 120) })))
116
+ } else {
117
+ throw new Error(`Unknown command: ${command}`)
118
+ }
119
+ } finally { db.close() }
120
+ yield* Effect.promise(() => updateNotice(config))
121
+ })
122
+
123
+ Effect.runPromise(run).catch((error) => { console.error(error.message || error); process.exitCode = 1 })
@@ -0,0 +1,36 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
3
+ import { z } from 'zod'
4
+ import { expandPath, loadConfig, configEnvironment } from '../config/client.js'
5
+ import { ingest } from '../harnesses/ingest.js'
6
+ import { openDatabase } from '../storage/client.js'
7
+ import { contextFor, searchSessions } from '../search/client.js'
8
+ import { installedVersion } from '../updates/client.js'
9
+
10
+ export async function serveMcp() {
11
+ const config = loadConfig()
12
+ const server = new McpServer({ name: 'ck', version: installedVersion().version })
13
+ server.registerTool('search_sessions', {
14
+ description: 'Search local Claude Code, Codex, and Hermes sessions. Returns exact source message IDs.',
15
+ inputSchema: { query: z.string().min(1), harness: z.enum(['claudeCode', 'codex', 'hermes']).optional(), limit: z.number().int().min(1).max(20).optional() },
16
+ }, async ({ query, harness, limit }) => {
17
+ const db = openDatabase(expandPath(config.database.path))
18
+ try {
19
+ ingest(db, configEnvironment(config), () => {})
20
+ const hits = await searchSessions(db, query, { harness, limit })
21
+ return { content: [{ type: 'text', text: JSON.stringify(hits, null, 2) }] }
22
+ } finally { db.close() }
23
+ })
24
+ server.registerTool('task_context', {
25
+ description: 'Find cited prior user instructions and conversation passages for a current request.',
26
+ inputSchema: { request: z.string().min(1), harness: z.enum(['claudeCode', 'codex', 'hermes']).optional(), cwd: z.string().optional() },
27
+ }, async ({ request, harness, cwd }) => {
28
+ const db = openDatabase(expandPath(config.database.path))
29
+ try {
30
+ ingest(db, configEnvironment(config), () => {})
31
+ const text = await contextFor(db, request, { harness, cwd, maxChars: 7000 })
32
+ return { content: [{ type: 'text', text: text || 'No indexed context found.' }] }
33
+ } finally { db.close() }
34
+ })
35
+ await server.connect(new StdioServerTransport())
36
+ }
@@ -0,0 +1,50 @@
1
+ import { createWriteStream, existsSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { pipeline } from 'node:stream/promises'
4
+ import { Readable } from 'node:stream'
5
+ import { homedir } from 'node:os'
6
+ import { fileDigest } from './helpers/verify.js'
7
+
8
+ import { models } from './constants.js'
9
+ export { models } from './constants.js'
10
+
11
+ export const modelRoot = (env = process.env) => env.CHEATINGKIT_MODELS || join(homedir(), '.cheatingkit', 'models', 'hf')
12
+ export const modelPath = (model, env = process.env) => join(modelRoot(env), model.id, model.revision)
13
+
14
+ export async function checkModel(model, env = process.env) {
15
+ const root = modelPath(model, env)
16
+ const bad = []
17
+ for (const file of model.files) {
18
+ const path = join(root, file.path)
19
+ if (!existsSync(path) || statSync(path).size !== file.size || await fileDigest(path, file) !== (file.sha256 || file.gitSha1)) bad.push(file.path)
20
+ }
21
+ return { key: model.key, id: model.id, revision: model.revision, path: root, ready: bad.length === 0, missingOrMismatched: bad }
22
+ }
23
+
24
+ export async function fetchModel(model, env = process.env, report = () => {}) {
25
+ const root = modelPath(model, env)
26
+ for (const file of model.files) {
27
+ const path = join(root, file.path)
28
+ if (existsSync(path) && statSync(path).size === file.size && await fileDigest(path, file) === (file.sha256 || file.gitSha1)) continue
29
+ mkdirSync(dirname(path), { recursive: true })
30
+ const part = path + '.part'
31
+ rmSync(part, { force: true })
32
+ report(`Downloading ${model.id}: ${file.path}`)
33
+ const url = `https://huggingface.co/${model.id}/resolve/${model.revision}/${file.path}`
34
+ try {
35
+ const response = await fetch(url, { signal: AbortSignal.timeout(15 * 60_000) })
36
+ if (!response.ok || !response.body) throw new Error(`HTTP ${response.status} for ${url}`)
37
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(part))
38
+ if (statSync(part).size !== file.size || await fileDigest(part, file) !== (file.sha256 || file.gitSha1)) throw new Error(`Hash mismatch for ${file.path}`)
39
+ renameSync(part, path)
40
+ } catch (error) { rmSync(part, { force: true }); throw error }
41
+ }
42
+ return checkModel(model, env)
43
+ }
44
+
45
+ export async function checkModels(env = process.env) { return Promise.all(models.map((model) => checkModel(model, env))) }
46
+ export async function fetchModels(env = process.env, report = () => {}) {
47
+ const out = []
48
+ for (const model of models) out.push(await fetchModel(model, env, report))
49
+ return out
50
+ }
@@ -0,0 +1,21 @@
1
+ export const models = [
2
+ {
3
+ key: 'minilm', id: 'Xenova/all-MiniLM-L6-v2', revision: '751bff37182d3f1213fa05d7196b954e230abad9',
4
+ files: [
5
+ { path: 'config.json', size: 650, gitSha1: '72147e4ff4426ebedbfa2146c4a0999def51a313' },
6
+ { path: 'tokenizer.json', size: 711661, gitSha1: 'c17ed520ed8438736732a54957a69306b8822215' },
7
+ { path: 'tokenizer_config.json', size: 366, gitSha1: '37fca74771bc76a8e01178ce3a6055a0995f8093' },
8
+ { path: 'onnx/model_quantized.onnx', size: 22972370, sha256: 'afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1' },
9
+ ],
10
+ },
11
+ {
12
+ key: 'gliner', id: 'fastino/gliner2.5-small-v1', revision: 'b5d42bf7dc7d01c40304ae4ed43c2f13c325a75b',
13
+ files: [
14
+ { path: 'config.json', size: 4104, gitSha1: 'cfd76c9f59461050dd1c00ac0b670eaac7d1495d' },
15
+ { path: 'encoder_config/config.json', size: 856, gitSha1: 'cdaf6bb43684ee0c7623598df371099ed8b453e6' },
16
+ { path: 'model.safetensors', size: 295567700, sha256: '4ee982787ace270d4bf15dbcb28ced38e0aa201372347114ceedd6336055de2b' },
17
+ { path: 'tokenizer.json', size: 8341713, gitSha1: 'a93077b30f99647415b09c3534fed78681ffc853' },
18
+ { path: 'tokenizer_config.json', size: 645, gitSha1: '5efd586306801b08ca13390b0619a94c943046e4' },
19
+ ],
20
+ },
21
+ ]
@@ -0,0 +1,9 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { createReadStream } from 'node:fs'
3
+
4
+ export async function fileDigest(path, file) {
5
+ const hash = createHash(file.sha256 ? 'sha256' : 'sha1')
6
+ if (file.gitSha1) hash.update(`blob ${file.size}\0`)
7
+ for await (const chunk of createReadStream(path)) hash.update(chunk)
8
+ return hash.digest('hex')
9
+ }
@@ -0,0 +1,84 @@
1
+ import { expandPath } from '../config/client.js'
2
+
3
+ const prototypes = {
4
+ coding: ['Write code, debug software, run tests, inspect a repository.', 'Implement a software feature using tools and files.'],
5
+ cybersecurity: ['Analyze a security vulnerability or penetration test.', 'Discuss cyber defense, exploits, security testing, or access control.'],
6
+ malware: ['Create malicious software, phishing, credential theft, or evasion.', 'Analyze a malware sample or harmful code behavior.'],
7
+ privacy: ['Discuss private personal data, tracking, surveillance, or account secrets.', 'Protect sensitive records and credentials.'],
8
+ finance: ['Discuss money, payments, investments, prices, or financial accounts.', 'Calculate costs and budgets.'],
9
+ general: ['General conversation, writing, advice, and questions.', 'Summarize information or explain a concept.'],
10
+ }
11
+
12
+ const cosine = (a, b) => {
13
+ let dot = 0, aa = 0, bb = 0
14
+ for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; aa += a[i] ** 2; bb += b[i] ** 2 }
15
+ return dot / (Math.sqrt(aa * bb) || 1)
16
+ }
17
+
18
+ function bodyText(raw) {
19
+ if (!raw) return ''
20
+ let value
21
+ try { value = JSON.parse(raw) } catch { value = raw }
22
+ if (typeof value === 'string') return value
23
+ if (Array.isArray(value)) return value.map((part) => part?.text || part?.content || '').filter((part) => typeof part === 'string').join(' ').slice(0, 8000)
24
+ return ''
25
+ }
26
+
27
+ export async function labelMessages(db, config, report = () => {}) {
28
+ if (!config.models?.enabled) return { labeled: 0, leadUps: 0 }
29
+ const { pipeline, env } = await import('@huggingface/transformers')
30
+ env.allowRemoteModels = true
31
+ if (config.models.embedding.cachePath) env.cacheDir = expandPath(config.models.embedding.cachePath)
32
+ const { id, revision, dtype, batchSize } = config.models.embedding
33
+ const modelKey = `${id}@${revision}`
34
+ report(`Loading local CPU embedding model ${id}`)
35
+ const extractor = await pipeline('feature-extraction', id, { dtype, revision, device: 'cpu' })
36
+ const names = (config.models.labels || Object.keys(prototypes)).filter((name) => prototypes[name])
37
+ const prompts = names.flatMap((name) => prototypes[name])
38
+ const anchors = await extractor(prompts, { pooling: 'mean', normalize: true })
39
+ const width = anchors.dims.at(-1)
40
+ const vectors = names.map((_, index) => [0, 1].map((offset) => anchors.data.slice((index * 2 + offset) * width, (index * 2 + offset + 1) * width)))
41
+ const total = db.prepare(`SELECT count(*) AS n FROM messages m
42
+ LEFT JOIN messageLabels l ON l.harness=m.harness AND l.sessionId=m.sessionId AND l.sourceId=m.sourceId AND l.modelId=?
43
+ WHERE l.sourceId IS NULL AND m.role IN ('user','assistant')`).get(modelKey).n
44
+ const nextRows = db.prepare(`SELECT m.rowid AS rowNumber,m.harness,m.sessionId,m.sourceId,m.body FROM messages m
45
+ LEFT JOIN messageLabels l ON l.harness=m.harness AND l.sessionId=m.sessionId AND l.sourceId=m.sourceId AND l.modelId=?
46
+ WHERE l.sourceId IS NULL AND m.role IN ('user','assistant') AND m.rowid>? ORDER BY m.rowid LIMIT ?`)
47
+ const save = db.prepare('INSERT OR REPLACE INTO messageLabels(harness,sessionId,sourceId,modelId,label,score,labeledAt) VALUES(?,?,?,?,?,?,?)')
48
+ let labeled = 0
49
+ let after = 0
50
+ while (true) {
51
+ const slice = nextRows.all(modelKey, after, batchSize || 24)
52
+ if (!slice.length) break
53
+ const texts = slice.map((row) => bodyText(row.body))
54
+ const output = await extractor(texts.map((text) => text || 'empty message'), { pooling: 'mean', normalize: true })
55
+ db.exec('BEGIN IMMEDIATE')
56
+ try {
57
+ for (const [index, row] of slice.entries()) {
58
+ const vector = output.data.slice(index * width, (index + 1) * width)
59
+ const ranked = names.map((name, i) => ({ name, score: Math.max(...vectors[i].map((anchor) => cosine(vector, anchor))) })).sort((a, b) => b.score - a.score)
60
+ save.run(row.harness, row.sessionId, row.sourceId, modelKey, ranked[0].name, ranked[0].score, new Date().toISOString())
61
+ labeled++
62
+ }
63
+ db.exec('COMMIT')
64
+ } catch (error) { db.exec('ROLLBACK'); throw error }
65
+ after = slice.at(-1).rowNumber
66
+ report(`Labeled ${labeled}/${total} messages`)
67
+ }
68
+ const warnings = db.prepare(`SELECT t.harness,t.sessionId,t.sourceId,m.sourcePosition FROM timeline t
69
+ JOIN messages m ON m.harness=t.harness AND m.sessionId=t.sessionId AND m.sourceId=t.sourceId WHERE t.kind='cyberWarning'`).all()
70
+ const lead = db.prepare('INSERT OR IGNORE INTO warningLeadUps(harness,sessionId,warningSourceId,sourceId,distance) VALUES(?,?,?,?,?)')
71
+ const previous = db.prepare('SELECT sourceId FROM messages WHERE harness=? AND sessionId=? AND sourcePosition<? AND role IN (\'user\',\'assistant\') ORDER BY sourcePosition DESC LIMIT ?')
72
+ let leadUps = 0
73
+ db.exec('BEGIN IMMEDIATE')
74
+ try {
75
+ for (const warning of warnings) {
76
+ for (const [index, row] of previous.all(warning.harness, warning.sessionId, warning.sourcePosition, config.models.leadUpMessages || 4).entries()) {
77
+ lead.run(warning.harness, warning.sessionId, warning.sourceId, row.sourceId, index + 1)
78
+ leadUps++
79
+ }
80
+ }
81
+ db.exec('COMMIT')
82
+ } catch (error) { db.exec('ROLLBACK'); throw error }
83
+ return { labeled, leadUps }
84
+ }
@@ -0,0 +1,117 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { pipeline, env } from '@huggingface/transformers'
3
+ import { modelPath, models } from '../models/client.js'
4
+
5
+ const embedModel = models.find((model) => model.key === 'minilm')
6
+ const modelId = `${embedModel.id}@${embedModel.revision}`
7
+ let extractor
8
+
9
+ function textOf(raw) {
10
+ if (!raw) return ''
11
+ let value = raw
12
+ try { value = JSON.parse(raw) } catch {}
13
+ if (typeof value === 'string') return value.trim()
14
+ if (Array.isArray(value)) return value.map((part) => part?.text || part?.content || '').filter((part) => typeof part === 'string').join(' ').trim()
15
+ return ''
16
+ }
17
+
18
+ export async function localEmbed(texts) {
19
+ if (!extractor) {
20
+ env.allowRemoteModels = false
21
+ extractor = await pipeline('feature-extraction', modelPath(embedModel), { dtype: 'q8', device: 'cpu' })
22
+ }
23
+ const output = await extractor(texts, { pooling: 'mean', normalize: true })
24
+ const width = output.dims.at(-1)
25
+ return texts.map((_, index) => Float32Array.from(output.data.slice(index * width, (index + 1) * width)))
26
+ }
27
+
28
+ function chunksOf(rows) {
29
+ const messages = rows.map((row) => ({ ...row, text: textOf(row.body) })).filter((row) => row.text)
30
+ const chunks = []
31
+ for (let start = 0; start < messages.length; start += 3) {
32
+ const window = messages.slice(start, start + 4)
33
+ const text = window.map((row) => `${row.role}: ${row.text.replace(/\s+/g, ' ')}`).join('\n')
34
+ chunks.push({ chunkStart: start, text, messageIds: window.map((row) => row.sourceId), textHash: createHash('sha256').update(text).digest('hex') })
35
+ if (start + 4 >= messages.length) break
36
+ }
37
+ return chunks
38
+ }
39
+
40
+ function vectorBytes(vector) { return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength) }
41
+
42
+ export async function indexSessions(db, report = () => {}, embed = localEmbed) {
43
+ const sessions = db.prepare('SELECT harness,sessionId FROM sessions ORDER BY harness,sessionId').all()
44
+ const selectRows = db.prepare("SELECT sourceId,role,body FROM messages WHERE harness=? AND sessionId=? AND role IN ('user','assistant') ORDER BY sourcePosition,sourceId")
45
+ const selectHeld = db.prepare('SELECT id,chunkStart,textHash,modelId,vector FROM searchChunks WHERE harness=? AND sessionId=?')
46
+ const upsert = db.prepare(`INSERT INTO searchChunks(harness,sessionId,chunkStart,messageIds,text,textHash,modelId,vector)
47
+ VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(harness,sessionId,chunkStart) DO UPDATE SET messageIds=excluded.messageIds,text=excluded.text,textHash=excluded.textHash,modelId=excluded.modelId,vector=excluded.vector`)
48
+ const idOf = db.prepare('SELECT id FROM searchChunks WHERE harness=? AND sessionId=? AND chunkStart=?')
49
+ const deleteFts = db.prepare('DELETE FROM searchChunksFts WHERE rowid=?')
50
+ const putFts = db.prepare('INSERT INTO searchChunksFts(rowid,text) VALUES(?,?)')
51
+ const deleteChunk = db.prepare('DELETE FROM searchChunks WHERE id=?')
52
+ let embedded = 0
53
+ let total = 0
54
+ for (const session of sessions) {
55
+ const chunks = chunksOf(selectRows.all(session.harness, session.sessionId))
56
+ const held = new Map(selectHeld.all(session.harness, session.sessionId).map((row) => [row.chunkStart, row]))
57
+ const changed = chunks.filter((chunk) => {
58
+ const old = held.get(chunk.chunkStart)
59
+ return !old || old.textHash !== chunk.textHash || old.modelId !== modelId
60
+ })
61
+ const vectors = []
62
+ for (let start = 0; start < changed.length; start += 24) vectors.push(...await embed(changed.slice(start, start + 24).map((chunk) => chunk.text)))
63
+ db.exec('BEGIN IMMEDIATE')
64
+ try {
65
+ for (const [index, chunk] of changed.entries()) {
66
+ const old = held.get(chunk.chunkStart)
67
+ if (old) deleteFts.run(old.id)
68
+ upsert.run(session.harness, session.sessionId, chunk.chunkStart, JSON.stringify(chunk.messageIds), chunk.text, chunk.textHash, modelId, vectorBytes(vectors[index]))
69
+ const id = idOf.get(session.harness, session.sessionId, chunk.chunkStart).id
70
+ putFts.run(id, chunk.text)
71
+ }
72
+ const starts = new Set(chunks.map((chunk) => chunk.chunkStart))
73
+ for (const old of held.values()) {
74
+ if (starts.has(old.chunkStart)) continue
75
+ deleteFts.run(old.id)
76
+ deleteChunk.run(old.id)
77
+ }
78
+ db.exec('COMMIT')
79
+ } catch (error) { db.exec('ROLLBACK'); throw error }
80
+ total += chunks.length
81
+ embedded += changed.length
82
+ if (changed.length) report(`${session.harness}/${session.sessionId}: indexed ${changed.length} changed windows`)
83
+ }
84
+ db.prepare('INSERT INTO indexState(stage,modelId,indexedAt,chunks) VALUES(?,?,?,?) ON CONFLICT(stage) DO UPDATE SET modelId=excluded.modelId,indexedAt=excluded.indexedAt,chunks=excluded.chunks')
85
+ .run('search', modelId, new Date().toISOString(), total)
86
+ return { sessions: sessions.length, chunks: total, embedded }
87
+ }
88
+
89
+ function cosine(a, b) {
90
+ let sum = 0
91
+ for (let i = 0; i < Math.min(a.length, b.length); i++) sum += a[i] * b[i]
92
+ return sum
93
+ }
94
+
95
+ export async function searchSessions(db, query, options = {}, embed = localEmbed) {
96
+ const tokens = [...new Set(query.match(/[\p{L}\p{N}_]+/gu) || [])].slice(0, 16)
97
+ const termQuery = tokens.map((token) => `"${token.replaceAll('"', '')}"`).join(' OR ')
98
+ const keyword = termQuery ? db.prepare('SELECT rowid FROM searchChunksFts WHERE searchChunksFts MATCH ? ORDER BY bm25(searchChunksFts) LIMIT 50').all(termQuery).map((row) => row.rowid) : []
99
+ const rows = db.prepare(`SELECT c.*,s.cwd FROM searchChunks c JOIN sessions s ON s.harness=c.harness AND s.sessionId=c.sessionId
100
+ WHERE (? IS NULL OR c.harness=?) AND (? IS NULL OR s.cwd=?)`).all(options.harness || null, options.harness || null, options.cwd || null, options.cwd || null)
101
+ const [queryVector] = await embed([query])
102
+ const vector = rows.map((row) => ({ id: row.id, score: cosine(queryVector, new Float32Array(row.vector.buffer.slice(row.vector.byteOffset, row.vector.byteOffset + row.vector.byteLength))) }))
103
+ .sort((a, b) => b.score - a.score).slice(0, 50)
104
+ const byId = new Map(rows.map((row) => [row.id, row]))
105
+ const scores = new Map()
106
+ for (const [rank, id] of keyword.entries()) if (byId.has(id)) scores.set(id, (scores.get(id) || 0) + 1 / (60 + rank + 1))
107
+ for (const [rank, item] of vector.entries()) scores.set(item.id, (scores.get(item.id) || 0) + 1 / (60 + rank + 1))
108
+ return [...scores].sort((a, b) => b[1] - a[1]).slice(0, options.limit || 5).map(([id, score]) => {
109
+ const row = byId.get(id)
110
+ return { harness: row.harness, sessionId: row.sessionId, cwd: row.cwd, messageIds: JSON.parse(row.messageIds), text: row.text, score }
111
+ })
112
+ }
113
+
114
+ export async function contextFor(db, query, options = {}, embed = localEmbed) {
115
+ const hits = await searchSessions(db, query, options, embed)
116
+ return hits.length ? hits.map((hit, index) => `[${index + 1}] ${hit.harness}/${hit.sessionId} messages ${hit.messageIds.join(', ')}\n${hit.text}`).join('\n\n').slice(0, options.maxChars || 7000) : ''
117
+ }
@@ -0,0 +1,116 @@
1
+ import { mkdirSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+ import { Database } from 'bun:sqlite'
5
+
6
+ export function databasePath(env = process.env) {
7
+ return env.CHEATINGKIT_DB || join(homedir(), '.cheatingkit', 'sessions.db')
8
+ }
9
+
10
+ export function openDatabase(path = databasePath()) {
11
+ mkdirSync(dirname(path), { recursive: true })
12
+ const db = new Database(path, { create: true })
13
+ db.exec(`
14
+ PRAGMA journal_mode = WAL;
15
+ PRAGMA foreign_keys = ON;
16
+ CREATE TABLE IF NOT EXISTS sessions (
17
+ harness TEXT NOT NULL,
18
+ sessionId TEXT NOT NULL,
19
+ sourcePath TEXT NOT NULL,
20
+ startedAt TEXT,
21
+ updatedAt TEXT,
22
+ cwd TEXT,
23
+ currentModel TEXT,
24
+ PRIMARY KEY (harness, sessionId)
25
+ );
26
+ CREATE TABLE IF NOT EXISTS messages (
27
+ harness TEXT NOT NULL,
28
+ sessionId TEXT NOT NULL,
29
+ sourceId TEXT NOT NULL,
30
+ sourcePosition INTEGER NOT NULL,
31
+ timestamp TEXT,
32
+ role TEXT NOT NULL,
33
+ body TEXT,
34
+ model TEXT,
35
+ rawType TEXT,
36
+ PRIMARY KEY (harness, sessionId, sourceId),
37
+ FOREIGN KEY (harness, sessionId) REFERENCES sessions(harness, sessionId)
38
+ );
39
+ CREATE TABLE IF NOT EXISTS toolCalls (
40
+ harness TEXT NOT NULL,
41
+ sessionId TEXT NOT NULL,
42
+ sourceId TEXT NOT NULL,
43
+ messageId TEXT,
44
+ timestamp TEXT,
45
+ name TEXT NOT NULL,
46
+ input TEXT,
47
+ output TEXT,
48
+ PRIMARY KEY (harness, sessionId, sourceId)
49
+ );
50
+ CREATE TABLE IF NOT EXISTS timeline (
51
+ harness TEXT NOT NULL,
52
+ sessionId TEXT NOT NULL,
53
+ sourceId TEXT NOT NULL,
54
+ timestamp TEXT,
55
+ kind TEXT NOT NULL,
56
+ detail TEXT NOT NULL,
57
+ PRIMARY KEY (harness, sessionId, sourceId, kind)
58
+ );
59
+ CREATE TABLE IF NOT EXISTS sourceCursors (
60
+ sourcePath TEXT PRIMARY KEY,
61
+ harness TEXT NOT NULL,
62
+ offsetBytes INTEGER NOT NULL DEFAULT 0,
63
+ sourceSize INTEGER NOT NULL DEFAULT 0,
64
+ sourceModifiedMs REAL NOT NULL DEFAULT 0,
65
+ updatedAt TEXT NOT NULL
66
+ );
67
+ CREATE TABLE IF NOT EXISTS sourceRecords (
68
+ harness TEXT NOT NULL,
69
+ sourcePath TEXT NOT NULL,
70
+ sourcePosition INTEGER NOT NULL,
71
+ sessionId TEXT NOT NULL,
72
+ rawJson TEXT NOT NULL,
73
+ PRIMARY KEY (harness, sourcePath, sourcePosition)
74
+ );
75
+ CREATE TABLE IF NOT EXISTS messageLabels (
76
+ harness TEXT NOT NULL,
77
+ sessionId TEXT NOT NULL,
78
+ sourceId TEXT NOT NULL,
79
+ modelId TEXT NOT NULL,
80
+ label TEXT NOT NULL,
81
+ score REAL NOT NULL,
82
+ labeledAt TEXT NOT NULL,
83
+ PRIMARY KEY (harness, sessionId, sourceId, modelId)
84
+ );
85
+ CREATE TABLE IF NOT EXISTS warningLeadUps (
86
+ harness TEXT NOT NULL,
87
+ sessionId TEXT NOT NULL,
88
+ warningSourceId TEXT NOT NULL,
89
+ sourceId TEXT NOT NULL,
90
+ distance INTEGER NOT NULL,
91
+ PRIMARY KEY (harness, sessionId, warningSourceId, sourceId)
92
+ );
93
+ CREATE TABLE IF NOT EXISTS searchChunks (
94
+ id INTEGER PRIMARY KEY,
95
+ harness TEXT NOT NULL,
96
+ sessionId TEXT NOT NULL,
97
+ chunkStart INTEGER NOT NULL,
98
+ messageIds TEXT NOT NULL,
99
+ text TEXT NOT NULL,
100
+ textHash TEXT NOT NULL,
101
+ modelId TEXT NOT NULL,
102
+ vector BLOB NOT NULL,
103
+ UNIQUE (harness, sessionId, chunkStart)
104
+ );
105
+ CREATE VIRTUAL TABLE IF NOT EXISTS searchChunksFts USING fts5(text);
106
+ CREATE TABLE IF NOT EXISTS indexState (
107
+ stage TEXT PRIMARY KEY,
108
+ modelId TEXT NOT NULL,
109
+ indexedAt TEXT NOT NULL,
110
+ chunks INTEGER NOT NULL
111
+ );
112
+ CREATE INDEX IF NOT EXISTS messagesByTime ON messages(harness, sessionId, timestamp);
113
+ CREATE INDEX IF NOT EXISTS timelineByTime ON timeline(timestamp);
114
+ `)
115
+ return db
116
+ }
@@ -0,0 +1,71 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+
5
+ const packageFile = new URL('../../../package.json', import.meta.url)
6
+ const releaseFile = new URL('../../../release.json', import.meta.url)
7
+
8
+ export function installedVersion() {
9
+ const manifest = JSON.parse(readFileSync(packageFile, 'utf8'))
10
+ const release = existsSync(releaseFile) ? JSON.parse(readFileSync(releaseFile, 'utf8')) : null
11
+ return { version: manifest.version, build: release?.build || null, commit: release?.commit || null }
12
+ }
13
+
14
+ function compareVersion(a, b) {
15
+ const parse = (value) => {
16
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/.exec(value || '')
17
+ return match ? { core: match.slice(1, 4).map(Number), pre: match[4] || '' } : null
18
+ }
19
+ const left = parse(a)
20
+ const right = parse(b)
21
+ if (!left || !right) return 0
22
+ for (let i = 0; i < 3; i++) if (left.core[i] !== right.core[i]) return Math.sign(left.core[i] - right.core[i])
23
+ if (!left.pre && right.pre) return 1
24
+ if (left.pre && !right.pre) return -1
25
+ if (!left.pre && !right.pre) return 0
26
+ const l = left.pre.split('.')
27
+ const r = right.pre.split('.')
28
+ for (let i = 0; i < Math.max(l.length, r.length); i++) {
29
+ if (l[i] === undefined) return -1
30
+ if (r[i] === undefined) return 1
31
+ if (l[i] === r[i]) continue
32
+ const ln = /^\d+$/.test(l[i])
33
+ const rn = /^\d+$/.test(r[i])
34
+ if (ln && rn) return Math.sign(Number(l[i]) - Number(r[i]))
35
+ if (ln !== rn) return ln ? -1 : 1
36
+ return l[i] < r[i] ? -1 : 1
37
+ }
38
+ return 0
39
+ }
40
+
41
+ async function jsonAt(url) {
42
+ try {
43
+ const response = await fetch(url, {
44
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'cheatingkit-cli' },
45
+ signal: AbortSignal.timeout(2000),
46
+ })
47
+ return response.ok ? await response.json() : null
48
+ } catch { return null }
49
+ }
50
+
51
+ export async function checkUpdates(config, force = false) {
52
+ if (config.updates?.check === false) return { status: 'disabled' }
53
+ const file = join(homedir(), '.cheatingkit', 'updates.json')
54
+ const track = config.updates?.track === 'nightly' ? 'nightly' : 'stable'
55
+ const old = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null
56
+ const due = !old || old.track !== track || Date.now() - Date.parse(old.checkedAt) >= (config.updates?.intervalHours || 24) * 3_600_000
57
+ if (!force && !due) return old
58
+ const current = installedVersion().version
59
+ const tags = await jsonAt('https://registry.npmjs.org/-/package/cheatingkit/dist-tags')
60
+ const version = track === 'nightly' ? tags?.next : tags?.latest
61
+ const best = /^\d+\.\d+\.\d+(?:-nightly\.\d{12}\.[0-9a-f]{7})?$/.test(version || '')
62
+ ? { version, url: `https://www.npmjs.com/package/cheatingkit/v/${version}` }
63
+ : null
64
+ const state = {
65
+ checkedAt: new Date().toISOString(), track, status: !best ? 'unavailable' : compareVersion(best.version, current) > 0 ? 'newer' : 'current',
66
+ current, version: best?.version || null, url: best?.url || null,
67
+ }
68
+ mkdirSync(dirname(file), { recursive: true })
69
+ writeFileSync(file, JSON.stringify(state, null, 2) + '\n')
70
+ return state
71
+ }