mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Enhance CLI commands with partial matching and formatting
Add partial-match utility for fuzzy loop name lookup. Introduce ralph-format helpers for consistent output formatting. Improve status, cancel, and list commands with better UX.
This commit is contained in:
1 parent
fbf259f22c
commit
c2d502f893
18 files changed
+2479
-694
No files matched your search
@@ -3,79 +3,21 @@ import { openDatabase, confirm } from '../utils'
|
||||
import { execSync, spawnSync } from 'child_process'
|
||||
import { existsSync } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
import { findPartialMatch } from '../../utils/partial-match'
|
||||
|
||||
interface CancelOptions {
|
||||
projectId?: string
|
||||
export interface CancelArgs {
|
||||
dbPath?: string
|
||||
resolvedProjectId?: string
|
||||
name?: string
|
||||
cleanup?: boolean
|
||||
force?: boolean
|
||||
help?: boolean
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): CancelOptions & { worktreeName?: string } {
|
||||
const options: CancelOptions & { worktreeName?: string } = {}
|
||||
let i = 0
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--cleanup') {
|
||||
options.cleanup = true
|
||||
} else if (arg === '--force') {
|
||||
options.force = true
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true
|
||||
} else if (!arg.startsWith('-')) {
|
||||
options.worktreeName = arg
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Cancel a Ralph loop
|
||||
|
||||
Usage:
|
||||
ocm-mem cancel [name] [options]
|
||||
|
||||
Arguments:
|
||||
name Worktree name to cancel (optional if only one active)
|
||||
|
||||
Options:
|
||||
--cleanup Remove worktree directory after cancellation
|
||||
--force Skip confirmation prompt
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export async function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): Promise<void> {
|
||||
const options = parseArgs(args)
|
||||
options.projectId = options.projectId || globalOpts.projectId
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const db = openDatabase(options.dbPath)
|
||||
export async function run(argv: CancelArgs): Promise<void> {
|
||||
const db = openDatabase(argv.dbPath)
|
||||
|
||||
try {
|
||||
const projectId = options.projectId
|
||||
const projectId = argv.resolvedProjectId
|
||||
|
||||
const now = Date.now()
|
||||
let query: string
|
||||
@@ -123,11 +65,23 @@ export async function run(args: string[], globalOpts: { dbPath?: string; project
|
||||
|
||||
let loopToCancel: { state: RalphState; row: { project_id: string; key: string; data: string } } | undefined
|
||||
|
||||
if (options.worktreeName) {
|
||||
loopToCancel = loops.find((l) => l.state.worktreeName === options.worktreeName)
|
||||
if (argv.name) {
|
||||
const { match, candidates } = findPartialMatch(argv.name, loops, (l) => [
|
||||
l.state.worktreeName,
|
||||
l.state.worktreeBranch,
|
||||
])
|
||||
|
||||
if (!loopToCancel) {
|
||||
console.error(`Ralph loop not found: ${options.worktreeName}`)
|
||||
if (!match && candidates.length > 0) {
|
||||
console.error(`Multiple loops match '${argv.name}':`)
|
||||
for (const c of candidates) {
|
||||
console.error(` - ${c.state.worktreeName}`)
|
||||
}
|
||||
console.error('')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!match && candidates.length === 0) {
|
||||
console.error(`Ralph loop not found: ${argv.name}`)
|
||||
console.error('')
|
||||
console.error('Active loops:')
|
||||
for (const l of loops) {
|
||||
@@ -136,6 +90,8 @@ export async function run(args: string[], globalOpts: { dbPath?: string; project
|
||||
console.error('')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
loopToCancel = match!
|
||||
} else {
|
||||
if (loops.length === 1) {
|
||||
loopToCancel = loops[0]
|
||||
@@ -166,62 +122,100 @@ export async function run(args: string[], globalOpts: { dbPath?: string; project
|
||||
console.log(` Session: ${state.sessionId}`)
|
||||
console.log(` Iteration: ${state.iteration}/${state.maxIterations}`)
|
||||
console.log(` Phase: ${state.phase}`)
|
||||
if (options.cleanup) {
|
||||
if (argv.cleanup) {
|
||||
console.log(` Worktree: ${state.worktreeDir} (will be removed)`)
|
||||
}
|
||||
console.log('')
|
||||
|
||||
await runCancel(db, loopToCancel, options)
|
||||
const shouldProceed = argv.force || await confirm(`Cancel Ralph loop '${state.worktreeName}'`)
|
||||
|
||||
if (!shouldProceed) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
|
||||
const updatedState = {
|
||||
...state,
|
||||
active: false,
|
||||
completedAt: new Date().toISOString(),
|
||||
terminationReason: 'cancelled',
|
||||
}
|
||||
db.prepare('UPDATE project_kv SET data = ?, updated_at = ? WHERE project_id = ? AND key = ?').run(
|
||||
JSON.stringify(updatedState),
|
||||
Date.now(),
|
||||
loopToCancel.row.project_id,
|
||||
loopToCancel.row.key,
|
||||
)
|
||||
|
||||
console.log(`Cancelled Ralph loop: ${state.worktreeName}`)
|
||||
|
||||
if (argv.cleanup && state.worktreeDir && !state.inPlace) {
|
||||
if (existsSync(state.worktreeDir)) {
|
||||
try {
|
||||
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
|
||||
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
|
||||
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
|
||||
if (removeResult.status !== 0) {
|
||||
throw new Error(removeResult.stderr || 'git worktree remove failed')
|
||||
}
|
||||
console.log(`Removed worktree: ${state.worktreeDir}`)
|
||||
} catch {
|
||||
console.error(`Failed to remove worktree: ${state.worktreeDir}`)
|
||||
console.error('You may need to remove it manually.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('')
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runCancel(
|
||||
db: ReturnType<typeof openDatabase>,
|
||||
loopToCancel: { state: RalphState; row: { project_id: string; key: string; data: string } },
|
||||
options: CancelOptions & { worktreeName?: string },
|
||||
): Promise<void> {
|
||||
const { state } = loopToCancel
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Cancel a Ralph loop
|
||||
|
||||
const shouldProceed = options.force || await confirm(`Cancel Ralph loop '${state.worktreeName}'`)
|
||||
Usage:
|
||||
ocm-mem cancel [name] [options]
|
||||
|
||||
if (!shouldProceed) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
Arguments:
|
||||
name Worktree name to cancel (optional if only one active)
|
||||
|
||||
const updatedState = {
|
||||
...state,
|
||||
active: false,
|
||||
completedAt: new Date().toISOString(),
|
||||
terminationReason: 'cancelled',
|
||||
}
|
||||
db.prepare('UPDATE project_kv SET data = ?, updated_at = ? WHERE project_id = ? AND key = ?').run(
|
||||
JSON.stringify(updatedState),
|
||||
Date.now(),
|
||||
loopToCancel.row.project_id,
|
||||
loopToCancel.row.key,
|
||||
)
|
||||
|
||||
console.log(`Cancelled Ralph loop: ${state.worktreeName}`)
|
||||
|
||||
if (options.cleanup && state.worktreeDir && !state.inPlace) {
|
||||
if (existsSync(state.worktreeDir)) {
|
||||
try {
|
||||
const gitCommonDir = execSync('git rev-parse --git-common-dir', { cwd: state.worktreeDir, encoding: 'utf-8' }).trim()
|
||||
const gitRoot = resolve(state.worktreeDir, gitCommonDir, '..')
|
||||
const removeResult = spawnSync('git', ['worktree', 'remove', '-f', state.worktreeDir], { cwd: gitRoot, encoding: 'utf-8' })
|
||||
if (removeResult.status !== 0) {
|
||||
throw new Error(removeResult.stderr || 'git worktree remove failed')
|
||||
}
|
||||
console.log(`Removed worktree: ${state.worktreeDir}`)
|
||||
} catch {
|
||||
console.error(`Failed to remove worktree: ${state.worktreeDir}`)
|
||||
console.error('You may need to remove it manually.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('')
|
||||
Options:
|
||||
--cleanup Remove worktree directory after cancellation
|
||||
--force Skip confirmation prompt
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export async function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): Promise<void> {
|
||||
const argv: CancelArgs = {
|
||||
dbPath: globalOpts.dbPath,
|
||||
resolvedProjectId: globalOpts.resolvedProjectId,
|
||||
}
|
||||
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
if (arg === '--cleanup') {
|
||||
argv.cleanup = true
|
||||
} else if (arg === '--force') {
|
||||
argv.force = true
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else if (!arg.startsWith('-')) {
|
||||
argv.name = arg
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
await run(argv)
|
||||
}
|
||||
@@ -1,75 +1,134 @@
|
||||
import { openDatabase, formatDate, truncate, confirm, resolveProjectNames, displayProjectId, MemoryScope } from '../utils'
|
||||
import { existsSync, readFileSync } from 'fs'
|
||||
import { openDatabase, formatDate, truncate, confirm } from '../utils'
|
||||
import { existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { homedir, platform } from 'os'
|
||||
import { execSync } from 'child_process'
|
||||
import { createConnection } from 'net'
|
||||
|
||||
interface CleanupOptions {
|
||||
export interface CleanupArgs {
|
||||
dbPath?: string
|
||||
resolvedProjectId?: string
|
||||
olderThan?: number
|
||||
ids?: number[]
|
||||
scope?: MemoryScope
|
||||
ids?: string
|
||||
scope?: 'convention' | 'decision' | 'context'
|
||||
all?: boolean
|
||||
dryRun?: boolean
|
||||
force?: boolean
|
||||
projectId?: string
|
||||
dbPath?: string
|
||||
help?: boolean
|
||||
vecWorkers?: boolean
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): CleanupOptions {
|
||||
const options: CleanupOptions = {}
|
||||
let i = 0
|
||||
export async function run(argv: CleanupArgs): Promise<void> {
|
||||
if (argv.vecWorkers) {
|
||||
const result = await cleanupVecWorkers()
|
||||
console.log(result)
|
||||
return
|
||||
}
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
if (!argv.olderThan && !argv.ids && !argv.all) {
|
||||
console.error('At least one filter must be provided: --older-than, --ids, or --all')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (arg === '--older-than') {
|
||||
options.olderThan = parseInt(args[++i], 10)
|
||||
if (isNaN(options.olderThan)) {
|
||||
console.error('Invalid --older-than value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--ids') {
|
||||
const idsStr = args[++i]
|
||||
options.ids = idsStr.split(',').map((id) => parseInt(id.trim(), 10)).filter((id) => !isNaN(id))
|
||||
if (options.ids.length === 0) {
|
||||
const projectId = argv.resolvedProjectId
|
||||
|
||||
if (argv.all && !projectId) {
|
||||
console.error('--all requires --project to be specified')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
console.error('Project ID required. Use --project or run from a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const db = openDatabase(argv.dbPath)
|
||||
|
||||
try {
|
||||
let query = 'SELECT id, project_id, scope, content, created_at FROM memories WHERE project_id = ?'
|
||||
const params: (string | number)[] = [projectId]
|
||||
|
||||
if (argv.olderThan) {
|
||||
const cutoffTime = Date.now() - argv.olderThan * 24 * 60 * 60 * 1000
|
||||
query += ' AND created_at < ?'
|
||||
params.push(cutoffTime)
|
||||
}
|
||||
|
||||
if (argv.ids) {
|
||||
const parsedIds = argv.ids.split(',').map((id) => parseInt(id.trim(), 10)).filter((id) => !isNaN(id))
|
||||
if (parsedIds.length === 0) {
|
||||
console.error('Invalid --ids value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--scope') {
|
||||
const scope = args[++i] as MemoryScope
|
||||
if (scope !== 'convention' && scope !== 'decision' && scope !== 'context') {
|
||||
console.error(`Unknown scope '${scope}'. Use 'convention', 'decision', or 'context'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.scope = scope
|
||||
} else if (arg === '--all') {
|
||||
options.all = true
|
||||
} else if (arg === '--dry-run') {
|
||||
options.dryRun = true
|
||||
} else if (arg === '--force') {
|
||||
options.force = true
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--vec-workers') {
|
||||
options.vecWorkers = true
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
query += ` AND id IN (${parsedIds.map(() => '?').join(',')})`
|
||||
params.push(...parsedIds)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
if (argv.scope) {
|
||||
query += ' AND scope = ?'
|
||||
params.push(argv.scope)
|
||||
}
|
||||
|
||||
return options
|
||||
if (argv.all) {
|
||||
query = 'SELECT id, project_id, scope, content, created_at FROM memories WHERE project_id = ?'
|
||||
params.length = 0
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const rows = db.prepare(query).all(...params) as Array<{
|
||||
id: number
|
||||
project_id: string
|
||||
scope: string
|
||||
content: string
|
||||
created_at: number
|
||||
}>
|
||||
|
||||
if (rows.length === 0) {
|
||||
console.log('No memories found to delete.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(`Found ${rows.length} memories to delete:`)
|
||||
console.log(' ID SCOPE CREATED CONTENT')
|
||||
|
||||
const displayRows = rows.slice(0, 20)
|
||||
for (const row of displayRows) {
|
||||
const id = String(row.id).padEnd(6)
|
||||
const scope = row.scope.padEnd(12)
|
||||
const created = formatDate(row.created_at)
|
||||
const content = truncate(row.content, 40)
|
||||
console.log(` ${id} ${scope} ${created} ${content}`)
|
||||
}
|
||||
|
||||
if (rows.length > 20) {
|
||||
console.log(` ... and ${rows.length - 20} more`)
|
||||
}
|
||||
|
||||
console.log('')
|
||||
|
||||
if (argv.dryRun) {
|
||||
console.log('Dry run - no memories deleted.')
|
||||
return
|
||||
}
|
||||
|
||||
const shouldProceed = argv.force || await confirm(`Delete ${rows.length} memories`)
|
||||
|
||||
if (!shouldProceed) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
|
||||
const idsToDelete = rows.map((r) => r.id)
|
||||
const deleteQuery = `DELETE FROM memories WHERE id IN (${idsToDelete.map(() => '?').join(',')})`
|
||||
db.prepare(deleteQuery).run(...idsToDelete)
|
||||
|
||||
const remainingCount = db.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?').get(projectId) as { count: number }
|
||||
|
||||
console.log(`Deleted ${rows.length} memories. ${remainingCount.count} remaining.`)
|
||||
console.log("Note: Run 'memory-health reindex' in OpenCode to clean up orphaned embeddings.")
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
@@ -87,132 +146,55 @@ Options:
|
||||
--all Delete all memories for the project (requires --project)
|
||||
--dry-run Preview what would be deleted without deleting
|
||||
--force Skip confirmation prompt
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--vec-workers Clean up orphaned vec-worker processes
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export async function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): Promise<void> {
|
||||
const options = parseArgs(args)
|
||||
options.projectId = options.projectId || globalOpts.projectId
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
export async function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): Promise<void> {
|
||||
const argv: CleanupArgs = {
|
||||
dbPath: globalOpts.dbPath,
|
||||
resolvedProjectId: globalOpts.resolvedProjectId,
|
||||
}
|
||||
|
||||
if (options.vecWorkers) {
|
||||
const result = await cleanupVecWorkers()
|
||||
console.log(result)
|
||||
return
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
if (arg === '--older-than') {
|
||||
argv.olderThan = parseInt(args[++i], 10)
|
||||
if (isNaN(argv.olderThan)) {
|
||||
console.error('Invalid --older-than value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--ids') {
|
||||
argv.ids = args[++i]
|
||||
} else if (arg === '--scope') {
|
||||
const scope = args[++i] as 'convention' | 'decision' | 'context'
|
||||
if (scope !== 'convention' && scope !== 'decision' && scope !== 'context') {
|
||||
console.error(`Unknown scope '${scope}'. Use 'convention', 'decision', or 'context'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
argv.scope = scope
|
||||
} else if (arg === '--all') {
|
||||
argv.all = true
|
||||
} else if (arg === '--dry-run') {
|
||||
argv.dryRun = true
|
||||
} else if (arg === '--force') {
|
||||
argv.force = true
|
||||
} else if (arg === '--vec-workers') {
|
||||
argv.vecWorkers = true
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if (!options.olderThan && !options.ids && !options.all) {
|
||||
console.error('At least one filter must be provided: --older-than, --ids, or --all')
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (options.all && !options.projectId) {
|
||||
console.error('--all requires --project to be specified')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!options.projectId) {
|
||||
console.error('Project ID required. Use --project or run from a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const db = openDatabase(options.dbPath || globalOpts.dbPath)
|
||||
|
||||
try {
|
||||
runMemoryCleanup(db, options)
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runMemoryCleanup(db: ReturnType<typeof openDatabase>, options: CleanupOptions): Promise<void> {
|
||||
const projectId = options.projectId!
|
||||
let query = 'SELECT id, project_id, scope, content, created_at FROM memories WHERE project_id = ?'
|
||||
const params: (string | number)[] = [projectId]
|
||||
|
||||
if (options.olderThan) {
|
||||
const cutoffTime = Date.now() - options.olderThan * 24 * 60 * 60 * 1000
|
||||
query += ' AND created_at < ?'
|
||||
params.push(cutoffTime)
|
||||
}
|
||||
|
||||
if (options.ids && options.ids.length > 0) {
|
||||
query += ` AND id IN (${options.ids.map(() => '?').join(',')})`
|
||||
params.push(...options.ids)
|
||||
}
|
||||
|
||||
if (options.scope) {
|
||||
query += ' AND scope = ?'
|
||||
params.push(options.scope)
|
||||
}
|
||||
|
||||
if (options.all) {
|
||||
query = 'SELECT id, project_id, scope, content, created_at FROM memories WHERE project_id = ?'
|
||||
params.length = 0
|
||||
params.push(projectId)
|
||||
}
|
||||
|
||||
const rows = db.prepare(query).all(...params) as Array<{
|
||||
id: number
|
||||
project_id: string
|
||||
scope: string
|
||||
content: string
|
||||
created_at: number
|
||||
}>
|
||||
|
||||
if (rows.length === 0) {
|
||||
console.log('No memories found to delete.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(`Found ${rows.length} memories to delete:`)
|
||||
console.log(' ID SCOPE CREATED CONTENT')
|
||||
|
||||
const displayRows = rows.slice(0, 20)
|
||||
for (const row of displayRows) {
|
||||
const id = String(row.id).padEnd(6)
|
||||
const scope = row.scope.padEnd(12)
|
||||
const created = formatDate(row.created_at)
|
||||
const content = truncate(row.content, 40)
|
||||
console.log(` ${id} ${scope} ${created} ${content}`)
|
||||
}
|
||||
|
||||
if (rows.length > 20) {
|
||||
console.log(` ... and ${rows.length - 20} more`)
|
||||
}
|
||||
|
||||
console.log('')
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log('Dry run - no memories deleted.')
|
||||
return
|
||||
}
|
||||
|
||||
const shouldProceed = options.force || await confirm(`Delete ${rows.length} memories`)
|
||||
|
||||
if (!shouldProceed) {
|
||||
console.log('Cancelled.')
|
||||
return
|
||||
}
|
||||
|
||||
const idsToDelete = rows.map((r) => r.id)
|
||||
const deleteQuery = `DELETE FROM memories WHERE id IN (${idsToDelete.map(() => '?').join(',')})`
|
||||
db.prepare(deleteQuery).run(...idsToDelete)
|
||||
|
||||
const remainingCount = db.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?').get(projectId) as { count: number }
|
||||
|
||||
console.log(`Deleted ${rows.length} memories. ${remainingCount.count} remaining.`)
|
||||
console.log("Note: Run 'memory-health reindex' in OpenCode to clean up orphaned embeddings.")
|
||||
await run(argv)
|
||||
}
|
||||
|
||||
export async function cleanupVecWorkers(): Promise<string> {
|
||||
@@ -237,7 +219,7 @@ export async function cleanupVecWorkers(): Promise<string> {
|
||||
process.kill(worker.pid, 'SIGTERM')
|
||||
results.push(`✗ PID ${worker.pid} - terminated (was orphaned)`)
|
||||
cleaned++
|
||||
} catch (err) {
|
||||
} catch {
|
||||
results.push(`✗ PID ${worker.pid} - failed to terminate`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,14 +7,14 @@ import {
|
||||
MemoryScope,
|
||||
} from '../utils'
|
||||
|
||||
export interface ExportOptions {
|
||||
export interface ExportArgs {
|
||||
dbPath?: string
|
||||
resolvedProjectId?: string
|
||||
format?: 'json' | 'markdown'
|
||||
output?: string
|
||||
projectId?: string
|
||||
scope?: MemoryScope
|
||||
scope?: 'convention' | 'decision' | 'context'
|
||||
limit?: number
|
||||
offset?: number
|
||||
dbPath?: string
|
||||
}
|
||||
|
||||
export function formatAsJson(memories: PluginMemory[]): string {
|
||||
@@ -49,27 +49,27 @@ export function formatAsMarkdown(memories: PluginMemory[]): string {
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function exportMemories(options: ExportOptions): void {
|
||||
const db = openDatabase(options.dbPath)
|
||||
export function run(argv: ExportArgs): void {
|
||||
const projectId = argv.resolvedProjectId
|
||||
|
||||
if (!projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const db = openDatabase(argv.dbPath)
|
||||
|
||||
try {
|
||||
if (!options.projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const projectId = options.projectId
|
||||
|
||||
const conditions: string[] = ['project_id = ?']
|
||||
const params: (string | number)[] = [projectId]
|
||||
|
||||
if (options.scope) {
|
||||
if (argv.scope) {
|
||||
conditions.push('scope = ?')
|
||||
params.push(options.scope)
|
||||
params.push(argv.scope)
|
||||
}
|
||||
|
||||
const limit = options.limit ?? 1000
|
||||
const offset = options.offset ?? 0
|
||||
const limit = argv.limit ?? 1000
|
||||
const offset = argv.offset ?? 0
|
||||
|
||||
const query = `
|
||||
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
|
||||
@@ -103,7 +103,7 @@ function exportMemories(options: ExportOptions): void {
|
||||
updatedAt: row.updated_at,
|
||||
}))
|
||||
|
||||
const format = options.format || 'json'
|
||||
const format = argv.format || 'json'
|
||||
let output: string
|
||||
|
||||
if (format === 'markdown') {
|
||||
@@ -112,9 +112,9 @@ function exportMemories(options: ExportOptions): void {
|
||||
output = formatAsJson(memories)
|
||||
}
|
||||
|
||||
if (options.output) {
|
||||
writeFileSync(options.output, output, 'utf-8')
|
||||
console.log(`Exported ${memories.length} memories to ${options.output}`)
|
||||
if (argv.output) {
|
||||
writeFileSync(argv.output, output, 'utf-8')
|
||||
console.log(`Exported ${memories.length} memories to ${argv.output}`)
|
||||
} else {
|
||||
console.log(output)
|
||||
}
|
||||
@@ -123,60 +123,6 @@ function exportMemories(options: ExportOptions): void {
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): ExportOptions {
|
||||
const options: ExportOptions = {}
|
||||
let i = 0
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = args[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.format = format
|
||||
} else if (arg === '--output' || arg === '-o') {
|
||||
options.output = args[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--scope' || arg === '-s') {
|
||||
const scope = args[++i] as MemoryScope
|
||||
if (scope !== 'convention' && scope !== 'decision' && scope !== 'context') {
|
||||
console.error(`Unknown scope '${scope}'. Use 'convention', 'decision', or 'context'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.scope = scope
|
||||
} else if (arg === '--limit' || arg === '-l') {
|
||||
options.limit = parseInt(args[++i], 10)
|
||||
if (isNaN(options.limit)) {
|
||||
console.error('Invalid limit value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--offset') {
|
||||
options.offset = parseInt(args[++i], 10)
|
||||
if (isNaN(options.offset ?? 0)) {
|
||||
console.error('Invalid offset value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Export memories from the database
|
||||
@@ -187,7 +133,6 @@ Usage:
|
||||
Options:
|
||||
--format, -f <format> Output format: json or markdown (default: json)
|
||||
--output, -o <file> Output file path (prints to stdout if not specified)
|
||||
--project, -p <id> Project ID to filter by (auto-detected from git if not provided)
|
||||
--scope, -s <scope> Filter by scope: convention, decision, or context
|
||||
--limit, -l <n> Limit number of memories (default: 1000)
|
||||
--offset <n> Offset for pagination (default: 0)
|
||||
@@ -196,10 +141,53 @@ Options:
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
options.projectId = options.projectId || globalOpts.projectId
|
||||
export function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): void {
|
||||
const argv: ExportArgs = {
|
||||
dbPath: globalOpts.dbPath,
|
||||
resolvedProjectId: globalOpts.resolvedProjectId,
|
||||
}
|
||||
|
||||
exportMemories(options)
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = args[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
argv.format = format
|
||||
} else if (arg === '--output' || arg === '-o') {
|
||||
argv.output = args[++i]
|
||||
} else if (arg === '--scope' || arg === '-s') {
|
||||
const scope = args[++i] as 'convention' | 'decision' | 'context'
|
||||
if (scope !== 'convention' && scope !== 'decision' && scope !== 'context') {
|
||||
console.error(`Unknown scope '${scope}'. Use 'convention', 'decision', or 'context'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
argv.scope = scope
|
||||
} else if (arg === '--limit' || arg === '-l') {
|
||||
argv.limit = parseInt(args[++i], 10)
|
||||
if (isNaN(argv.limit)) {
|
||||
console.error('Invalid limit value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--offset') {
|
||||
argv.offset = parseInt(args[++i], 10)
|
||||
if (isNaN(argv.offset ?? 0)) {
|
||||
console.error('Invalid offset value')
|
||||
process.exit(1)
|
||||
}
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
run(argv)
|
||||
}
|
||||
@@ -6,11 +6,12 @@ import {
|
||||
MemoryScope,
|
||||
} from '../utils'
|
||||
|
||||
export interface ImportOptions {
|
||||
format?: 'json' | 'markdown'
|
||||
projectId: string
|
||||
force?: boolean
|
||||
export interface ImportArgs {
|
||||
dbPath?: string
|
||||
resolvedProjectId?: string
|
||||
file: string
|
||||
format?: 'json' | 'markdown'
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
export function parseJsonImport(content: string, projectId: string): PluginMemory[] {
|
||||
@@ -20,17 +21,22 @@ export function parseJsonImport(content: string, projectId: string): PluginMemor
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
return data.map((item: Record<string, unknown>, index: number) => ({
|
||||
id: 0,
|
||||
projectId: (item.projectId as string) || projectId,
|
||||
scope: (item.scope as MemoryScope) || 'context',
|
||||
content: item.content as string,
|
||||
filePath: (item.filePath as string) || null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: (item.createdAt as number) || now,
|
||||
updatedAt: (item.updatedAt as number) || now,
|
||||
}))
|
||||
return data.map((item: Record<string, unknown>) => {
|
||||
if (!item.content || typeof item.content !== 'string') {
|
||||
throw new Error('Invalid memory: missing or invalid content field')
|
||||
}
|
||||
return {
|
||||
id: 0,
|
||||
projectId: (item.projectId as string) || projectId,
|
||||
scope: (item.scope as MemoryScope) || 'context',
|
||||
content: item.content as string,
|
||||
filePath: (item.filePath as string) || null,
|
||||
accessCount: 0,
|
||||
lastAccessedAt: null,
|
||||
createdAt: (item.createdAt as number) || now,
|
||||
updatedAt: (item.updatedAt as number) || now,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function parseMarkdownImport(content: string, projectId: string): PluginMemory[] {
|
||||
@@ -39,7 +45,6 @@ export function parseMarkdownImport(content: string, projectId: string): PluginM
|
||||
let currentScope: MemoryScope = 'context'
|
||||
let currentContent: string[] = []
|
||||
let currentCreatedAt = Date.now()
|
||||
let memoryIndex = 0
|
||||
|
||||
const scopePattern = /^##\s+(\w+)(?:s)?\s+\(\d+\)$/i
|
||||
const memoryPattern = /^###\s+\[(\d+)\]\s+-\s+Created\s+(\d{4}-\d{2}-\d{2})/
|
||||
@@ -82,7 +87,6 @@ export function parseMarkdownImport(content: string, projectId: string): PluginM
|
||||
const memoryMatch = line.match(memoryPattern)
|
||||
if (memoryMatch) {
|
||||
saveCurrentMemory()
|
||||
memoryIndex++
|
||||
try {
|
||||
currentCreatedAt = new Date(memoryMatch[2]).getTime()
|
||||
} catch {
|
||||
@@ -127,11 +131,18 @@ export function parseMarkdownImport(content: string, projectId: string): PluginM
|
||||
return memories
|
||||
}
|
||||
|
||||
function importMemories(filePath: string, options: ImportOptions): void {
|
||||
const db = openDatabase(options.dbPath)
|
||||
export function run(argv: ImportArgs): void {
|
||||
const projectId = argv.resolvedProjectId
|
||||
|
||||
if (!projectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
let filePath = argv.file
|
||||
if (filePath === '-') filePath = '/dev/stdin'
|
||||
|
||||
let content: string
|
||||
|
||||
try {
|
||||
content = readFileSync(filePath, 'utf-8')
|
||||
} catch {
|
||||
@@ -139,15 +150,14 @@ function importMemories(filePath: string, options: ImportOptions): void {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const format = options.format || (extname(filePath).toLowerCase() === '.md' ? 'markdown' : 'json')
|
||||
const format = argv.format || (extname(filePath).toLowerCase() === '.md' ? 'markdown' : 'json')
|
||||
|
||||
let memories: PluginMemory[]
|
||||
|
||||
try {
|
||||
if (format === 'markdown') {
|
||||
memories = parseMarkdownImport(content, options.projectId)
|
||||
memories = parseMarkdownImport(content, projectId)
|
||||
} else {
|
||||
memories = parseJsonImport(content, options.projectId)
|
||||
memories = parseJsonImport(content, projectId)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to parse ${format} file: ${error instanceof Error ? error.message : 'Unknown error'}`)
|
||||
@@ -159,17 +169,19 @@ function importMemories(filePath: string, options: ImportOptions): void {
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const db = openDatabase(argv.dbPath)
|
||||
|
||||
try {
|
||||
let importedCount = 0
|
||||
let skippedCount = 0
|
||||
|
||||
for (const memory of memories) {
|
||||
memory.projectId = options.projectId
|
||||
memory.projectId = projectId
|
||||
|
||||
if (!options.force) {
|
||||
if (!argv.force) {
|
||||
const existing = db
|
||||
.prepare('SELECT id FROM memories WHERE project_id = ? AND content = ? LIMIT 1')
|
||||
.get(options.projectId, memory.content)
|
||||
.get(projectId, memory.content)
|
||||
|
||||
if (existing) {
|
||||
skippedCount++
|
||||
@@ -200,52 +212,6 @@ function importMemories(filePath: string, options: ImportOptions): void {
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { filePath: string; options: ImportOptions } {
|
||||
const options: ImportOptions = { projectId: '' }
|
||||
let filePath = args[0]
|
||||
let i = 1
|
||||
|
||||
if (!filePath || filePath.startsWith('-')) {
|
||||
console.error('Import requires a file path')
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (filePath === '-') {
|
||||
filePath = '/dev/stdin'
|
||||
}
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = args[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
options.format = format
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--force') {
|
||||
options.force = true
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { filePath, options }
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Import memories into the database
|
||||
@@ -258,22 +224,53 @@ Arguments:
|
||||
|
||||
Options:
|
||||
--format, -f <format> Input format: json or markdown (auto-detected from extension)
|
||||
--project, -p <id> Project ID to assign memories to (required, auto-detected from git)
|
||||
--force Skip duplicate detection and import all memories
|
||||
--db-path <path> Path to database file
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const { filePath, options } = parseArgs(args)
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
options.projectId = options.projectId || globalOpts.projectId || ''
|
||||
export function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): void {
|
||||
const filePath = args[0]
|
||||
if (!filePath || filePath.startsWith('-') && filePath !== '-') {
|
||||
console.error('Import requires a file path')
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!options.projectId) {
|
||||
const argv: ImportArgs = {
|
||||
dbPath: globalOpts.dbPath,
|
||||
resolvedProjectId: globalOpts.resolvedProjectId,
|
||||
file: filePath === '-' ? '/dev/stdin' : filePath,
|
||||
}
|
||||
|
||||
let i = 1
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
if (arg === '--format' || arg === '-f') {
|
||||
const format = args[++i] as 'json' | 'markdown'
|
||||
if (format !== 'json' && format !== 'markdown') {
|
||||
console.error(`Unknown format '${format}'. Use 'json' or 'markdown'.`)
|
||||
process.exit(1)
|
||||
}
|
||||
argv.format = format
|
||||
} else if (arg === '--force') {
|
||||
argv.force = true
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if (!argv.resolvedProjectId) {
|
||||
console.error('Project ID required. Use --project or ensure this is a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
importMemories(filePath, options)
|
||||
run(argv)
|
||||
}
|
||||
@@ -7,52 +7,12 @@ interface ProjectMemoryStats {
|
||||
newest: number
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { dbPath?: string; help?: boolean } {
|
||||
const options: { dbPath?: string; help?: boolean } = {}
|
||||
let i = 0
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
export interface ListArgs {
|
||||
dbPath?: string
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
List projects with memory counts
|
||||
|
||||
Usage:
|
||||
ocm-mem list [options]
|
||||
|
||||
Options:
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const db = openDatabase(options.dbPath)
|
||||
export function run(argv: ListArgs): void {
|
||||
const db = openDatabase(argv.dbPath)
|
||||
const nameMap = resolveProjectNames()
|
||||
|
||||
try {
|
||||
@@ -84,3 +44,27 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
List projects with memory counts
|
||||
|
||||
Usage:
|
||||
ocm-mem list [options]
|
||||
|
||||
Options:
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): void {
|
||||
for (const arg of args) {
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
run({ dbPath: globalOpts.dbPath })
|
||||
}
|
||||
@@ -10,80 +10,37 @@ interface ProjectStats {
|
||||
newest: number
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { projectId?: string; dbPath?: string; help?: boolean } {
|
||||
const options: { projectId?: string; dbPath?: string; help?: boolean } = {}
|
||||
let i = 0
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
export interface StatsArgs {
|
||||
dbPath?: string
|
||||
resolvedProjectId?: string
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Show memory statistics for a project
|
||||
|
||||
Usage:
|
||||
ocm-mem stats [options]
|
||||
|
||||
Options:
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
const dbPath = options.dbPath || globalOpts.dbPath
|
||||
const projectId = options.projectId || globalOpts.projectId
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
export function run(argv: StatsArgs): void {
|
||||
const projectId = argv.resolvedProjectId
|
||||
|
||||
if (!projectId) {
|
||||
console.error('Project ID required. Use --project or run from a git repository.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const finalProjectId = projectId
|
||||
|
||||
const db = openDatabase(dbPath)
|
||||
const db = openDatabase(argv.dbPath)
|
||||
const nameMap = resolveProjectNames()
|
||||
|
||||
try {
|
||||
const scopeRows = db.prepare(`
|
||||
SELECT scope, COUNT(*) as count FROM memories
|
||||
WHERE project_id = ? GROUP BY scope
|
||||
`).all(finalProjectId) as ScopeStats[]
|
||||
`).all(projectId) as ScopeStats[]
|
||||
|
||||
const statsRow = db.prepare(`
|
||||
SELECT MIN(created_at) as oldest, MAX(created_at) as newest
|
||||
FROM memories WHERE project_id = ?
|
||||
`).get(finalProjectId) as ProjectStats | undefined
|
||||
`).get(projectId) as ProjectStats | undefined
|
||||
|
||||
const totalMemories = scopeRows.reduce((sum, row) => sum + row.count, 0)
|
||||
|
||||
console.log('')
|
||||
console.log(`Memory Statistics for: ${displayProjectId(finalProjectId, nameMap)}`)
|
||||
console.log(`Memory Statistics for: ${displayProjectId(projectId, nameMap)}`)
|
||||
console.log(` Total: ${totalMemories}`)
|
||||
console.log(' By scope:')
|
||||
|
||||
@@ -109,3 +66,28 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Show memory statistics for a project
|
||||
|
||||
Usage:
|
||||
ocm-mem stats [options]
|
||||
|
||||
Options:
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): void {
|
||||
for (const arg of args) {
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
run({ dbPath: globalOpts.dbPath, resolvedProjectId: globalOpts.resolvedProjectId })
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import type { RalphState } from '../../services/ralph'
|
||||
import { openDatabase } from '../utils'
|
||||
import { formatSessionOutput, formatAuditResult } from '../../utils/ralph-format'
|
||||
import { createOpencodeClient } from '@opencode-ai/sdk/v2'
|
||||
import { fetchSessionOutput } from '../../services/ralph'
|
||||
import { findPartialMatch, filterByPartial } from '../../utils/partial-match'
|
||||
|
||||
interface RalphLoopInfo {
|
||||
sessionId: string
|
||||
worktreeName: string
|
||||
worktreeBranch: string
|
||||
worktreeBranch?: string
|
||||
iteration: number
|
||||
maxIterations: number
|
||||
phase: 'coding' | 'auditing'
|
||||
@@ -12,65 +16,47 @@ interface RalphLoopInfo {
|
||||
audit: boolean
|
||||
}
|
||||
|
||||
function parseArgs(args: string[]): { projectId?: string; dbPath?: string; help?: boolean; worktreeName?: string } {
|
||||
const options: { projectId?: string; dbPath?: string; help?: boolean; worktreeName?: string } = {}
|
||||
let i = 0
|
||||
export interface StatusArgs {
|
||||
dbPath?: string
|
||||
resolvedProjectId?: string
|
||||
name?: string
|
||||
server?: string
|
||||
listWorktrees?: boolean
|
||||
listWorktreesFilter?: string
|
||||
}
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
export async function run(argv: StatusArgs): Promise<void> {
|
||||
const db = openDatabase(argv.dbPath)
|
||||
|
||||
if (arg === '--project' || arg === '-p') {
|
||||
options.projectId = args[++i]
|
||||
} else if (arg === '--db-path') {
|
||||
options.dbPath = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true
|
||||
} else if (!arg.startsWith('-')) {
|
||||
options.worktreeName = arg
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
async function tryFetchSessionOutput(serverUrl: string, sessionId: string, directory: string) {
|
||||
try {
|
||||
const client = createOpencodeClient({ baseUrl: serverUrl, directory })
|
||||
return await fetchSessionOutput(client, sessionId, directory)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Show Ralph loop status
|
||||
|
||||
Usage:
|
||||
ocm-mem status [options]
|
||||
ocm-mem status <name> [options]
|
||||
|
||||
Arguments:
|
||||
name Worktree name for detailed status (optional)
|
||||
|
||||
Options:
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export function run(args: string[], globalOpts: { dbPath?: string; projectId?: string }): void {
|
||||
const options = parseArgs(args)
|
||||
options.projectId = options.projectId || globalOpts.projectId
|
||||
options.dbPath = options.dbPath || globalOpts.dbPath
|
||||
|
||||
if (options.help) {
|
||||
help()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const db = openDatabase(options.dbPath)
|
||||
|
||||
try {
|
||||
const projectId = options.projectId
|
||||
if (argv.listWorktrees) {
|
||||
const rows = db.prepare('SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?').all('ralph:%', Date.now()) as Array<{ key: string; data: string }>
|
||||
const states: RalphState[] = []
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const state = JSON.parse(row.data) as RalphState
|
||||
states.push(state)
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
const filtered = filterByPartial(argv.listWorktreesFilter, states, (s) => [s.worktreeName, s.worktreeBranch])
|
||||
for (const state of filtered) {
|
||||
console.log(state.worktreeName)
|
||||
}
|
||||
db.close()
|
||||
return
|
||||
}
|
||||
|
||||
const projectId = argv.resolvedProjectId
|
||||
|
||||
const now = Date.now()
|
||||
let query: string
|
||||
@@ -114,13 +100,31 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const worktreeName = options.worktreeName
|
||||
const worktreeName = argv.name
|
||||
|
||||
if (worktreeName) {
|
||||
let activeLoop = activeLoops.find((l) => l.worktreeName === worktreeName)
|
||||
let recentLoop = recentLoops.find((l) => l.state.worktreeName === worktreeName)
|
||||
type LoopUnion = { type: 'active'; loop: RalphLoopInfo } | { type: 'recent'; loop: typeof recentLoops[number] }
|
||||
const allLoops: LoopUnion[] = [
|
||||
...activeLoops.map((l) => ({ type: 'active' as const, loop: l })),
|
||||
...recentLoops.map((l) => ({ type: 'recent' as const, loop: l })),
|
||||
]
|
||||
|
||||
if (!activeLoop && !recentLoop) {
|
||||
const { match, candidates } = findPartialMatch(worktreeName, allLoops, (l) => [
|
||||
l.type === 'active' ? l.loop.worktreeName : l.loop.state.worktreeName,
|
||||
l.type === 'active' ? l.loop.worktreeBranch : l.loop.state.worktreeBranch,
|
||||
])
|
||||
|
||||
if (!match && candidates.length > 0) {
|
||||
console.error(`Multiple loops match '${worktreeName}':`)
|
||||
for (const c of candidates) {
|
||||
const name = c.type === 'active' ? c.loop.worktreeName : c.loop.state.worktreeName
|
||||
console.error(` - ${name}`)
|
||||
}
|
||||
console.error('')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!match && candidates.length === 0) {
|
||||
console.error(`Ralph loop not found: ${worktreeName}`)
|
||||
console.error('')
|
||||
if (activeLoops.length > 0) {
|
||||
@@ -139,11 +143,16 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (activeLoop) {
|
||||
const matchedLoop = match!
|
||||
const resolvedWorktreeName = matchedLoop.type === 'active'
|
||||
? matchedLoop.loop.worktreeName
|
||||
: matchedLoop.loop.state.worktreeName
|
||||
|
||||
if (matchedLoop.type === 'active') {
|
||||
const row = rows.find((r) => {
|
||||
try {
|
||||
const state = JSON.parse(r.data) as RalphState
|
||||
return state.worktreeName === worktreeName
|
||||
return state.worktreeName === resolvedWorktreeName
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
@@ -164,7 +173,9 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
console.log(`Ralph Loop: ${state.worktreeName}`)
|
||||
console.log(` Session ID: ${state.sessionId}`)
|
||||
console.log(` Worktree: ${state.worktreeName}`)
|
||||
console.log(` Branch: ${state.worktreeBranch}`)
|
||||
if (state.worktreeBranch) {
|
||||
console.log(` Branch: ${state.worktreeBranch}`)
|
||||
}
|
||||
console.log(` Worktree Dir: ${state.worktreeDir}`)
|
||||
if (state.inPlace) {
|
||||
console.log(` Mode: in-place`)
|
||||
@@ -179,9 +190,22 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
if (state.completionPromise) {
|
||||
console.log(` Completion: ${state.completionPromise}`)
|
||||
}
|
||||
console.log('')
|
||||
} else if (recentLoop) {
|
||||
const state = recentLoop.state
|
||||
if (state.lastAuditResult) {
|
||||
for (const line of formatAuditResult(state.lastAuditResult)) {
|
||||
console.log(line)
|
||||
}
|
||||
}
|
||||
|
||||
const sessionOutput = await tryFetchSessionOutput(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir)
|
||||
if (sessionOutput) {
|
||||
console.log('Session Output:')
|
||||
for (const line of formatSessionOutput(sessionOutput)) {
|
||||
console.log(line)
|
||||
}
|
||||
console.log('')
|
||||
}
|
||||
} else {
|
||||
const state = matchedLoop.loop.state
|
||||
const completedAt = state.completedAt!
|
||||
const duration = new Date(completedAt).getTime() - new Date(state.startedAt).getTime()
|
||||
const hours = Math.floor(duration / (1000 * 60 * 60))
|
||||
@@ -192,7 +216,9 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
console.log(`Ralph Loop (Completed): ${state.worktreeName}`)
|
||||
console.log(` Session ID: ${state.sessionId}`)
|
||||
console.log(` Worktree: ${state.worktreeName}`)
|
||||
console.log(` Branch: ${state.worktreeBranch}`)
|
||||
if (state.worktreeBranch) {
|
||||
console.log(` Branch: ${state.worktreeBranch}`)
|
||||
}
|
||||
console.log(` Worktree Dir: ${state.worktreeDir}`)
|
||||
if (state.inPlace) {
|
||||
console.log(` Mode: in-place (completed)`)
|
||||
@@ -202,7 +228,20 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
console.log(` Reason: ${state.terminationReason ?? 'unknown'}`)
|
||||
console.log(` Started: ${new Date(state.startedAt).toISOString()}`)
|
||||
console.log(` Completed: ${new Date(completedAt).toISOString()}`)
|
||||
console.log('')
|
||||
if (state.lastAuditResult) {
|
||||
for (const line of formatAuditResult(state.lastAuditResult)) {
|
||||
console.log(line)
|
||||
}
|
||||
}
|
||||
|
||||
const sessionOutput = await tryFetchSessionOutput(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir)
|
||||
if (sessionOutput) {
|
||||
console.log('Session Output:')
|
||||
for (const line of formatSessionOutput(sessionOutput)) {
|
||||
console.log(line)
|
||||
}
|
||||
console.log('')
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (activeLoops.length > 0) {
|
||||
@@ -254,3 +293,57 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Show Ralph loop status
|
||||
|
||||
Usage:
|
||||
ocm-mem status [options]
|
||||
ocm-mem status <name> [options]
|
||||
|
||||
Arguments:
|
||||
name Worktree name for detailed status (optional, supports partial matching)
|
||||
|
||||
Options:
|
||||
--server <url> OpenCode server URL (default: http://localhost:5551)
|
||||
--list-worktrees List all worktree names (for shell completion)
|
||||
Optionally provide a filter: --list-worktrees <filter>
|
||||
--project, -p <id> Project ID (auto-detected from git if not provided)
|
||||
--db-path <path> Path to memory database
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export async function cli(args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }): Promise<void> {
|
||||
const argv: StatusArgs = {
|
||||
dbPath: globalOpts.dbPath,
|
||||
resolvedProjectId: globalOpts.resolvedProjectId,
|
||||
server: 'http://localhost:5551',
|
||||
}
|
||||
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
if (arg === '--server') {
|
||||
argv.server = args[++i]
|
||||
} else if (arg === '--list-worktrees') {
|
||||
argv.listWorktrees = true
|
||||
if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
|
||||
argv.listWorktreesFilter = args[++i]
|
||||
}
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
help()
|
||||
process.exit(0)
|
||||
} else if (!arg.startsWith('-')) {
|
||||
argv.name = arg
|
||||
} else {
|
||||
console.error(`Unknown option: ${arg}`)
|
||||
help()
|
||||
process.exit(1)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
await run(argv)
|
||||
}
|
||||
@@ -2,19 +2,7 @@ import { execFileSync } from 'child_process'
|
||||
import { VERSION } from '../../version'
|
||||
import { checkForUpdate, performUpgrade } from '../../utils/upgrade'
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Check for and install plugin updates
|
||||
|
||||
Usage:
|
||||
ocm-mem upgrade
|
||||
|
||||
Options:
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
|
||||
export async function run(_args: string[], _globalOpts: { dbPath?: string; projectId?: string }): Promise<void> {
|
||||
export async function run(): Promise<void> {
|
||||
const updateCheck = await checkForUpdate()
|
||||
|
||||
if (!updateCheck.latest || !updateCheck.updateAvailable) {
|
||||
@@ -43,3 +31,15 @@ export async function run(_args: string[], _globalOpts: { dbPath?: string; proje
|
||||
console.log('Restart OpenCode to use the new version.')
|
||||
}
|
||||
}
|
||||
|
||||
export function help(): void {
|
||||
console.log(`
|
||||
Check for and install plugin updates
|
||||
|
||||
Usage:
|
||||
ocm-mem upgrade
|
||||
|
||||
Options:
|
||||
--help, -h Show this help message
|
||||
`.trim())
|
||||
}
|
||||
@@ -2,15 +2,15 @@
|
||||
import { parseGlobalOptions, getGitProjectId, resolveProjectIdByName } from './utils'
|
||||
|
||||
interface CommandModule {
|
||||
run: (args: string[], globalOpts: { dbPath?: string; projectId?: string }) => Promise<void>
|
||||
cli: (args: string[], globalOpts: { dbPath?: string; resolvedProjectId?: string }) => Promise<void> | void
|
||||
help: () => void | Promise<void>
|
||||
}
|
||||
|
||||
const commands: Record<string, CommandModule> = {
|
||||
export: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/export')
|
||||
run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/export')
|
||||
cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/export')
|
||||
@@ -18,9 +18,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
import: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/import')
|
||||
run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/import')
|
||||
cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/import')
|
||||
@@ -28,9 +28,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
list: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/list')
|
||||
run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/list')
|
||||
cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/list')
|
||||
@@ -38,9 +38,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
stats: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/stats')
|
||||
run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/stats')
|
||||
cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/stats')
|
||||
@@ -48,9 +48,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
cleanup: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/cleanup')
|
||||
run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/cleanup')
|
||||
await cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/cleanup')
|
||||
@@ -58,9 +58,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
upgrade: {
|
||||
run: async (args, globalOpts) => {
|
||||
cli: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/upgrade')
|
||||
await run(args, globalOpts)
|
||||
await run()
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/upgrade')
|
||||
@@ -68,9 +68,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
status: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/status')
|
||||
await run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/status')
|
||||
await cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/status')
|
||||
@@ -78,9 +78,9 @@ const commands: Record<string, CommandModule> = {
|
||||
},
|
||||
},
|
||||
cancel: {
|
||||
run: async (args, globalOpts) => {
|
||||
const { run } = await import('./commands/cancel')
|
||||
await run(args, globalOpts)
|
||||
cli: async (args, globalOpts) => {
|
||||
const { cli } = await import('./commands/cancel')
|
||||
await cli(args, globalOpts)
|
||||
},
|
||||
help: async () => {
|
||||
const { help } = await import('./commands/cancel')
|
||||
@@ -119,7 +119,6 @@ Run '<command> --help' for more information on a command.
|
||||
function resolveProjectId(input: string): string {
|
||||
const isSha = /^[0-9a-f]{40}$/.test(input)
|
||||
if (isSha) return input
|
||||
|
||||
return resolveProjectIdByName(input) || input
|
||||
}
|
||||
|
||||
@@ -166,19 +165,14 @@ async function runCli(): Promise<void> {
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
let finalProjectId = globalOpts.projectId
|
||||
const resolvedProjectId = globalOpts.projectId
|
||||
? resolveProjectId(globalOpts.projectId)
|
||||
: getGitProjectId(globalOpts.dir)
|
||||
: getGitProjectId(globalOpts.dir) ?? undefined
|
||||
|
||||
const effectiveGlobalOpts: { dbPath?: string; projectId?: string } = {
|
||||
...globalOpts,
|
||||
}
|
||||
|
||||
if (finalProjectId) {
|
||||
effectiveGlobalOpts.projectId = finalProjectId
|
||||
}
|
||||
|
||||
await command.run(commandArgs, effectiveGlobalOpts)
|
||||
await command.cli(commandArgs, {
|
||||
dbPath: globalOpts.dbPath,
|
||||
resolvedProjectId,
|
||||
})
|
||||
}
|
||||
|
||||
runCli().catch((error) => {
|
||||
|
||||
@@ -19,13 +19,6 @@ export interface PluginMemory {
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface GlobalOptions {
|
||||
dbPath?: string
|
||||
projectId?: string
|
||||
dir?: string
|
||||
help?: boolean
|
||||
}
|
||||
|
||||
export function resolveDefaultDbPath(): string {
|
||||
const localPath = join(process.cwd(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
|
||||
if (existsSync(localPath)) {
|
||||
@@ -107,36 +100,6 @@ export function confirm(message: string): Promise<boolean> {
|
||||
})
|
||||
}
|
||||
|
||||
export interface ParsedGlobalOptions {
|
||||
globalOpts: GlobalOptions
|
||||
remainingArgs: string[]
|
||||
}
|
||||
|
||||
export function parseGlobalOptions(args: string[]): ParsedGlobalOptions {
|
||||
const globalOpts: GlobalOptions = {}
|
||||
const remainingArgs: string[] = []
|
||||
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--db-path') {
|
||||
globalOpts.dbPath = args[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
globalOpts.projectId = args[++i]
|
||||
} else if (arg === '--dir' || arg === '-d') {
|
||||
globalOpts.dir = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
globalOpts.help = true
|
||||
} else {
|
||||
remainingArgs.push(arg)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { globalOpts, remainingArgs }
|
||||
}
|
||||
|
||||
export function resolveProjectNames(): Map<string, string> {
|
||||
const nameMap = new Map<string, string>()
|
||||
@@ -195,3 +158,41 @@ export function resolveProjectIdByName(name: string): string | null {
|
||||
export function displayProjectId(id: string, nameMap: Map<string, string>): string {
|
||||
return nameMap.get(id) || id
|
||||
}
|
||||
|
||||
export interface GlobalOptions {
|
||||
dbPath?: string
|
||||
projectId?: string
|
||||
dir?: string
|
||||
help?: boolean
|
||||
}
|
||||
|
||||
export interface ParsedGlobalOptions {
|
||||
globalOpts: GlobalOptions
|
||||
remainingArgs: string[]
|
||||
}
|
||||
|
||||
export function parseGlobalOptions(args: string[]): ParsedGlobalOptions {
|
||||
const globalOpts: GlobalOptions = {}
|
||||
const remainingArgs: string[] = []
|
||||
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
const arg = args[i]
|
||||
|
||||
if (arg === '--db-path') {
|
||||
globalOpts.dbPath = args[++i]
|
||||
} else if (arg === '--project' || arg === '-p') {
|
||||
globalOpts.projectId = args[++i]
|
||||
} else if (arg === '--dir' || arg === '-d') {
|
||||
globalOpts.dir = args[++i]
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
globalOpts.help = true
|
||||
} else {
|
||||
remainingArgs.push(arg)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return { globalOpts, remainingArgs }
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
export interface PartialMatchResult<T> {
|
||||
match: T | null
|
||||
candidates: T[]
|
||||
}
|
||||
|
||||
export function findPartialMatch<T>(
|
||||
input: string,
|
||||
items: T[],
|
||||
getFields: (item: T) => (string | undefined)[],
|
||||
): PartialMatchResult<T> {
|
||||
const inputLower = input.toLowerCase()
|
||||
|
||||
let exactMatch: T | null = null
|
||||
const substringMatches: T[] = []
|
||||
|
||||
for (const item of items) {
|
||||
const fields = getFields(item)
|
||||
let hasExact = false
|
||||
let hasSubstring = false
|
||||
|
||||
for (const field of fields) {
|
||||
if (field === undefined) continue
|
||||
const fieldLower = field.toLowerCase()
|
||||
|
||||
if (fieldLower === inputLower) {
|
||||
hasExact = true
|
||||
}
|
||||
if (fieldLower.includes(inputLower)) {
|
||||
hasSubstring = true
|
||||
}
|
||||
}
|
||||
|
||||
if (hasExact) {
|
||||
exactMatch = item
|
||||
break
|
||||
}
|
||||
if (hasSubstring) {
|
||||
substringMatches.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
if (exactMatch) {
|
||||
return { match: exactMatch, candidates: [] }
|
||||
}
|
||||
|
||||
if (substringMatches.length === 1) {
|
||||
return { match: substringMatches[0], candidates: [] }
|
||||
}
|
||||
|
||||
if (substringMatches.length > 1) {
|
||||
return { match: null, candidates: substringMatches }
|
||||
}
|
||||
|
||||
return { match: null, candidates: [] }
|
||||
}
|
||||
|
||||
export function filterByPartial<T>(
|
||||
input: string | undefined,
|
||||
items: T[],
|
||||
getFields: (item: T) => (string | undefined)[],
|
||||
): T[] {
|
||||
if (!input || input.length === 0) {
|
||||
return items
|
||||
}
|
||||
|
||||
const inputLower = input.toLowerCase()
|
||||
|
||||
return items.filter((item) => {
|
||||
const fields = getFields(item)
|
||||
for (const field of fields) {
|
||||
if (field === undefined) continue
|
||||
if (field.toLowerCase().includes(inputLower)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { truncate } from '../cli/utils'
|
||||
import type { RalphSessionOutput } from '../services/ralph'
|
||||
|
||||
export function formatTokens(n: number): string {
|
||||
return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`
|
||||
}
|
||||
|
||||
export function formatSessionOutput(sessionOutput: RalphSessionOutput): string[] {
|
||||
const lines: string[] = []
|
||||
const costStr = `$${sessionOutput.totalCost.toFixed(4)}`
|
||||
const t = sessionOutput.totalTokens
|
||||
const tokensStr = `${formatTokens(t.input)} in / ${formatTokens(t.output)} out / ${formatTokens(t.reasoning)} reasoning / ${formatTokens(t.cacheRead)} cache read / ${formatTokens(t.cacheWrite)} cache write`
|
||||
lines.push(` Cost: ${costStr} | Tokens: ${tokensStr}`)
|
||||
|
||||
if (sessionOutput.fileChanges) {
|
||||
const fc = sessionOutput.fileChanges
|
||||
lines.push(` Files changed: ${fc.files} (+${fc.additions}/-${fc.deletions} lines)`)
|
||||
}
|
||||
|
||||
if (sessionOutput.messages.length > 0) {
|
||||
lines.push('')
|
||||
lines.push('Recent Activity:')
|
||||
for (const msg of sessionOutput.messages) {
|
||||
const preview = truncate(msg.text.replace(/\n/g, ' ').trim(), 200)
|
||||
lines.push(` [assistant] ${preview}`)
|
||||
}
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
export function formatAuditResult(auditResult: string): string[] {
|
||||
const auditPreview = truncate(auditResult, 300)
|
||||
return ['', 'Last Audit:', ` ${auditPreview}`]
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
|
||||
interface RalphState {
|
||||
sessionId: string
|
||||
worktreeName: string
|
||||
worktreeBranch: string
|
||||
worktreeDir: string
|
||||
inPlace: boolean
|
||||
iteration: number
|
||||
maxIterations: number
|
||||
phase: 'coding' | 'auditing'
|
||||
startedAt: string
|
||||
completedAt?: string
|
||||
terminationReason?: string
|
||||
active: boolean
|
||||
audit: boolean
|
||||
errorCount: number
|
||||
auditCount: number
|
||||
completionPromise?: string
|
||||
lastAuditResult?: string
|
||||
}
|
||||
|
||||
function createTestKvDb(tempDir: string): Database {
|
||||
const dbPath = join(tempDir, 'memory.db')
|
||||
const db = new Database(dbPath)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS project_kv (
|
||||
project_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (project_id, key)
|
||||
)
|
||||
`)
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
function insertRalphState(db: Database, projectId: string, worktreeName: string, state: Partial<RalphState>): void {
|
||||
const defaultState: RalphState = {
|
||||
sessionId: 'test-session-id',
|
||||
worktreeName,
|
||||
worktreeBranch: 'main',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
inPlace: false,
|
||||
iteration: 1,
|
||||
maxIterations: 10,
|
||||
phase: 'coding',
|
||||
startedAt: new Date().toISOString(),
|
||||
active: true,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
...state,
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const expiresAt = now + 86400000
|
||||
const data = JSON.stringify(defaultState)
|
||||
|
||||
db.run(
|
||||
'INSERT OR REPLACE INTO project_kv (project_id, key, data, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
||||
[projectId, `ralph:${worktreeName}`, data, expiresAt, now]
|
||||
)
|
||||
}
|
||||
|
||||
describe('CLI Cancel', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
let originalError: typeof console.error
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cancel-test-'))
|
||||
originalLog = console.log
|
||||
originalError = console.error
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
console.error = originalError
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('shows no active loops when KV is empty', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('No active Ralph loops')
|
||||
})
|
||||
|
||||
test('shows no active loops when all are inactive', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'inactive-worktree', {
|
||||
active: false,
|
||||
completedAt: new Date().toISOString(),
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('No active Ralph loops')
|
||||
})
|
||||
|
||||
test('auto-selects single active loop with force', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'single-loop', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const row = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:single-loop') as { data: string }
|
||||
const state = JSON.parse(row.data) as RalphState
|
||||
db2.close()
|
||||
|
||||
expect(state.active).toBe(false)
|
||||
expect(state.terminationReason).toBe('cancelled')
|
||||
expect(state.completedAt).toBeDefined()
|
||||
})
|
||||
|
||||
test('cancellation sets correct state fields', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'test-loop', {})
|
||||
db.close()
|
||||
|
||||
const beforeCancel = new Date()
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const row = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:test-loop') as { data: string }
|
||||
const state = JSON.parse(row.data) as RalphState
|
||||
db2.close()
|
||||
|
||||
expect(state.active).toBe(false)
|
||||
expect(state.terminationReason).toBe('cancelled')
|
||||
expect(state.completedAt).toBeDefined()
|
||||
expect(new Date(state.completedAt!).getTime()).toBeGreaterThanOrEqual(beforeCancel.getTime())
|
||||
})
|
||||
|
||||
test('lists active loops when multiple exist and no name given', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'loop-one', {})
|
||||
insertRalphState(db, 'test-project', 'loop-two', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
console.error = (msg: string) => outputLines.push(msg)
|
||||
|
||||
let exited = false
|
||||
const originalExit = process.exit
|
||||
process.exit = (() => { exited = true; throw new Error('process.exit called') }) as any
|
||||
|
||||
try {
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
})
|
||||
} catch (e) {
|
||||
if (!(e instanceof Error) || !e.message.includes('process.exit')) {
|
||||
throw e
|
||||
}
|
||||
} finally {
|
||||
process.exit = originalExit
|
||||
}
|
||||
|
||||
expect(exited).toBe(true)
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Multiple active Ralph loops')
|
||||
expect(output).toContain('loop-one')
|
||||
expect(output).toContain('loop-two')
|
||||
})
|
||||
|
||||
test('finds loop by name when multiple active', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'loop-alpha', {})
|
||||
insertRalphState(db, 'test-project', 'loop-beta', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
name: 'loop-beta',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const alphaRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:loop-alpha') as { data: string }
|
||||
const betaRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:loop-beta') as { data: string }
|
||||
const alphaState = JSON.parse(alphaRow.data) as RalphState
|
||||
const betaState = JSON.parse(betaRow.data) as RalphState
|
||||
db2.close()
|
||||
|
||||
expect(alphaState.active).toBe(true)
|
||||
expect(betaState.active).toBe(false)
|
||||
expect(betaState.terminationReason).toBe('cancelled')
|
||||
})
|
||||
|
||||
test('partial name matches single loop proceeds with cancel', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
|
||||
insertRalphState(db, 'test-project', 'ralph-fix-bug', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
name: 'auth',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const authRow = db2.prepare('SELECT data FROM project_kv WHERE key = ?').get('ralph:ralph-feat-auth') as { data: string }
|
||||
const authState = JSON.parse(authRow.data) as RalphState
|
||||
db2.close()
|
||||
|
||||
expect(authState.active).toBe(false)
|
||||
expect(authState.terminationReason).toBe('cancelled')
|
||||
})
|
||||
|
||||
test('partial name matches multiple loops lists ambiguous and exits', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
|
||||
insertRalphState(db, 'test-project', 'ralph-auth-fix', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.error = (msg: string) => outputLines.push(msg)
|
||||
|
||||
let exited = false
|
||||
const originalExit = process.exit
|
||||
process.exit = (() => { exited = true; throw new Error('process.exit called') }) as any
|
||||
|
||||
try {
|
||||
const { run } = await import('../src/cli/commands/cancel')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
name: 'auth',
|
||||
})
|
||||
} catch (e) {
|
||||
if (!(e instanceof Error) || !e.message.includes('process.exit')) {
|
||||
throw e
|
||||
}
|
||||
} finally {
|
||||
process.exit = originalExit
|
||||
}
|
||||
|
||||
expect(exited).toBe(true)
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain("Multiple loops match 'auth':")
|
||||
expect(output).toContain('ralph-feat-auth')
|
||||
expect(output).toContain('ralph-auth-fix')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,273 @@
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
|
||||
function createTestMemoryDb(tempDir: string): Database {
|
||||
const dbPath = join(tempDir, 'memory.db')
|
||||
const db = new Database(dbPath)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
file_path TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_accessed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope)`)
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
function insertTestMemory(db: Database, projectId: string, scope: string, content: string, createdAt?: number): number {
|
||||
const now = createdAt || Date.now()
|
||||
const result = db.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[projectId, scope, content, null, 0, now, now]
|
||||
)
|
||||
return result.lastInsertRowid as number
|
||||
}
|
||||
|
||||
describe('CLI Cleanup', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
let originalError: typeof console.error
|
||||
let originalExit: typeof process.exit
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-cleanup-test-'))
|
||||
originalLog = console.log
|
||||
originalError = console.error
|
||||
originalExit = process.exit
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
console.error = originalError
|
||||
process.exit = originalExit
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('requires at least one filter', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.error = (msg: string) => outputLines.push(msg)
|
||||
|
||||
let exited = false
|
||||
process.exit = (() => { exited = true }) as any
|
||||
|
||||
try {
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
})
|
||||
} finally {
|
||||
process.exit = originalExit
|
||||
}
|
||||
|
||||
expect(exited).toBe(true)
|
||||
expect(outputLines.join('\n')).toContain('At least one filter')
|
||||
})
|
||||
|
||||
test('--all requires --project', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.error = (msg: string) => outputLines.push(msg)
|
||||
|
||||
let exited = false
|
||||
process.exit = (() => { exited = true }) as any
|
||||
|
||||
try {
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
all: true,
|
||||
})
|
||||
} finally {
|
||||
process.exit = originalExit
|
||||
}
|
||||
|
||||
expect(exited).toBe(true)
|
||||
expect(outputLines.join('\n')).toContain('--all requires --project')
|
||||
})
|
||||
|
||||
test('--ids parses comma-separated IDs', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 1')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 2')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 3')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
ids: '1,3',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const remaining = db2.prepare('SELECT COUNT(*) as count FROM memories').get() as { count: number }
|
||||
db2.close()
|
||||
|
||||
expect(remaining.count).toBe(1)
|
||||
})
|
||||
|
||||
test('--older-than filters by age', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
const oldTime = Date.now() - (3 * 24 * 60 * 60 * 1000)
|
||||
const newTime = Date.now()
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Old memory', oldTime)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'New memory', newTime)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
olderThan: 2,
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const remaining = db2.prepare('SELECT COUNT(*) as count FROM memories').get() as { count: number }
|
||||
db2.close()
|
||||
|
||||
expect(remaining.count).toBe(1)
|
||||
})
|
||||
|
||||
test('--scope filters by scope', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
const id1 = insertTestMemory(db, 'test-project', 'convention', 'Convention 1')
|
||||
const id2 = insertTestMemory(db, 'test-project', 'convention', 'Convention 2')
|
||||
insertTestMemory(db, 'test-project', 'decision', 'Decision 1')
|
||||
insertTestMemory(db, 'test-project', 'context', 'Context 1')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
ids: `${id1},${id2}`,
|
||||
scope: 'convention',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const remaining = db2.prepare('SELECT COUNT(*) as count FROM memories WHERE scope = ?').get('convention') as { count: number }
|
||||
const total = db2.prepare('SELECT COUNT(*) as count FROM memories').get() as { count: number }
|
||||
db2.close()
|
||||
|
||||
expect(remaining.count).toBe(0)
|
||||
expect(total.count).toBe(2)
|
||||
})
|
||||
|
||||
test('--dry-run does not delete', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 1')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 2')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
all: true,
|
||||
dryRun: true,
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const remaining = db2.prepare('SELECT COUNT(*) as count FROM memories').get() as { count: number }
|
||||
db2.close()
|
||||
|
||||
expect(remaining.count).toBe(2)
|
||||
expect(outputLines.join('\n')).toContain('Dry run')
|
||||
})
|
||||
|
||||
test('--force --all deletes all project memories', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 1')
|
||||
insertTestMemory(db, 'test-project', 'decision', 'Memory 2')
|
||||
insertTestMemory(db, 'test-project', 'context', 'Memory 3')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
all: true,
|
||||
force: true,
|
||||
})
|
||||
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const remaining = db2.prepare('SELECT COUNT(*) as count FROM memories WHERE project_id = ?').get('test-project') as { count: number }
|
||||
db2.close()
|
||||
|
||||
expect(remaining.count).toBe(0)
|
||||
})
|
||||
|
||||
test('reports remaining count after deletion', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 1')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 2')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 3')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 4')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Memory 5')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/cleanup')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
ids: '1,2',
|
||||
force: true,
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('remaining')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cleanupVecWorkers', () => {
|
||||
test('returns cleanup result message', async () => {
|
||||
const { cleanupVecWorkers } = await import('../src/cli/commands/cleanup')
|
||||
const result = await cleanupVecWorkers()
|
||||
expect(result).toContain('Vec-worker cleanup complete')
|
||||
expect(result).toContain('Terminated')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,205 @@
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
|
||||
function createTestMemoryDb(tempDir: string): Database {
|
||||
const dbPath = join(tempDir, 'memory.db')
|
||||
const db = new Database(dbPath)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
file_path TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_accessed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
|
||||
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope)`)
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
function insertTestMemory(db: Database, projectId: string, scope: string, content: string, createdAt?: number): void {
|
||||
const now = createdAt || Date.now()
|
||||
db.run(
|
||||
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[projectId, scope, content, null, 0, now, now]
|
||||
)
|
||||
}
|
||||
|
||||
describe('CLI List', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-list-test-'))
|
||||
originalLog = console.log
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('lists projects with memory counts', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
insertTestMemory(db, 'project-one', 'convention', 'First convention')
|
||||
insertTestMemory(db, 'project-one', 'decision', 'First decision')
|
||||
insertTestMemory(db, 'project-two', 'context', 'Context for project two')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/list')
|
||||
run({ dbPath: join(tempDir, 'memory.db') })
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Projects with memories:')
|
||||
expect(output).toContain('project-one')
|
||||
expect(output).toContain('project-two')
|
||||
})
|
||||
|
||||
test('shows no memories message when empty', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/list')
|
||||
run({ dbPath: join(tempDir, 'memory.db') })
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('No memories found')
|
||||
})
|
||||
|
||||
test('shows correct oldest and newest dates', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
const oldTime = Date.now() - 86400000
|
||||
const newTime = Date.now()
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Old memory', oldTime)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'New memory', newTime)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/list')
|
||||
run({ dbPath: join(tempDir, 'memory.db') })
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
const oldDate = new Date(oldTime).toISOString().split('T')[0]
|
||||
const newDate = new Date(newTime).toISOString().split('T')[0]
|
||||
expect(output).toContain(oldDate)
|
||||
expect(output).toContain(newDate)
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Stats', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
let originalError: typeof console.error
|
||||
let originalExit: typeof process.exit
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-stats-test-'))
|
||||
originalLog = console.log
|
||||
originalError = console.error
|
||||
originalExit = process.exit
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
console.error = originalError
|
||||
process.exit = originalExit
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('shows per-scope counts', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Convention 1')
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Convention 2')
|
||||
insertTestMemory(db, 'test-project', 'decision', 'Decision 1')
|
||||
insertTestMemory(db, 'test-project', 'context', 'Context 1')
|
||||
insertTestMemory(db, 'test-project', 'context', 'Context 2')
|
||||
insertTestMemory(db, 'test-project', 'context', 'Context 3')
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/stats')
|
||||
run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('convention: 2')
|
||||
expect(output).toContain('decision: 1')
|
||||
expect(output).toContain('context: 3')
|
||||
})
|
||||
|
||||
test('shows oldest and newest dates', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
const oldTime = Date.now() - 86400000
|
||||
const newTime = Date.now()
|
||||
insertTestMemory(db, 'test-project', 'convention', 'Old memory', oldTime)
|
||||
insertTestMemory(db, 'test-project', 'convention', 'New memory', newTime)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/stats')
|
||||
run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
const oldDate = new Date(oldTime).toISOString().split('T')[0]
|
||||
const newDate = new Date(newTime).toISOString().split('T')[0]
|
||||
expect(output).toContain('Oldest:')
|
||||
expect(output).toContain('Newest:')
|
||||
expect(output).toContain(oldDate)
|
||||
expect(output).toContain(newDate)
|
||||
})
|
||||
|
||||
test('exits with error when no project ID', async () => {
|
||||
const db = createTestMemoryDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.error = (msg: string) => outputLines.push(msg)
|
||||
|
||||
let exited = false
|
||||
process.exit = (() => { exited = true }) as any
|
||||
|
||||
try {
|
||||
const { run } = await import('../src/cli/commands/stats')
|
||||
run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
})
|
||||
} finally {
|
||||
process.exit = originalExit
|
||||
}
|
||||
|
||||
expect(exited).toBe(true)
|
||||
expect(outputLines.join('\n')).toContain('Project ID required')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,486 @@
|
||||
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
|
||||
interface RalphState {
|
||||
sessionId: string
|
||||
worktreeName: string
|
||||
worktreeBranch: string
|
||||
worktreeDir: string
|
||||
inPlace: boolean
|
||||
iteration: number
|
||||
maxIterations: number
|
||||
phase: 'coding' | 'auditing'
|
||||
startedAt: string
|
||||
completedAt?: string
|
||||
terminationReason?: string
|
||||
active: boolean
|
||||
audit: boolean
|
||||
errorCount: number
|
||||
auditCount: number
|
||||
completionPromise?: string
|
||||
lastAuditResult?: string
|
||||
}
|
||||
|
||||
function createTestKvDb(tempDir: string): Database {
|
||||
const dbPath = join(tempDir, 'memory.db')
|
||||
const db = new Database(dbPath)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS project_kv (
|
||||
project_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (project_id, key)
|
||||
)
|
||||
`)
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
function insertRalphState(db: Database, projectId: string, worktreeName: string, state: Partial<RalphState>): void {
|
||||
const defaultState: RalphState = {
|
||||
sessionId: 'test-session-id',
|
||||
worktreeName,
|
||||
worktreeBranch: 'main',
|
||||
worktreeDir: '/tmp/test-worktree',
|
||||
inPlace: false,
|
||||
iteration: 1,
|
||||
maxIterations: 10,
|
||||
phase: 'coding',
|
||||
startedAt: new Date().toISOString(),
|
||||
active: true,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
...state,
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const expiresAt = state.completedAt ? now + 86400000 : now + 86400000
|
||||
const data = JSON.stringify(defaultState)
|
||||
|
||||
db.run(
|
||||
'INSERT OR REPLACE INTO project_kv (project_id, key, data, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
||||
[projectId, `ralph:${worktreeName}`, data, expiresAt, now]
|
||||
)
|
||||
}
|
||||
|
||||
describe('CLI Status - list-worktrees', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-status-test-'))
|
||||
originalLog = console.log
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('lists active worktree names', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'worktree-one', {})
|
||||
insertRalphState(db, 'test-project', 'worktree-two', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
listWorktrees: true,
|
||||
})
|
||||
|
||||
expect(outputLines).toContain('worktree-one')
|
||||
expect(outputLines).toContain('worktree-two')
|
||||
})
|
||||
|
||||
test('skips expired entries', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
const db2 = new Database(join(tempDir, 'memory.db'))
|
||||
const now = Date.now()
|
||||
const expiredAt = now - 86400000
|
||||
|
||||
const expiredState: RalphState = {
|
||||
sessionId: 'test-session',
|
||||
worktreeName: 'expired-worktree',
|
||||
worktreeBranch: 'main',
|
||||
worktreeDir: '/tmp/test',
|
||||
inPlace: false,
|
||||
iteration: 1,
|
||||
maxIterations: 10,
|
||||
phase: 'coding',
|
||||
startedAt: new Date().toISOString(),
|
||||
active: true,
|
||||
audit: false,
|
||||
errorCount: 0,
|
||||
auditCount: 0,
|
||||
}
|
||||
|
||||
db2.run(
|
||||
'INSERT INTO project_kv (project_id, key, data, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
||||
['test-project', 'ralph:expired-worktree', JSON.stringify(expiredState), expiredAt, now]
|
||||
)
|
||||
db2.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
listWorktrees: true,
|
||||
})
|
||||
|
||||
expect(outputLines).not.toContain('expired-worktree')
|
||||
})
|
||||
|
||||
test('includes inactive loops in list', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'inactive-worktree', { active: false, completedAt: new Date().toISOString() })
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
listWorktrees: true,
|
||||
})
|
||||
|
||||
expect(outputLines).toContain('inactive-worktree')
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Status - summary', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
let originalError: typeof console.error
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-status-summary-'))
|
||||
originalLog = console.log
|
||||
originalError = console.error
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
console.error = originalError
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('shows active loops when no name given', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'active-one', { startedAt: new Date(Date.now() - 3600000).toISOString() })
|
||||
insertRalphState(db, 'test-project', 'active-two', { startedAt: new Date(Date.now() - 1800000).toISOString() })
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Active Ralph Loops:')
|
||||
expect(output).toContain('active-one')
|
||||
expect(output).toContain('active-two')
|
||||
})
|
||||
|
||||
test('shows no loops message when empty', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('No Ralph loops found')
|
||||
})
|
||||
|
||||
test('shows recently completed loops', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'completed-one', {
|
||||
active: false,
|
||||
completedAt: new Date().toISOString(),
|
||||
terminationReason: 'success',
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Recently Completed:')
|
||||
expect(output).toContain('completed-one')
|
||||
})
|
||||
})
|
||||
|
||||
describe('CLI Status - partial matching', () => {
|
||||
let tempDir: string
|
||||
let originalLog: typeof console.log
|
||||
let originalError: typeof console.error
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join('.', 'temp-status-partial-'))
|
||||
originalLog = console.log
|
||||
originalError = console.error
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
console.log = originalLog
|
||||
console.error = originalError
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('partial name matches single active loop', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {
|
||||
startedAt: new Date(Date.now() - 3600000).toISOString(),
|
||||
})
|
||||
insertRalphState(db, 'test-project', 'ralph-fix-bug', {
|
||||
startedAt: new Date(Date.now() - 1800000).toISOString(),
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
name: 'auth',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Ralph Loop: ralph-feat-auth')
|
||||
})
|
||||
|
||||
test('partial name matches single recent loop', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-completed-auth', {
|
||||
active: false,
|
||||
completedAt: new Date().toISOString(),
|
||||
terminationReason: 'success',
|
||||
})
|
||||
insertRalphState(db, 'test-project', 'ralph-fix-bug', {
|
||||
active: true,
|
||||
startedAt: new Date(Date.now() - 1800000).toISOString(),
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
name: 'completed',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Ralph Loop (Completed): ralph-completed-auth')
|
||||
})
|
||||
|
||||
test('partial name matches multiple loops lists ambiguous', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
|
||||
insertRalphState(db, 'test-project', 'ralph-auth-fix', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.error = (msg: string) => outputLines.push(msg)
|
||||
|
||||
let exited = false
|
||||
const originalExit = process.exit
|
||||
process.exit = (() => { exited = true; throw new Error('process.exit called') }) as any
|
||||
|
||||
try {
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
name: 'auth',
|
||||
})
|
||||
} catch (e) {
|
||||
if (!(e instanceof Error) || !e.message.includes('process.exit')) {
|
||||
throw e
|
||||
}
|
||||
} finally {
|
||||
process.exit = originalExit
|
||||
}
|
||||
|
||||
expect(exited).toBe(true)
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain("Multiple loops match 'auth':")
|
||||
expect(output).toContain('ralph-feat-auth')
|
||||
expect(output).toContain('ralph-auth-fix')
|
||||
})
|
||||
|
||||
test('partial name matches via worktreeBranch field', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {
|
||||
worktreeBranch: 'feat/auth',
|
||||
startedAt: new Date(Date.now() - 3600000).toISOString(),
|
||||
})
|
||||
insertRalphState(db, 'test-project', 'ralph-fix-bug', {
|
||||
worktreeBranch: 'fix/bug',
|
||||
startedAt: new Date(Date.now() - 1800000).toISOString(),
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
name: 'feat/auth',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Ralph Loop: ralph-feat-auth')
|
||||
expect(output).toContain('Branch: feat/auth')
|
||||
})
|
||||
|
||||
test('case-insensitive matching works', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {
|
||||
startedAt: new Date(Date.now() - 3600000).toISOString(),
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
name: 'AUTH',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Ralph Loop: ralph-feat-auth')
|
||||
})
|
||||
|
||||
test('exact match takes priority over partial', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'auth', {
|
||||
startedAt: new Date(Date.now() - 3600000).toISOString(),
|
||||
})
|
||||
insertRalphState(db, 'test-project', 'ralph-auth', {
|
||||
startedAt: new Date(Date.now() - 1800000).toISOString(),
|
||||
})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
name: 'auth',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('Ralph Loop: auth')
|
||||
expect(output).not.toContain('Ralph Loop: ralph-auth')
|
||||
})
|
||||
|
||||
test('--list-worktrees with filter returns filtered results', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', { worktreeBranch: 'feat/auth' })
|
||||
insertRalphState(db, 'test-project', 'ralph-fix-bug', { worktreeBranch: 'fix/bug' })
|
||||
insertRalphState(db, 'test-project', 'ralph-update-deps', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
listWorktrees: true,
|
||||
listWorktreesFilter: 'auth',
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('ralph-feat-auth')
|
||||
expect(output).not.toContain('ralph-fix-bug')
|
||||
expect(output).not.toContain('ralph-update-deps')
|
||||
})
|
||||
|
||||
test('--list-worktrees without filter returns all', async () => {
|
||||
const db = createTestKvDb(tempDir)
|
||||
insertRalphState(db, 'test-project', 'ralph-feat-auth', {})
|
||||
insertRalphState(db, 'test-project', 'ralph-fix-bug', {})
|
||||
db.close()
|
||||
|
||||
const outputLines: string[] = []
|
||||
console.log = (msg: string) => outputLines.push(msg)
|
||||
|
||||
const { run } = await import('../src/cli/commands/status')
|
||||
await run({
|
||||
dbPath: join(tempDir, 'memory.db'),
|
||||
resolvedProjectId: 'test-project',
|
||||
server: 'http://localhost:5551',
|
||||
listWorktrees: true,
|
||||
})
|
||||
|
||||
const output = outputLines.join('\n')
|
||||
expect(output).toContain('ralph-feat-auth')
|
||||
expect(output).toContain('ralph-fix-bug')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, test, expect } from 'bun:test'
|
||||
import { findPartialMatch, filterByPartial } from '../src/utils/partial-match'
|
||||
|
||||
interface TestItem {
|
||||
worktreeName: string
|
||||
worktreeBranch?: string
|
||||
value: string
|
||||
}
|
||||
|
||||
describe('findPartialMatch', () => {
|
||||
test('exact match returns single result', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
{ worktreeName: 'ralph-update-deps', value: 'c' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('ralph-feat-auth', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result.match).toBe(items[0])
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
|
||||
test('substring match returns single result', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
{ worktreeName: 'ralph-update-deps', value: 'c' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('auth', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result.match).toBe(items[0])
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
|
||||
test('case-insensitive substring match', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('AUTH', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result.match).toBe(items[0])
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
|
||||
test('multiple substring matches returns candidates', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-auth-fix', value: 'b' },
|
||||
{ worktreeName: 'ralph-update-deps', value: 'c' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('auth', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result.match).toBeNull()
|
||||
expect(result.candidates).toEqual([items[0], items[1]])
|
||||
})
|
||||
|
||||
test('no matches returns null and empty candidates', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('nonexistent', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result.match).toBeNull()
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
|
||||
test('exact match takes priority over multiple substring matches', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-auth', value: 'b' },
|
||||
{ worktreeName: 'auth-fix', value: 'c' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('auth', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result.match).toBe(items[0])
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
|
||||
test('matches against worktreeBranch field', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', worktreeBranch: 'feat/auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', worktreeBranch: 'fix/bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('feat/auth', items, (i) => [i.worktreeName, i.worktreeBranch])
|
||||
|
||||
expect(result.match).toBe(items[0])
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
|
||||
test('matches against worktreeBranch with partial input', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', worktreeBranch: 'feat/auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', worktreeBranch: 'fix/bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = findPartialMatch('feat', items, (i) => [i.worktreeName, i.worktreeBranch])
|
||||
|
||||
expect(result.match).toBe(items[0])
|
||||
expect(result.candidates).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('filterByPartial', () => {
|
||||
test('with filter returns filtered items', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
{ worktreeName: 'ralph-update-deps', value: 'c' },
|
||||
]
|
||||
|
||||
const result = filterByPartial('auth', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result).toEqual([items[0]])
|
||||
})
|
||||
|
||||
test('without filter returns all items', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = filterByPartial(undefined, items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result).toEqual(items)
|
||||
})
|
||||
|
||||
test('empty filter returns all items', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = filterByPartial('', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result).toEqual(items)
|
||||
})
|
||||
|
||||
test('case-insensitive filtering', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = filterByPartial('AUTH', items, (i) => [i.worktreeName])
|
||||
|
||||
expect(result).toEqual([items[0]])
|
||||
})
|
||||
|
||||
test('filters by worktreeBranch field', () => {
|
||||
const items: TestItem[] = [
|
||||
{ worktreeName: 'ralph-feat-auth', worktreeBranch: 'feat/auth', value: 'a' },
|
||||
{ worktreeName: 'ralph-fix-bug', worktreeBranch: 'fix/bug', value: 'b' },
|
||||
]
|
||||
|
||||
const result = filterByPartial('feat', items, (i) => [i.worktreeName, i.worktreeBranch])
|
||||
|
||||
expect(result).toEqual([items[0]])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,220 @@
|
||||
import { describe, test, expect } from 'bun:test'
|
||||
import { formatTokens, formatSessionOutput, formatAuditResult } from '../src/utils/ralph-format'
|
||||
import type { RalphSessionOutput } from '../src/services/ralph'
|
||||
|
||||
describe('formatTokens', () => {
|
||||
test('numbers less than 1000 returned as string', () => {
|
||||
expect(formatTokens(500)).toBe('500')
|
||||
expect(formatTokens(999)).toBe('999')
|
||||
expect(formatTokens(0)).toBe('0')
|
||||
expect(formatTokens(1)).toBe('1')
|
||||
})
|
||||
|
||||
test('numbers greater than or equal to 1000 formatted with k suffix', () => {
|
||||
expect(formatTokens(1000)).toBe('1.0k')
|
||||
expect(formatTokens(1500)).toBe('1.5k')
|
||||
expect(formatTokens(2000)).toBe('2.0k')
|
||||
expect(formatTokens(2500)).toBe('2.5k')
|
||||
expect(formatTokens(10000)).toBe('10.0k')
|
||||
})
|
||||
|
||||
test('handles edge cases', () => {
|
||||
expect(formatTokens(0)).toBe('0')
|
||||
expect(formatTokens(100)).toBe('100')
|
||||
expect(formatTokens(1001)).toBe('1.0k')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSessionOutput', () => {
|
||||
test('includes cost string with dollar prefix', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.0123,
|
||||
totalTokens: {
|
||||
input: 1000,
|
||||
output: 500,
|
||||
reasoning: 200,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
expect(lines[0]).toContain('$0.0123')
|
||||
})
|
||||
|
||||
test('includes token breakdown', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 1500,
|
||||
output: 750,
|
||||
reasoning: 300,
|
||||
cacheRead: 100,
|
||||
cacheWrite: 50,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
expect(lines[0]).toContain('1.5k in')
|
||||
expect(lines[0]).toContain('750 out')
|
||||
expect(lines[0]).toContain('300 reasoning')
|
||||
expect(lines[0]).toContain('100 cache read')
|
||||
expect(lines[0]).toContain('50 cache write')
|
||||
})
|
||||
|
||||
test('includes file changes when present', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 100,
|
||||
output: 100,
|
||||
reasoning: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: {
|
||||
files: 5,
|
||||
additions: 100,
|
||||
deletions: 50,
|
||||
},
|
||||
messages: [],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
expect(lines).toContain(' Files changed: 5 (+100/-50 lines)')
|
||||
})
|
||||
|
||||
test('omits file changes line when not present', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 100,
|
||||
output: 100,
|
||||
reasoning: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
const hasFileChanges = lines.some((line) => line.includes('Files changed'))
|
||||
expect(hasFileChanges).toBe(false)
|
||||
})
|
||||
|
||||
test('includes recent activity messages', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 100,
|
||||
output: 100,
|
||||
reasoning: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [
|
||||
{ text: 'First message', cost: 0.001, tokens: { input: 10, output: 10, reasoning: 0, cacheRead: 0, cacheWrite: 0 } },
|
||||
{ text: 'Second message', cost: 0.001, tokens: { input: 10, output: 10, reasoning: 0, cacheRead: 0, cacheWrite: 0 } },
|
||||
],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
expect(lines).toContain('Recent Activity:')
|
||||
expect(lines.join('\n')).toContain('[assistant] First message')
|
||||
expect(lines.join('\n')).toContain('[assistant] Second message')
|
||||
})
|
||||
|
||||
test('handles empty messages array', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 100,
|
||||
output: 100,
|
||||
reasoning: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
const hasRecentActivity = lines.some((line) => line.includes('Recent Activity'))
|
||||
expect(hasRecentActivity).toBe(false)
|
||||
})
|
||||
|
||||
test('truncates long message text', () => {
|
||||
const longMessage = 'a'.repeat(250)
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 100,
|
||||
output: 100,
|
||||
reasoning: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [{ text: longMessage, cost: 0.001, tokens: { input: 10, output: 10, reasoning: 0, cacheRead: 0, cacheWrite: 0 } }],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
const messageLine = lines.find((line) => line.includes('[assistant]'))
|
||||
expect(messageLine).toBeDefined()
|
||||
expect(messageLine!.length).toBeLessThanOrEqual(220)
|
||||
})
|
||||
|
||||
test('handles multiline messages', () => {
|
||||
const sessionOutput: RalphSessionOutput = {
|
||||
totalCost: 0.01,
|
||||
totalTokens: {
|
||||
input: 100,
|
||||
output: 100,
|
||||
reasoning: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
fileChanges: null,
|
||||
messages: [{ text: 'Line 1\nLine 2\nLine 3', cost: 0.001, tokens: { input: 10, output: 10, reasoning: 0, cacheRead: 0, cacheWrite: 0 } }],
|
||||
}
|
||||
|
||||
const lines = formatSessionOutput(sessionOutput)
|
||||
const messageLine = lines.find((line) => line.includes('[assistant]'))
|
||||
expect(messageLine).toContain('Line 1 Line 2 Line 3')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatAuditResult', () => {
|
||||
test('returns array with empty line, Last Audit, and truncated result', () => {
|
||||
const auditResult = 'Audit passed with no issues'
|
||||
const lines = formatAuditResult(auditResult)
|
||||
|
||||
expect(lines).toHaveLength(3)
|
||||
expect(lines[0]).toBe('')
|
||||
expect(lines[1]).toBe('Last Audit:')
|
||||
expect(lines[2]).toContain('Audit passed with no issues')
|
||||
})
|
||||
|
||||
test('truncates long audit results to 300 chars', () => {
|
||||
const longResult = 'a'.repeat(400)
|
||||
const lines = formatAuditResult(longResult)
|
||||
|
||||
expect(lines).toHaveLength(3)
|
||||
expect(lines[2].length).toBeLessThanOrEqual(303)
|
||||
expect(lines[2]).toContain('...')
|
||||
})
|
||||
|
||||
test('handles short audit results', () => {
|
||||
const auditResult = 'Short audit result'
|
||||
const lines = formatAuditResult(auditResult)
|
||||
|
||||
expect(lines).toHaveLength(3)
|
||||
expect(lines[2]).toBe(' Short audit result')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user