feat(cli-stream): add search functionality and improve validation in CLI Stream Viewer

This commit is contained in:
catlog22
2025-12-28 22:52:32 +08:00
parent 32cea006b9
commit e2f4241b2e
6 changed files with 411 additions and 11 deletions

View File

@@ -329,10 +329,83 @@ const result = Task(
const summary = JSON.parse(result);
```
### Phase 5: Summary & Status Update
### Phase 5: Validation & Status Update
```javascript
// Agent already generated queue files, use summary
// ============ VALIDATION: Prevent "next returns empty" issues ============
const queuesDir = '.workflow/issues/queues';
const indexPath = `${queuesDir}/index.json`;
const queuePath = `${queuesDir}/${queueId}.json`;
// 1. Validate index.json has active_queue_id
const indexContent = Bash(`cat "${indexPath}" 2>/dev/null || echo '{}'`);
const index = JSON.parse(indexContent);
if (index.active_queue_id !== queueId) {
console.log(`⚠ Fixing: index.json active_queue_id not set to ${queueId}`);
index.active_queue_id = queueId;
// Ensure queue entry exists in index
if (!index.queues) index.queues = [];
const existing = index.queues.find(q => q.id === queueId);
if (!existing) {
index.queues.unshift({
id: queueId,
status: 'active',
issue_ids: summary.issues_queued,
total_solutions: summary.total_solutions,
completed_solutions: 0,
created_at: new Date().toISOString()
});
}
Bash(`echo '${JSON.stringify(index, null, 2)}' > "${indexPath}"`);
console.log(`✓ Fixed: index.json updated with active_queue_id: ${queueId}`);
}
// 2. Validate queue file exists and has correct structure
const queueContent = Bash(`cat "${queuePath}" 2>/dev/null || echo '{}'`);
const queue = JSON.parse(queueContent);
if (!queue.solutions || queue.solutions.length === 0) {
console.error(`✗ ERROR: Queue file ${queuePath} has no solutions array`);
console.error(' Agent did not generate queue correctly. Aborting.');
return;
}
// 3. Validate all solutions have status: "pending" (not "queued" or other)
let statusFixed = 0;
for (const sol of queue.solutions) {
if (sol.status !== 'pending' && sol.status !== 'executing' && sol.status !== 'completed') {
console.log(`⚠ Fixing: ${sol.item_id} status "${sol.status}" → "pending"`);
sol.status = 'pending';
statusFixed++;
}
}
// 4. Validate at least one item has no dependencies (DAG entry point)
const entryPoints = queue.solutions.filter(s =>
s.status === 'pending' && (!s.depends_on || s.depends_on.length === 0)
);
if (entryPoints.length === 0) {
console.error(`✗ ERROR: No entry points found (all items have dependencies)`);
console.error(' This will cause "ccw issue next" to return empty.');
console.error(' Check depends_on fields for circular dependencies.');
// Try to fix by clearing first item's dependencies
if (queue.solutions.length > 0) {
console.log(`⚠ Fixing: Clearing depends_on for first item ${queue.solutions[0].item_id}`);
queue.solutions[0].depends_on = [];
}
}
// Write back fixed queue if any changes made
if (statusFixed > 0 || entryPoints.length === 0) {
Bash(`echo '${JSON.stringify(queue, null, 2)}' > "${queuePath}"`);
console.log(`✓ Queue file updated with ${statusFixed} status fixes`);
}
// ============ OUTPUT SUMMARY ============
console.log(`
## Queue Formed: ${summary.queue_id}
@@ -341,15 +414,20 @@ console.log(`
**Issues**: ${summary.issues_queued.join(', ')}
**Groups**: ${summary.execution_groups.map(g => `${g.id}(${g.count})`).join(', ')}
**Conflicts Resolved**: ${summary.conflicts_resolved}
**Entry Points**: ${entryPoints.length} (items ready for immediate execution)
Next: \`/issue:execute\`
Next: \`/issue:execute\` or \`ccw issue next\`
`);
// Update issue statuses via CLI (use `update` for pure field changes)
// Note: `queue add` has its own logic; here we only need status update
// Update issue statuses via CLI
for (const issueId of summary.issues_queued) {
Bash(`ccw issue update ${issueId} --status queued`);
}
// Final verification
const verifyResult = Bash(`ccw issue queue dag 2>/dev/null | head -20`);
console.log('\n### Verification (DAG Preview):');
console.log(verifyResult);
```
## Error Handling
@@ -360,6 +438,10 @@ for (const issueId of summary.issues_queued) {
| Circular dependency | List cycles, abort queue formation |
| Unresolved conflicts | Agent resolves using ordering rules |
| Invalid task reference | Skip and warn |
| **index.json not updated** | Auto-fix: Set active_queue_id to new queue |
| **Wrong status value** | Auto-fix: Convert non-pending status to "pending" |
| **No entry points (all have deps)** | Auto-fix: Clear depends_on for first item |
| **Queue file missing solutions** | Abort with error, agent must regenerate |
## Related Commands

View File

@@ -234,19 +234,25 @@
color: hsl(var(--muted-foreground));
cursor: pointer;
white-space: nowrap;
transition: all 0.15s;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.cli-stream-tab:hover {
background: hsl(var(--hover));
color: hsl(var(--foreground));
transform: translateY(-1px);
}
.cli-stream-tab.active {
background: hsl(var(--card));
border-color: hsl(var(--primary));
color: hsl(var(--foreground));
box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
box-shadow: 0 2px 8px rgb(0 0 0 / 0.15);
transform: translateY(-1px);
}
.cli-stream-tab.active .cli-stream-tab-tool {
color: hsl(var(--primary));
}
.cli-stream-tab-status {
@@ -379,7 +385,13 @@
white-space: pre-wrap;
word-break: break-all;
margin: 0;
padding: 0;
padding: 2px 0;
border-radius: 2px;
transition: background-color 0.15s;
}
.cli-stream-line:hover {
background: hsl(0 0% 100% / 0.03);
}
.cli-stream-line.stdout {
@@ -388,17 +400,33 @@
.cli-stream-line.stderr {
color: hsl(8 75% 65%);
background: hsl(8 75% 65% / 0.05);
}
.cli-stream-line.system {
color: hsl(210 80% 65%);
font-style: italic;
padding-left: 8px;
border-left: 2px solid hsl(210 80% 65% / 0.5);
}
.cli-stream-line.info {
color: hsl(200 80% 70%);
}
/* JSON/Code syntax coloring in output */
.cli-stream-line .json-key {
color: hsl(200 80% 70%);
}
.cli-stream-line .json-string {
color: hsl(100 50% 60%);
}
.cli-stream-line .json-number {
color: hsl(40 80% 65%);
}
/* Search highlight */
.cli-stream-highlight {
background: hsl(50 100% 50% / 0.4);

View File

@@ -17,10 +17,23 @@ function initCliStreamViewer() {
// Initialize keyboard shortcuts
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && isCliStreamViewerOpen) {
toggleCliStreamViewer();
if (searchFilter) {
clearSearch();
} else {
toggleCliStreamViewer();
}
}
// Ctrl+F to focus search when viewer is open
if ((e.ctrlKey || e.metaKey) && e.key === 'f' && isCliStreamViewerOpen) {
e.preventDefault();
const searchInput = document.getElementById('cliStreamSearchInput');
if (searchInput) {
searchInput.focus();
searchInput.select();
}
}
});
// Initialize scroll detection for auto-scroll
const content = document.getElementById('cliStreamContent');
if (content) {
@@ -491,7 +504,9 @@ function _streamT(key) {
'cliStream.autoScroll': 'Auto-scroll',
'cliStream.close': 'Close',
'cliStream.cannotCloseRunning': 'Cannot close running execution',
'cliStream.lines': 'lines'
'cliStream.lines': 'lines',
'cliStream.searchPlaceholder': 'Search output...',
'cliStream.filterResults': 'results'
};
return fallbacks[key] || key;
}

View File

@@ -55,6 +55,8 @@ const i18n = {
'cliStream.close': 'Close',
'cliStream.cannotCloseRunning': 'Cannot close running execution',
'cliStream.lines': 'lines',
'cliStream.searchPlaceholder': 'Search output...',
'cliStream.filterResults': 'results',
// Sidebar - Project section
'nav.project': 'Project',
@@ -1975,6 +1977,8 @@ const i18n = {
'cliStream.close': '关闭',
'cliStream.cannotCloseRunning': '无法关闭运行中的执行',
'cliStream.lines': '行',
'cliStream.searchPlaceholder': '搜索输出...',
'cliStream.filterResults': '条结果',
// Sidebar - Project section
'nav.project': '项目',

View File

@@ -618,6 +618,16 @@
<span data-i18n="cliStream.title">CLI Stream</span>
<span class="cli-stream-count-badge" id="cliStreamCountBadge">0</span>
</div>
<div class="cli-stream-search">
<i data-lucide="search" class="cli-stream-search-icon"></i>
<input type="text"
id="cliStreamSearchInput"
class="cli-stream-search-input"
placeholder="Search output..."
oninput="handleSearchInput(event)"
data-i18n-placeholder="cliStream.searchPlaceholder">
<button class="cli-stream-search-clear" onclick="clearSearch()" title="Clear search">&times;</button>
</div>
<div class="cli-stream-actions">
<button class="cli-stream-action-btn" onclick="clearCompletedStreams()" data-i18n="cliStream.clearCompleted">
<i data-lucide="trash-2"></i>

View File

@@ -0,0 +1,261 @@
/**
* Unit tests for Memory command module (ccw memory)
*
* Notes:
* - Targets the runtime implementation shipped in `ccw/dist`.
* - Uses Node's built-in test runner (node:test).
* - Avoids real network / Python executions by stubbing HTTP and asserting fail-fast paths.
*/
import { after, afterEach, before, beforeEach, describe, it, mock } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
class ExitError extends Error {
code?: number;
constructor(code?: number) {
super(`process.exit(${code ?? 'undefined'})`);
this.code = code;
}
}
const TEST_CCW_HOME = mkdtempSync(join(tmpdir(), 'ccw-memory-command-'));
const TEST_USER_HOME = join(TEST_CCW_HOME, 'user-home');
const memoryCommandPath = new URL('../dist/commands/memory.js', import.meta.url).href;
const memoryStorePath = new URL('../dist/core/memory-store.js', import.meta.url).href;
const coreMemoryStorePath = new URL('../dist/core/core-memory-store.js', import.meta.url).href;
const historyStorePath = new URL('../dist/tools/cli-history-store.js', import.meta.url).href;
function stubHttpRequest(): void {
mock.method(http, 'request', (_options: any, cb?: any) => {
const res = {
statusCode: 204,
on(_event: string, _handler: any) {},
};
if (cb) cb(res);
const req: any = {
on(event: string, handler: any) {
if (event === 'socket') handler({ unref() {} });
return req;
},
write() {},
end() {},
destroy() {},
};
return req;
});
}
describe('memory command module', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let memoryModule: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let memoryStoreModule: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let coreMemoryStoreModule: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let historyStoreModule: any;
const originalEnv = {
CCW_DATA_DIR: process.env.CCW_DATA_DIR,
USERPROFILE: process.env.USERPROFILE,
HOME: process.env.HOME,
};
before(async () => {
process.env.CCW_DATA_DIR = TEST_CCW_HOME;
process.env.USERPROFILE = TEST_USER_HOME;
process.env.HOME = TEST_USER_HOME;
memoryModule = await import(memoryCommandPath);
memoryStoreModule = await import(memoryStorePath);
coreMemoryStoreModule = await import(coreMemoryStorePath);
historyStoreModule = await import(historyStorePath);
});
beforeEach(() => {
// Ensure we don't read real user data or write to real CCW storage
process.env.CCW_DATA_DIR = TEST_CCW_HOME;
process.env.USERPROFILE = TEST_USER_HOME;
process.env.HOME = TEST_USER_HOME;
try {
memoryStoreModule?.closeAllStores?.();
coreMemoryStoreModule?.closeAllStores?.();
historyStoreModule?.closeAllStores?.();
} catch {
// ignore cleanup errors
}
if (existsSync(TEST_CCW_HOME)) {
rmSync(TEST_CCW_HOME, { recursive: true, force: true });
}
mkdirSync(TEST_CCW_HOME, { recursive: true });
mkdirSync(TEST_USER_HOME, { recursive: true });
});
afterEach(() => {
mock.restoreAll();
});
after(() => {
try {
memoryStoreModule?.closeAllStores?.();
coreMemoryStoreModule?.closeAllStores?.();
historyStoreModule?.closeAllStores?.();
} catch {
// ignore
}
process.env.CCW_DATA_DIR = originalEnv.CCW_DATA_DIR;
process.env.USERPROFILE = originalEnv.USERPROFILE;
process.env.HOME = originalEnv.HOME;
rmSync(TEST_CCW_HOME, { recursive: true, force: true });
});
it('tracks entity access and persists entity stats', async () => {
stubHttpRequest();
mock.method(console, 'log', () => {});
mock.method(console, 'error', () => {});
mock.method(process as any, 'exit', (code?: number) => {
throw new ExitError(code);
});
const value = 'D:\\Repo\\src\\auth.ts';
await memoryModule.memoryCommand('track', [], {
type: 'file',
action: 'read',
value,
session: 'S-1',
});
const store = memoryStoreModule.getMemoryStore(process.cwd());
const normalized = 'd:/Repo/src/auth.ts';
const entity = store.getEntity('file', normalized);
assert.ok(entity, 'Expected entity to be persisted');
const stats = store.getStats(entity.id);
assert.ok(stats, 'Expected entity stats to exist');
assert.equal(stats.read_count, 1);
});
it('validates required track options (type/action/value)', async () => {
stubHttpRequest();
mock.method(console, 'log', () => {});
mock.method(console, 'error', () => {});
mock.method(process as any, 'exit', (code?: number) => {
throw new ExitError(code);
});
await assert.rejects(
memoryModule.memoryCommand('track', [], { type: 'file' }),
(err: any) => err instanceof ExitError && err.code === 1,
);
});
it('imports history safely (no-op when ~/.claude/history.jsonl is missing)', async () => {
stubHttpRequest();
mock.method(process as any, 'exit', (code?: number) => {
throw new ExitError(code);
});
const logs: string[] = [];
mock.method(console, 'log', (...args: any[]) => {
logs.push(args.map(String).join(' '));
});
mock.method(console, 'error', (...args: any[]) => {
logs.push(args.map(String).join(' '));
});
await memoryModule.memoryCommand('import', [], { source: 'history' });
assert.ok(logs.some((l) => l.includes('Import Complete')));
assert.ok(logs.some((l) => l.includes('Total Imported: 0')));
});
it('outputs empty JSON for stats/search/suggest when no data exists', async () => {
stubHttpRequest();
mock.method(process as any, 'exit', (code?: number) => {
throw new ExitError(code);
});
const outputs: string[] = [];
mock.method(console, 'log', (...args: any[]) => {
outputs.push(args.map(String).join(' '));
});
outputs.length = 0;
await memoryModule.memoryCommand('stats', [], { json: true, limit: '5' });
assert.deepEqual(JSON.parse(outputs.at(-1) ?? 'null'), []);
outputs.length = 0;
await memoryModule.memoryCommand('search', ['auth'], { json: true, limit: '5' });
assert.deepEqual(JSON.parse(outputs.at(-1) ?? 'null'), []);
outputs.length = 0;
await memoryModule.memoryCommand('suggest', [], { json: true, limit: '3', context: 'ctx' });
const suggestJson = JSON.parse(outputs.at(-1) ?? 'null');
assert.deepEqual(suggestJson.suggestions, []);
assert.equal(suggestJson.context, 'ctx');
});
it('prune is a no-op when database is missing', async () => {
stubHttpRequest();
mock.method(process as any, 'exit', (code?: number) => {
throw new ExitError(code);
});
const logs: string[] = [];
mock.method(console, 'log', (...args: any[]) => {
logs.push(args.map(String).join(' '));
});
await memoryModule.memoryCommand('prune', [], { olderThan: '1d', dryRun: true });
assert.ok(logs.some((l) => l.includes('Nothing to prune') || l.includes('No memory database found')));
});
it('embed/embed-status/semantic-search fail fast without core-memory database', async () => {
stubHttpRequest();
const errors: string[] = [];
mock.method(console, 'log', () => {});
mock.method(console, 'error', (...args: any[]) => {
errors.push(args.map(String).join(' '));
});
mock.method(process as any, 'exit', (code?: number) => {
throw new ExitError(code);
});
// Embed
await assert.rejects(
memoryModule.memoryCommand('embed', [], {}),
(err: any) => err instanceof ExitError && err.code === 1,
);
// Embed status
await assert.rejects(
memoryModule.memoryCommand('embed-status', [], { json: true }),
(err: any) => err instanceof ExitError && err.code === 1,
);
// Semantic search (topK/minScore triggers semantic mode)
await assert.rejects(
memoryModule.memoryCommand('search', ['auth'], { topK: '5', minScore: '0.5', json: true }),
(err: any) => err instanceof ExitError && err.code === 1,
);
// Should not attempt long-running operations; it should fail before Python execution.
assert.ok(
errors.some((e) => /embedder not available|database not found/i.test(e)),
'Expected a fast-fail message about embedder availability or missing DB',
);
});
});