feat: add project index and exact patch review

This commit is contained in:
Agent Workbench Dev
2026-10-29 17:59:35 +08:00
parent 5ec85b0319
commit 14ce622028
45 changed files with 1290 additions and 82 deletions
+29 -12
View File
@@ -5,13 +5,14 @@ import { api, downloadBlob, exportSession, setToken } from './api';
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard } from './components';
import { DiagnosticsPanel } from './DiagnosticsPanel';
import { TaskPanel } from './TaskPanel';
import { CodeIndexPanel } from './CodeIndexPanel';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000 };
export default function App() {
const [token, setAccess] = useState('');
const [version, setVersion] = useState('1.2.0');
const [version, setVersion] = useState('1.3.0');
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
@@ -29,6 +30,8 @@ export default function App() {
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const [openFile, setOpenFile] = useState<OpenFile | null>(null);
const [fileLoading, setFileLoading] = useState(false);
const [fileLine, setFileLine] = useState<number | null>(null);
const [fileNotice, setFileNotice] = useState('');
const [draftSaving, setDraftSaving] = useState(false);
const [changeBusy, setChangeBusy] = useState('');
const [deciding, setDeciding] = useState(false);
@@ -37,7 +40,7 @@ export default function App() {
const [composer, setComposer] = useState('');
const [sending, setSending] = useState(false);
const [creatingSession, setCreatingSession] = useState(false);
const [tab, setTab] = useState<'file' | 'changes' | 'trace' | 'task'>('file');
const [tab, setTab] = useState<'file' | 'changes' | 'trace' | 'task' | 'index'>('file');
const [changeId, setChangeId] = useState('');
const [eventId, setEventId] = useState('');
const [wide, setWide] = useState(false);
@@ -59,6 +62,7 @@ export default function App() {
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
const chatEnd = useRef<HTMLDivElement>(null);
const conversationRef = useRef<HTMLElement>(null);
const codeViewRef = useRef<HTMLDivElement>(null);
const composerRef = useRef<HTMLTextAreaElement>(null);
const filterRef = useRef<HTMLInputElement>(null);
const selectedSessionRef = useRef('');
@@ -122,7 +126,7 @@ export default function App() {
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
});
}
function showInspector(next: 'file' | 'changes' | 'trace' | 'task') {
function showInspector(next: 'file' | 'changes' | 'trace' | 'task' | 'index') {
setTab(next);
if (window.innerWidth <= 940) setWide(true);
if (window.innerWidth <= 620) setSidebarOpen(false);
@@ -136,7 +140,7 @@ export default function App() {
async function chooseProject(id: string, preferredSession?: string) {
selectedProjectRef.current = id; setProjectId(id); localStorage.setItem('awb-project', id);
filesRequest.current++; fileRequest.current++;
setOpenFile(null); setFiles([]); setFileLoading(false); setEditing(false); setCollapsed(new Set()); setFilter('');
setOpenFile(null); setFiles([]); setFileLoading(false); setFileLine(null); setFileNotice(''); setEditing(false); setCollapsed(new Set()); setFilter('');
const candidate = preferredSession || briefs.find(item => item.projectId === id)?.id || '';
selectSession(candidate);
if (window.innerWidth <= 620) setSidebarOpen(false);
@@ -188,13 +192,17 @@ export default function App() {
notify('已打开项目 ' + project.name);
} catch (error) { failure(error); }
}
async function loadFile(relative: string) {
async function loadFile(relative: string, location?: { line: number; expectedSha256: string }) {
if (!projectId) return;
const targetProject = projectId, request = ++fileRequest.current;
showInspector('file'); setFileLoading(true); setEditing(false);
showInspector('file'); setFileLoading(true); setEditing(false); setFileLine(null); setFileNotice('');
try {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
if (fileRequest.current === request && selectedProjectRef.current === targetProject) { setOpenFile(file); setDraft(file.content); }
if (fileRequest.current === request && selectedProjectRef.current === targetProject) {
setOpenFile(file); setDraft(file.content);
if (location && file.sha256 !== location.expectedSha256) setFileNotice('文件在索引后已变化,已打开当前内容。请回到索引刷新后重新定位。');
else if (location && location.line >= 1 && location.line <= file.content.split('\n').length) setFileLine(location.line);
}
} catch (error) { if (fileRequest.current === request) failure(error); }
finally { if (fileRequest.current === request) setFileLoading(false); }
}
@@ -218,7 +226,7 @@ export default function App() {
acceptSession(updated); await refreshFiles(targetProject);
if (action === 'apply' && openFile?.path === change.path && selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(change.path));
if (selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) { setOpenFile(file); setDraft(file.content); setEditing(false); }
if (selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) { setOpenFile(file); setDraft(file.content); setEditing(false); setFileLine(null); setFileNotice(''); }
}
notify(action === 'apply' ? '已应用 ' + change.path : '已撤回提案。');
} catch (error) { failure(error); } finally { setChangeBusy(''); }
@@ -363,6 +371,14 @@ export default function App() {
const viewport = conversationRef.current;
if (viewport) viewport.scrollTop = viewport.scrollHeight;
}, [session?.messages.length, session?.events.length, approval?.id]);
useEffect(() => {
if (!fileLine || tab !== 'file' || editing) return;
const frame = requestAnimationFrame(() => {
const viewport = codeViewRef.current, line = viewport?.querySelector<HTMLElement>('[data-line="' + fileLine + '"]');
if (viewport && line) viewport.scrollTop += line.getBoundingClientRect().top - viewport.getBoundingClientRect().top - viewport.clientHeight * .35;
});
return () => cancelAnimationFrame(frame);
}, [openFile?.sha256, fileLine, tab, wide, editing]);
useEffect(() => {
let previousMobile = window.innerWidth <= 620;
const update = () => {
@@ -435,12 +451,13 @@ export default function App() {
</main>
{((mobile && sidebarOpen) || (narrow && wide)) && <button type="button" className="panel-scrim" aria-label="关闭侧边面板" onClick={() => { setSidebarOpen(false); setWide(false); }} />}
<aside className="inspector">
<div className="inspector-tabs"><button className={tab === 'file' ? 'selected' : ''} onClick={() => setTab('file')}><FileCode2 size={14} />文件</button><button className={tab === 'changes' ? 'selected' : ''} onClick={() => setTab('changes')}><GitBranch size={14} />改动{pending.length > 0 && <b>{pending.length}</b>}</button><button className={tab === 'trace' ? 'selected' : ''} onClick={() => setTab('trace')}><SquareTerminal size={14} />轨迹</button><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck size={14} />任务</button><IconButton label={narrow ? '关闭检视区' : wide ? '缩小检视区' : '放大检视区'} onClick={() => setWide(previous => !previous)}>{narrow ? <X size={16} /> : wide ? <Minimize2 size={14} /> : <Maximize2 size={14} />}</IconButton></div>
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span><IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : <div className="code-view">{openFile.content.split('\n').map((line, index) => <div key={index}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
{tab === 'changes' && (selectedChange ? <div className="changes-inspector"><div className="change-list">{session?.changes.map(change => <button key={change.id} className={selectedChange.id === change.id ? 'selected' : ''} onClick={() => setChangeId(change.id)}><FileCode2 size={14} /><span>{change.path}</span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></button>)}</div><div className="change-summary"><div><strong>{selectedChange.path}</strong><Status value={selectedChange.status} /></div><p>{selectedChange.reason}</p></div><DiffView change={selectedChange} /><div className="change-actions">{['pending', 'conflict'].includes(selectedChange.status) ? <><button className="button secondary" onClick={() => changeAction(selectedChange, 'reject')} disabled={!!changeBusy || isRunning}>撤回提案</button><button className="button primary" disabled={selectedChange.status !== 'pending' || !!changeBusy || isRunning} onClick={() => changeAction(selectedChange, 'apply')}><Check size={14} />应用这项改动</button></> : <span className="subtle">{selectedChange.status === 'applied' ? '这项改动已写入项目。' : '这项提案已结束。'}</span>}<IconButton label="下载建议内容" onClick={() => downloadBlob(new Blob([selectedChange.content], { type: 'text/plain;charset=utf-8' }), selectedChange.path.split('/').at(-1) || 'proposal.txt')}><ArrowDownToLine size={15} /></IconButton></div></div> : <EmptyInspector kind="changes" />)}
<div className="inspector-tabs"><button className={tab === 'file' ? 'selected' : ''} onClick={() => setTab('file')}><FileCode2 size={14} />文件</button><button className={tab === 'changes' ? 'selected' : ''} onClick={() => setTab('changes')}><GitBranch size={14} />改动{pending.length > 0 && <b>{pending.length}</b>}</button><button className={tab === 'trace' ? 'selected' : ''} onClick={() => setTab('trace')}><SquareTerminal size={14} />轨迹</button><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck size={14} />任务</button><button className={tab === 'index' ? 'selected' : ''} onClick={() => setTab('index')}><Search size={14} />索引</button><IconButton label={narrow ? '关闭检视区' : wide ? '缩小检视区' : '放大检视区'} onClick={() => setWide(previous => !previous)}>{narrow ? <X size={16} /> : wide ? <Minimize2 size={14} /> : <Maximize2 size={14} />}</IconButton></div>
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span><IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B{fileLine ? ' · 定位第 ' + fileLine + ' 行' : ''}</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{fileNotice && <div className="file-index-notice" role="status">{fileNotice}</div>}{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : <div className="code-view" ref={codeViewRef}>{openFile.content.split('\n').map((line, index) => <div key={index} data-line={index + 1} className={fileLine === index + 1 ? 'code-line-target' : ''}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
{tab === 'changes' && (selectedChange ? <div className="changes-inspector"><div className="change-list">{session?.changes.map(change => <button key={change.id} className={selectedChange.id === change.id ? 'selected' : ''} onClick={() => setChangeId(change.id)}><FileCode2 size={14} /><span>{change.path}</span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></button>)}</div><div className="change-summary"><div><strong>{selectedChange.path}</strong><Status value={selectedChange.status} /></div><p>{selectedChange.reason}</p>{selectedChange.patch && <p className="patch-detail">精确补丁 · {selectedChange.patch.edits} 处替换 · {selectedChange.patch.lineEnding === 'mixed' ? '按原文核对混合换行' : '保留 ' + selectedChange.patch.lineEnding.toUpperCase() + ' 换行'}{selectedChange.patch.preservedBom ? ' · 保留 BOM' : ''}</p>}</div><DiffView change={selectedChange} /><div className="change-actions">{['pending', 'conflict'].includes(selectedChange.status) ? <><button className="button secondary" onClick={() => changeAction(selectedChange, 'reject')} disabled={!!changeBusy || isRunning}>撤回提案</button><button className="button primary" disabled={selectedChange.status !== 'pending' || !!changeBusy || isRunning} onClick={() => changeAction(selectedChange, 'apply')}><Check size={14} />应用这项改动</button></> : <span className="subtle">{selectedChange.status === 'applied' ? '这项改动已写入项目。' : '这项提案已结束。'}</span>}<IconButton label="下载建议内容" onClick={() => downloadBlob(new Blob([selectedChange.content], { type: 'text/plain;charset=utf-8' }), selectedChange.path.split('/').at(-1) || 'proposal.txt')}><ArrowDownToLine size={15} /></IconButton></div></div> : <EmptyInspector kind="changes" />)}
{tab === 'trace' && (session?.events.length ? <div className="trace-inspector"><div className="trace-caption"><span>完整执行记录</span><span>{toolEvents.length} 次工具调用</span></div><div className="trace-list">{session.events.map(event => <ToolRow key={event.id} event={event} selected={selectedEvent?.id === event.id} onSelect={() => setEventId(event.id)} />)}</div>{selectedEvent && <div className="event-details"><div className="event-detail-heading"><strong>{selectedEvent.label}</strong><Status value={selectedEvent.phase} /></div>{selectedEvent.input && <><h4>输入</h4><pre>{JSON.stringify(selectedEvent.input, null, 2)}</pre></>}<h4>结果</h4><pre>{selectedEvent.output || (selectedEvent.phase === 'waiting' ? '等待确认后执行。' : '正在等待工具结果。')}</pre>{selectedEvent.durationMs !== undefined && <p className="subtle">耗时 {(selectedEvent.durationMs / 1000).toFixed(2)} 秒,包含确认等待。</p>}</div>}</div> : <EmptyInspector kind="trace" />)}
{tab === 'task' && (session ? <TaskPanel key={session.id} session={session} onSession={acceptSession} onError={failure} busy={isRunning} /> : <EmptyInspector kind="trace" />)}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : '读取范围限定在当前项目'}</span></div>
{selectedProject && <CodeIndexPanel key={selectedProject.id} project={selectedProject} active={tab === 'index'} onOpen={(path, line, expectedSha256) => void loadFile(path, { line, expectedSha256 })} />}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
</aside>
{projectOpen && <Modal title="打开项目" description="选择要在本机读取和开发的项目文件夹。" onClose={() => setProjectOpen(false)}><form onSubmit={event => { event.preventDefault(); openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} onChange={event => setProjectInput(event.target.value)} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label><div className="modal-actions">{exampleId && <button type="button" className="button secondary" onClick={() => { chooseProject(exampleId); setProjectOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim()}><FolderOpen size={15} />打开项目</button></div></form></Modal>}
{settingsOpen && <Modal title="模型连接" description="同一套项目工具,可以使用离线演示或你自己的模型服务。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
+34
View File
@@ -0,0 +1,34 @@
.code-index-panel{display:flex;flex:1;flex-direction:column;min-height:0;overflow:hidden;background:#FCFDFC}
.code-index-panel[hidden]{display:none}
.index-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:17px 16px 13px;border-bottom:1px solid #dde8e3}
.index-heading>div{min-width:0}.index-heading .field-eyebrow{display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.index-heading h3{margin:7px 0 0;font-family:Bahnschrift,'Segoe UI','Microsoft YaHei',sans-serif;font-size:20px;font-weight:600;color:#154B4A}
.index-search{padding:13px 16px;border-bottom:1px solid #dde8e3;background:#FCFDFC}
.index-query{display:flex;align-items:center;gap:8px;padding:0 10px;border:1px solid #b8ccc4;border-radius:7px;color:#154B4A;background:white}
.index-query:focus-within{border-color:#4664D9;box-shadow:0 0 0 2px #4664D918}
.index-query input{flex:1;min-width:0;width:100%;border:0!important;box-shadow:none!important;padding:10px 0;background:transparent;outline:none;font-size:12px;color:#1C2E32}
.index-query input:focus-visible{outline:none!important}
.index-search-controls{display:flex;justify-content:space-between;gap:9px;margin-top:9px}.index-search-controls select{min-width:0;flex:1;border:1px solid #ccdcd4;background:#EDF3F1;border-radius:6px;padding:7px 9px;color:#1C2E32;font-size:12px}
.index-search-controls .button{padding:7px 13px;font-size:12px;min-width:78px;justify-content:center}
.index-scroll{flex:1;min-height:0;overflow:auto;padding:13px 16px 20px}
.index-coverage{border-left:3px solid #154B4A;background:#EDF3F1;padding:11px 12px;font-size:11px;line-height:1.6;color:#526b63}
.index-coverage>div{display:flex;justify-content:space-between;gap:8px}.index-coverage strong{color:#154B4A;font-size:12px}.index-coverage p{margin:5px 0;color:#1C2E32;font-variant-numeric:tabular-nums}.index-coverage.partial{border-color:#A16C21;background:#A16C210B}.index-coverage.partial strong{color:#A16C21}
.index-scope{margin:10px 0 16px;font-size:11px;color:#526b63;line-height:1.8}.index-scope summary{cursor:pointer;color:#154B4A}.index-scope p{margin:7px 0}.index-scope>code{display:block;font-size:10px;overflow-wrap:anywhere;line-height:1.7;margin-top:5px}
.index-result-caption{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:#60736d;padding:0 0 9px}.index-result-caption>span:first-child{min-width:0;overflow-wrap:anywhere}.index-result-caption>span:last-child{flex-shrink:0}
.index-results{display:flex;flex-direction:column;gap:8px}
.index-result{width:100%;text-align:left;padding:12px 10px;border:1px solid #d8e4de;border-radius:7px;background:#FCFDFC;transition:border-color .15s,background .15s;color:#1C2E32;cursor:pointer}
.index-result:hover:not(:disabled){border-color:#154B4A;background:#EDF3F150}.index-result:disabled{opacity:.55;cursor:default}.index-result:focus-visible{outline:2px solid #4664D9;outline-offset:2px}
.index-result-title{display:flex;align-items:center;gap:6px;color:#154B4A}.index-result-title>strong{font-family:'Cascadia Code',Consolas,monospace;font-size:12px;overflow-wrap:anywhere;min-width:0;flex:1}.index-result-title>span{flex-shrink:0;font-size:10px;color:#526b63;padding:1px 5px;background:#EDF3F1;border-radius:3px}.index-result-title>svg{flex-shrink:0}
.index-result-location{display:flex;align-items:baseline;gap:1px;margin:7px 0;color:#526b63;font-family:'Cascadia Code',Consolas,monospace;font-size:11px}.index-result-location>span{min-width:0;overflow-wrap:anywhere}.index-result-location>b{color:#4664D9;font-weight:500;flex-shrink:0}
.index-signature{display:block;width:100%;font-size:10px;color:#61736c;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.index-target{font-size:10px;overflow-wrap:anywhere;color:#526b63;line-height:1.7;margin:6px 0 0}
.index-result-evidence{display:flex;justify-content:space-between;gap:6px;margin-top:8px;font-size:10px;color:#73827b}.index-result-evidence>code{font-size:10px;flex-shrink:0}
.index-empty{text-align:center;padding:35px 13px;color:#60736d;font-size:12px;line-height:1.8}.index-empty>svg{color:#154B4A}.index-empty h4{font-size:14px;color:#154B4A;margin:12px 0 4px}.index-empty p{margin:0}
.index-limit{font-size:11px;line-height:1.8;margin:14px 0 0;color:#60736d}.index-error,.index-warnings{font-size:11px;line-height:1.8;background:#A16C210B;border:1px solid #A16C2135;border-radius:6px;padding:10px;margin:0 0 12px;color:#76541f}.index-error p,.index-warnings p{margin:5px 0;overflow-wrap:anywhere}.index-warnings p>span{display:block;font-family:'Cascadia Code',Consolas,monospace;color:#1C2E32;font-size:10px}
.file-index-notice{padding:10px 13px;border-bottom:1px solid #A16C2135;background:#A16C210B;color:#76541f;font-size:11px;line-height:1.7;flex-shrink:0}
.code-view>div.code-line-target{background:#4664D915;box-shadow:inset 3px 0 #4664D9}.code-view>div.code-line-target>span{color:#4664D9;font-weight:600}
.patch-detail{color:#154B4A!important;font-size:11px!important}
.inspector-tabs{gap:3px;padding-left:8px;padding-right:8px}.inspector-tabs>button:not(.icon-button){white-space:nowrap;flex-shrink:0;padding-left:6px;padding-right:6px;gap:4px}.inspector-tabs>.icon-button{flex-shrink:0}
.diff-caption{position:sticky;top:0;z-index:1;background:#FCFDFC}.diff-jump{font-size:10px;color:#4664D9;white-space:nowrap;padding:3px 5px;border-radius:3px}.diff-jump:hover{background:#4664D910}
@media(max-width:1250px){.inspector-tabs{gap:1px;padding-left:7px;padding-right:7px}.inspector-tabs>button:not(.icon-button){padding-left:7px;padding-right:7px}}
@media(max-width:620px){.index-heading,.index-search{padding-left:13px;padding-right:13px}.index-scroll{padding-left:13px;padding-right:13px}}
@media(prefers-reduced-motion:reduce){.index-result{transition:none}}
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowUpRight, FileCode2, LoaderCircle, RefreshCw, Search } from 'lucide-react';
import { api } from './api';
import type { CodeQuery, CodeQueryKind, CodeResult, Project } from './types';
import './CodeIndexPanel.css';
const kindNames: Record<string, string> = { function: '函数', method: '方法', class: '类', interface: '接口', type: '类型', enum: '枚举', binding: '变量' };
const resultName = (result: CodeResult) => result.resultKind === 'symbol' ? result.qualifiedName || result.name : result.name;
export function CodeIndexPanel({ project, active, onOpen }: {
project: Project; active: boolean; onOpen: (path: string, line: number, sha256: string) => void;
}) {
const [query, setQuery] = useState('');
const [kind, setKind] = useState<CodeQueryKind>('all');
const [result, setResult] = useState<CodeQuery | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const request = useRef(0);
const initialLoad = useRef(false);
async function search(nextKind = kind) {
const current = ++request.current;
setBusy(true); setError('');
try {
const response = await api<CodeQuery>('/projects/' + project.id + '/code-query?query=' + encodeURIComponent(query.trim()) + '&kind=' + nextKind + '&limit=40');
if (current !== request.current || response.index.projectId !== project.id) return;
setResult(response);
} catch (cause) {
if (current === request.current) setError(cause instanceof Error ? cause.message : String(cause));
} finally { if (current === request.current) setBusy(false); }
}
useEffect(() => () => { request.current++; initialLoad.current = false; }, [project.id, project.root]);
useEffect(() => {
if (active && !initialLoad.current) { initialLoad.current = true; void search(); }
}, [active]);
const index = result?.index, coverage = index?.coverage;
return <section className="code-index-panel" aria-label="工程索引" hidden={!active}>
<header className="index-heading"><div><span className="field-eyebrow">当前项目 · {project.name}</span><h3>定位代码</h3></div>
<button className="icon-button" aria-label="刷新工程索引" title="重新核对文件变化并刷新结果" disabled={busy} onClick={() => void search()}>
{busy ? <LoaderCircle size={16} className="spin" /> : <RefreshCw size={16} />}
</button>
</header>
<form className="index-search" onSubmit={event => { event.preventDefault(); void search(); }}>
<label className="index-query"><Search size={15} /><input aria-label="索引查询" maxLength={200} placeholder="函数、类、文件名或导入" value={query} onChange={event => setQuery(event.target.value)} /></label>
<div className="index-search-controls"><select aria-label="索引结果类型" value={kind} onChange={event => { const next = event.target.value as CodeQueryKind; setKind(next); void search(next); }}>
<option value="all">全部结果</option><option value="symbols">符号声明</option><option value="imports">导入关系</option><option value="files">项目文件</option>
</select><button className="button primary" type="submit" disabled={busy}>{busy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}查找</button></div>
</form>
<div className="index-scroll" aria-busy={busy}>
{error && <div className="index-error" role="alert"><strong>索引未刷新</strong><p>{error}</p><button className="button secondary" disabled={busy} onClick={() => void search()}>重试索引</button></div>}
{index && coverage && <>
<div className={'index-coverage ' + (coverage.truncated ? 'partial' : '')}>
<div><strong>{coverage.truncated ? '部分结果' : '当前范围已索引'}</strong><span>{new Date(index.generatedAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</span></div>
<p>{coverage.fileCount} 个文件 · {coverage.symbolCount} 个符号 · {coverage.importCount} 处导入</p>
<span>本次 {index.refresh.updatedFiles} 更新 · {index.refresh.reusedFiles} 复用 · {index.refresh.removedFiles} 移除</span>
</div>
<details className="index-scope"><summary>查看索引范围与依据</summary>
<p>{coverage.astFiles} 个 JS/TS/React 文件采用静态声明分析;{coverage.pythonCandidateFiles} 个 Python 文件提供声明候选。</p>
<p>已检查 {index.sourceScope.scannedFiles} 个文件,快照上限 {index.sourceScope.maximumFiles} 个文件;单文件符号分析上限 {Math.round(coverage.maximumFileBytes / 1000)} KB。</p>
<p>{index.sourceScope.note}</p>{index.notes.map(note => <p key={note}>{note}</p>)}
<code title={index.indexFingerprint}>索引 {index.indexFingerprint}</code>
<code title={index.sourceFingerprint}>源码 {index.sourceFingerprint}</code>
</details>
{index.warnings.length > 0 && <div className="index-warnings"><strong>{coverage.unindexedFiles} 个文件需要补充核对</strong>
{index.warnings.slice(0, 4).map(warning => <p key={warning.path}><span>{warning.path}</span>{warning.message}</p>)}
{index.warnings.length > 4 && <p>其余文件可按名称查询后读取当前内容。</p>}
</div>}
<div className="index-result-caption" role="status"><span>{result!.query ? `“${result!.query}”` : '当前结果'} · {result!.totalMatches} 项匹配</span><span>显示 {result!.results.length} 项</span></div>
<div className="index-results">{result!.results.map((item, position) => <button type="button" className="index-result" key={item.resultKind + item.path + item.line + position}
disabled={busy || !!error} aria-label={'打开 ' + item.path + ' 第 ' + item.line + ' 行 ' + resultName(item)} onClick={() => onOpen(item.path, item.line, item.sha256)}>
<div className="index-result-title"><FileCode2 size={14} /><strong>{resultName(item)}</strong><span>{item.resultKind === 'symbol' ? kindNames[item.kind] || '声明' : item.resultKind === 'import' ? '导入' : '文件'}</span><ArrowUpRight size={13} /></div>
<div className="index-result-location"><span>{item.path}</span><b>:{item.line}</b></div>
{item.signature && <code className="index-signature" title={item.signature}>{item.signature}</code>}
{item.resultKind === 'import' && <p className="index-target">{item.target ? '文件候选 → ' + item.target : item.status === 'external-or-alias' ? '外部模块或路径别名,目标未解析' : '当前范围没有对应本地文件'}</p>}
<div className="index-result-evidence"><span>{item.evidenceMethod === 'python-declaration-candidate' ? 'Python 候选 · 需读源码核对' : item.evidenceMethod === 'javascript-typescript-ast' ? '静态声明' : '文件指纹'}{item.exported ? ' · 已导出' : ''}</span><code>{item.sha256.slice(0, 10)}</code></div>
</button>)}</div>
{result!.results.length === 0 && <div className="index-empty"><Search size={22} /><h4>当前范围没有匹配</h4><p>调整名称、路径或结果类型;文件刚有变化时可刷新索引。</p></div>}
{result!.truncated && <p className="index-limit">这里只展示当前范围的有限结果。可以增加查询词缩小范围;无匹配不代表整个项目都没有该代码。</p>}
</>}
{!result && !error && <div className="index-empty"><LoaderCircle className="spin" size={22} /><h4>正在核对项目文件</h4><p>读取实际声明、导入及文件指纹。</p></div>}
</div>
</section>;
}
+14 -4
View File
@@ -47,6 +47,15 @@ export function Modal({ title, description, children, onClose, wide = false }: {
</div>, document.body);
}
export function DiffView({ change }: { change: Change }) {
const viewport = useRef<HTMLDivElement>(null);
function jumpToFirstChange() {
const area = viewport.current, row = area?.querySelector<HTMLElement>('.diff-added, .diff-removed');
if (area && row) area.scrollTop += row.getBoundingClientRect().top - area.getBoundingClientRect().top - 85;
}
useEffect(() => {
const frame = requestAnimationFrame(jumpToFirstChange);
return () => cancelAnimationFrame(frame);
}, [change.id]);
let before = 1, after = 1;
const rows: { before: number | null; after: number | null; text: string; kind: string }[] = [];
for (const part of change.diff) {
@@ -57,8 +66,8 @@ export function DiffView({ change }: { change: Change }) {
kind: part.added ? 'added' : part.removed ? 'removed' : 'same' });
}
}
return <div className="diff-view" aria-label={'文件差异 ' + change.path}>
<div className="diff-caption"><span>{change.baseExists ? '原文件 → 建议内容' : '新建文件'}</span><span className="code-utility">{change.baseSha256?.slice(0, 10) || 'NEW'}</span></div>
return <div className="diff-view" aria-label={'文件差异 ' + change.path} ref={viewport}>
<div className="diff-caption"><span>{change.baseExists ? '原文件 → 建议内容' : '新建文件'}</span><button type="button" className="diff-jump" onClick={jumpToFirstChange}>定位首处改动</button><span className="code-utility">{change.baseSha256?.slice(0, 10) || 'NEW'}</span></div>
{rows.length ? rows.map((row, index) => <div key={index} className={'diff-line diff-' + row.kind}>
<span className="line-number">{row.before}</span><span className="line-number">{row.after}</span>
<span className="diff-sign">{row.kind === 'added' ? '+' : row.kind === 'removed' ? '−' : ' '}</span><code>{row.text || ' '}</code>
@@ -70,8 +79,9 @@ export function ToolRow({ event, selected = false, onSelect }: { event: ToolEven
const Symbol = ['waiting', 'unknown', 'unverified', 'queued', 'validating'].includes(phase) ? ShieldQuestion : ['running', 'retrying'].includes(phase) ? LoaderCircle
: ['failed', 'denied', 'interrupted'].includes(phase) ? XCircle : Check;
const detail = event.tool === 'run_command' ? String(event.input?.command || '')
: event.tool === 'read_file' || event.tool === 'propose_file' ? String(event.input?.path || '')
: event.tool === 'search_files' ? String(event.input?.query || '') : event.tool === 'list_files' ? '项目目录'
: ['read_file', 'propose_file', 'propose_patch'].includes(event.tool || '') ? String(event.input?.path || '')
: ['search_files', 'query_code'].includes(event.tool || '') ? String(event.input?.query || '') : event.tool === 'list_files' ? '项目目录'
: event.tool === 'index_project' ? '当前项目 · 声明与导入'
: event.tool === 'inspect_session' ? '会话 · 错误 · 当前状态' : event.kind === 'model' ? '模型服务' + (event.attempts && event.attempts > 1 ? ' · 第 ' + event.attempts + ' 次' : '') : '';
return <button type="button" onClick={onSelect} className={'tool-row ' + (selected ? 'selected ' : '') + 'tool-' + phase}>
<span className="tool-symbol"><Symbol size={14} className={['running', 'retrying'].includes(phase) ? 'spin' : ''} /></span>
+17 -1
View File
@@ -18,6 +18,8 @@ export interface Change {
id: string; path: string; reason: string; status: string; baseExists: boolean; baseSha256: string | null;
baseContent: string; content: string; sha256: string; diff: DiffPart[]; additions: number; deletions: number;
createdAt: string; appliedAt?: string;
editKind?: 'exact-patch';
patch?: { edits: number; lineEnding: 'lf' | 'crlf' | 'mixed'; preservedBom: boolean; ranges: { startLine: number; endLine: number; anchorSha256: string; replacementSha256: string }[] };
}
export interface Approval { id: string; command: string; reason: string; cwd: string; shell?: string; status: string; createdAt: string; checkPlanId?: string; checkScripts?: { name: string; script: string; lifecycle: { name: string; script: string }[] }[] }
export interface Session {
@@ -45,10 +47,24 @@ export interface RuntimeDiagnostics {
} | null;
}
export interface FileEntry { path: string; name: string; kind: string; bytes: number }
export interface OpenFile { path: string; content: string; sha256: string; bytes: number }
export interface OpenFile { path: string; content: string; sha256: string; bytes: number; bom?: boolean }
export interface Bootstrap { token: string; version: string; config: Config; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment; eventCursor?: number; storage?: { engine: string; schemaVersion: number }; runtimeRoot?: string }
export interface ResearchDoc { id: string; title: string; description: string }
export type CodeQueryKind = 'all' | 'symbols' | 'imports' | 'files';
export interface CodeIndexSummary {
schemaVersion: number; projectId: string; projectName: string; parser: string; generatedAt: string; sourceFingerprint: string; indexFingerprint: string;
coverage: { snapshotComplete: boolean; fileCount: number; symbolCount: number; importCount: number; astFiles: number; pythonCandidateFiles: number; unindexedFiles: number; truncated: boolean; maximumFileBytes: number; maximumSymbols: number };
refresh: { updatedFiles: number; reusedFiles: number; removedFiles: number };
sourceScope: { complete: boolean; scannedFiles: number; bytes: number; maximumFiles: number; maximumBytes: number; excludedFiles: number; note: string };
warnings: { path: string; sha256: string; status: string; message: string; line: number }[]; notes: string[];
}
export interface CodeResult {
resultKind: 'symbol' | 'import' | 'file'; path: string; line: number; sha256: string; name: string; kind: string;
qualifiedName?: string; signature?: string; evidenceMethod: string; exported?: boolean; status?: string; target?: string | null;
}
export interface CodeQuery { query: string; kind: CodeQueryKind; results: CodeResult[]; totalMatches: number; truncated: boolean; index: CodeIndexSummary }
export interface ModelSnapshot { mode: string; model: string; baseUrl: string; verified?: boolean; contextLimit?: number; maxOutputTokens?: number }
export interface Usage { requests: number; inputTokens: number; outputTokens: number; totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
export interface RunBudget { maxSteps: number; maxDurationMs: number; maxTokens: number; maxTaskTokens: number }
+228
View File
@@ -0,0 +1,228 @@
import path from 'node:path';
import { createHash } from 'node:crypto';
import { parse } from '@babel/parser';
import { inspectProject } from '../project-inspector.mjs';
import { readText } from '../../server/files.mjs';
const hash = value => createHash('sha256').update(value).digest('hex');
const conflict = message => Object.assign(new Error(message), { status: 409 });
const js = /\.(?:[mc]?js|jsx|[mc]?ts|tsx)$/i;
const functionTypes = new Set(['FunctionExpression', 'ArrowFunctionExpression']);
const names = { FunctionDeclaration: 'function', FunctionExpression: 'function', TSDeclareFunction: 'function', ClassDeclaration: 'class', ClassExpression: 'class', TSTypeAliasDeclaration: 'type', TSInterfaceDeclaration: 'interface', TSEnumDeclaration: 'enum' };
const parserVersion = 'babel-parser-7.29.11';
const nodeName = node => node?.type === 'Identifier' ? node.name : node?.type === 'PrivateName' ? '#' + node.id.name : node?.type === 'StringLiteral' ? node.value : null;
function javascript(source, filename, maximumNodes, maximumSymbols) {
const plugins = [...(/\.(?:[mc]?ts|tsx)$/i.test(filename) ? ['typescript'] : []), ...(/\.(?:[mc]?js|jsx|tsx)$/i.test(filename) ? ['jsx'] : []), 'decorators-legacy'];
const ast = parse(source, { sourceType: 'unambiguous', plugins, createImportExpressions: true, allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true });
const exported = new Set(), exportNames = new Set(), topLevel = new Set();
for (const entry of ast.program.body) {
const declaration = entry.declaration ?? entry;
const declarations = declaration.type === 'VariableDeclaration' ? declaration.declarations : [declaration];
for (const node of declarations) {
topLevel.add(node);
if (entry.type.startsWith('Export')) exported.add(node);
}
if (entry.type === 'ExportNamedDeclaration') for (const specifier of entry.specifiers) if (specifier.local?.name) exportNames.add(specifier.local.name);
if (entry.type === 'ExportDefaultDeclaration' && declaration.type === 'Identifier') exportNames.add(declaration.name);
}
const symbols = [], imports = [], stack = [{ node: ast.program, parent: null, scope: [] }];
let visited = 0, truncated = false, opaqueImports = 0;
while (stack.length) {
const { node, parent, scope } = stack.pop();
if (++visited > maximumNodes) { truncated = true; break; }
let name = nodeName(node.id), kind = names[node.type] ?? null;
if (functionTypes.has(node.type) && parent?.type === 'ExportDefaultDeclaration') kind = 'function';
if (!name && kind && parent?.type === 'ExportDefaultDeclaration') name = 'default';
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier') {
name = node.id.name;
kind = functionTypes.has(node.init?.type) ? 'function' : topLevel.has(node) ? 'binding' : null;
}
if (['ClassMethod', 'ClassPrivateMethod', 'ObjectMethod', 'TSMethodSignature'].includes(node.type)
|| ['ClassProperty', 'ClassPrivateProperty'].includes(node.type) && functionTypes.has(node.value?.type)) {
name = !node.computed ? nodeName(node.key) : null; kind = name ? 'method' : null;
}
if (name && kind) {
const cut = node.body?.start ?? node.init?.body?.start ?? node.value?.body?.start ?? node.id?.end ?? node.key?.end ?? node.end;
const signature = source.slice(node.start, Math.min(cut, node.start + 240)).replace(/\s+/g, ' ').trim();
if (symbols.length < maximumSymbols) symbols.push({ name, qualifiedName: [...scope, name].join('.'), kind, line: node.loc.start.line,
column: node.loc.start.column + 1, endLine: node.loc.end.line, signature, exported: exported.has(node) || topLevel.has(node) && exportNames.has(name), evidenceMethod: 'javascript-typescript-ast' });
else truncated = true;
}
let sourceNode, importKind;
if (node.type === 'ImportDeclaration') { sourceNode = node.source; importKind = node.importKind === 'type' ? 'type-import' : 'import'; }
else if (['ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && node.source) { sourceNode = node.source; importKind = 're-export'; }
else if (node.type === 'ImportExpression') { sourceNode = node.source; importKind = 'literal-dynamic-import'; }
else if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && node.callee.name === 'require') { sourceNode = node.arguments[0]; importKind = 'literal-require-call'; }
else if (node.type === 'TSImportEqualsDeclaration' && node.moduleReference?.type === 'TSExternalModuleReference') { sourceNode = node.moduleReference.expression; importKind = 'import-equals'; }
if (sourceNode?.type === 'StringLiteral' && imports.length < 400) imports.push({ source: sourceNode.value.slice(0, 500), line: node.loc.start.line,
kind: importKind, bindings: node.type === 'TSImportEqualsDeclaration' ? [nodeName(node.id)].filter(Boolean) : (node.specifiers ?? []).map(value => nodeName(value.local)).filter(Boolean).slice(0, 30), evidenceMethod: 'javascript-typescript-ast' });
else if (sourceNode) { truncated = true; if (sourceNode.type !== 'StringLiteral') opaqueImports++; }
let childScope = scope;
if (name && (names[node.type] && ['function', 'class'].includes(kind) || node.type === 'VariableDeclarator' && kind === 'function' || kind === 'method')) childScope = [...scope, name];
if (node.type === 'ObjectExpression' && parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier') childScope = [...scope, parent.id.name];
const children = Object.values(node).flatMap(value => Array.isArray(value) ? value : value && typeof value === 'object' ? [value] : []).filter(value => typeof value?.type === 'string');
for (let i = children.length - 1; i >= 0; i--) stack.push({ node: children[i], parent: node, scope: childScope });
}
return { symbols, imports, method: 'javascript-typescript-ast', truncated, opaqueImports, visitedNodes: visited };
}
// This lexer only removes comments and string bodies so declaration candidates
// do not come from docstrings. It is deliberately not a Python compiler.
function python(source, maximumSymbols) {
let triple = null, quote = null, escaped = false, truncated = false, bracketDepth = 0, lineContinuation = false;
const symbols = [], imports = [], scopes = [];
const lines = source.split('\n');
for (let index = 0; index < lines.length; index++) {
const line = lines[index], continued = bracketDepth > 0 || lineContinuation; let cleaned = '';
for (let i = 0; i < line.length;) {
const char = line[i], three = line.slice(i, i + 3);
if (triple) {
if (three === triple && !escaped) { triple = null; cleaned += ' '; i += 3; }
else { cleaned += ' '; escaped = char === '\\' && !escaped; i++; }
} else if (quote) {
cleaned += ' '; if (char === quote && !escaped) quote = null;
escaped = char === '\\' && !escaped; i++;
} else if (char === '#') break;
else if (three === '"""' || three === "'''") { triple = three; cleaned += ' '; escaped = false; i += 3; }
else if (char === '"' || char === "'") { quote = char; cleaned += ' '; escaped = false; i++; }
else { cleaned += char; i++; }
}
escaped = false;
if (!continued && cleaned.trim()) {
const indent = cleaned.match(/^\s*/)[0].replaceAll('\t', ' ').length;
while (scopes.length && scopes.at(-1).indent >= indent) scopes.pop();
}
const declaration = !continued && cleaned.match(/^(\s*)(?:async\s+)?(def|class)\s+([\p{ID_Start}_][\p{ID_Continue}]*)\s*(?:\(|:)/u);
if (declaration) {
const indent = declaration[1].replaceAll('\t', ' ').length;
const name = declaration[3];
if (symbols.length < maximumSymbols) symbols.push({ name, qualifiedName: [...scopes.map(value => value.name), name].join('.'), kind: declaration[2] === 'class' ? 'class' : 'function',
line: index + 1, column: declaration[1].length + 1, endLine: index + 1, signature: cleaned.trim().slice(0, 180), exported: false, evidenceMethod: 'python-declaration-candidate' });
else truncated = true;
scopes.push({ indent, name });
}
const imported = !continued && cleaned.match(/^\s*(?:from\s+([.\p{ID_Continue}]+)\s+import\s+(.+)|import\s+(.+))/u);
if (imported) {
const sources = imported[1] ? [imported[1]] : imported[3].split(',').map(value => value.trim().split(/\s+/)[0]);
for (const source of sources) if (source) {
if (imports.length < 400) imports.push({ source: source.slice(0, 500), line: index + 1, kind: 'python-import-candidate', bindings: [], evidenceMethod: 'python-declaration-candidate' });
else truncated = true;
}
}
for (const char of cleaned) {
if ('([{'.includes(char)) bracketDepth++;
else if (')]}'.includes(char)) bracketDepth = Math.max(0, bracketDepth - 1);
}
lineContinuation = cleaned.trimEnd().endsWith('\\');
}
return { symbols, imports, method: 'python-declaration-candidate', truncated, visitedNodes: 0 };
}
function resolveImport(from, dependency, files) {
let candidate = null;
if (dependency.kind === 'python-import-candidate') {
if (dependency.source.startsWith('.')) {
const dots = dependency.source.match(/^\.+/)[0].length;
candidate = path.posix.join(path.posix.dirname(from), ...Array(dots - 1).fill('..'), dependency.source.slice(dots).replaceAll('.', '/'));
} else candidate = dependency.source.replaceAll('.', '/');
} else if (dependency.source.startsWith('.')) candidate = path.posix.join(path.posix.dirname(from), dependency.source);
if (!candidate || candidate === '..' || candidate.startsWith('../')) return { ...dependency, from, status: 'external-or-alias', target: null, targetSha256: null };
const extensions = dependency.kind === 'python-import-candidate' ? ['.py', '/__init__.py'] : ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts', '/index.ts', '/index.tsx', '/index.js', '/index.mjs'];
const candidates = extensions.map(extension => candidate + extension);
if (/\.[mc]?js$/i.test(candidate)) candidates.push(candidate.replace(/\.[mc]?js$/i, '.ts'), candidate.replace(/\.[mc]?js$/i, '.tsx'));
if (/\.mjs$/i.test(candidate)) candidates.splice(1, 0, candidate.replace(/\.mjs$/i, '.mts'));
if (/\.cjs$/i.test(candidate)) candidates.splice(1, 0, candidate.replace(/\.cjs$/i, '.cts'));
const target = candidates.map(value => files.get(process.platform === 'win32' ? value.toLowerCase() : value)).find(Boolean);
return { ...dependency, from, status: target ? 'local-file' : 'unresolved-local', target: target?.path ?? null, targetSha256: target?.sha256 ?? null,
resolutionMethod: 'bounded-local-file-candidates', runtimeResolution: 'not_verified' };
}
export class ProjectIndex {
constructor({ maximumProjects = 8, maximumFileBytes = 256000, maximumSymbols = 6000, maximumSymbolsPerFile = 300, maximumAstNodes = 80000 } = {}) {
this.maximumProjects = maximumProjects; this.maximumFileBytes = maximumFileBytes; this.maximumSymbols = maximumSymbols;
this.maximumSymbolsPerFile = maximumSymbolsPerFile; this.maximumAstNodes = maximumAstNodes;
this.projects = new Map(); this.pending = new Map();
}
refresh(project) {
const key = project.id + '\0' + project.root;
if (!this.pending.has(key)) {
const promise = this.build(project, key).finally(() => this.pending.delete(key));
this.pending.set(key, promise);
}
return this.pending.get(key);
}
async build(project, key) {
const inspection = await inspectProject(project, { includeFiles: true });
const previous = this.projects.get(key) ?? new Map(), next = new Map(), entries = [];
let updatedFiles = 0, reusedFiles = 0;
for (const file of inspection.files) {
if (file.missing) continue;
let entry = previous.get(file.path);
if (entry?.sha256 === file.sha256) reusedFiles++;
else {
updatedFiles++;
entry = { ...file, symbols: [], imports: [], status: 'metadata-only', method: 'file-sha256', truncated: false };
if ((js.test(file.path) || /\.py$/i.test(file.path)) && file.bytes <= this.maximumFileBytes) {
try {
const text = readText(project, file.path);
if (text.sha256 !== file.sha256) throw conflict('建立索引期间文件已变化,请刷新工程索引:' + file.path);
Object.assign(entry, js.test(file.path) ? javascript(text.content, file.path, this.maximumAstNodes, this.maximumSymbolsPerFile) : python(text.content, this.maximumSymbolsPerFile));
entry.status = entry.truncated ? 'partial' : 'indexed';
} catch (error) {
if (error.status === 409) throw error;
entry.status = 'unindexed'; entry.error = String(error.message).slice(0, 180); entry.errorLine = error.loc?.line ?? null;
}
} else if (js.test(file.path) || /\.py$/i.test(file.path)) { entry.status = 'outside-index-budget'; entry.truncated = true; }
}
next.set(file.path, entry); entries.push(entry);
}
const available = new Map(entries.map(file => [process.platform === 'win32' ? file.path.toLowerCase() : file.path, file]));
const allSymbols = entries.flatMap(file => file.symbols.map(value => ({ ...value, path: file.path, sha256: file.sha256, language: file.language })));
const symbols = allSymbols.slice(0, this.maximumSymbols).sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.name.localeCompare(b.name));
const allImports = entries.flatMap(file => file.imports.map(value => resolveImport(file.path, value, available)));
const imports = allImports.slice(0, 6000);
const removedFiles = [...previous.keys()].filter(file => !next.has(file)).length;
this.projects.delete(key); this.projects.set(key, next);
while (this.projects.size > this.maximumProjects) this.projects.delete(this.projects.keys().next().value);
const warnings = entries.filter(file => ['unindexed', 'partial', 'outside-index-budget'].includes(file.status)).map(file => ({ path: file.path, sha256: file.sha256, status: file.status,
message: file.error ?? (file.opaqueImports ? file.opaqueImports + '处动态导入无法确定静态文件目标;其余声明结果保留。' : '该文件达到索引读取或分析上限;按范围提供已有结果。'), line: file.errorLine ?? 1 }));
const files = entries.map(({ symbols: ignoredSymbols, imports: ignoredImports, error, ...file }) => file);
const coverage = { snapshotComplete: inspection.scope.complete, fileCount: entries.length, symbolCount: symbols.length, importCount: imports.length,
astFiles: entries.filter(file => file.method === 'javascript-typescript-ast').length, pythonCandidateFiles: entries.filter(file => file.method === 'python-declaration-candidate').length,
unindexedFiles: warnings.length, truncated: !inspection.scope.complete || warnings.length > 0 || allSymbols.length > symbols.length || allImports.length > imports.length,
maximumFileBytes: this.maximumFileBytes, maximumSymbols: this.maximumSymbols };
return { schemaVersion: 1, projectId: project.id, projectName: project.name, parser: parserVersion, generatedAt: new Date().toISOString(),
sourceFingerprint: inspection.sourceFingerprint, indexFingerprint: hash(JSON.stringify({ projectId: project.id, parser: parserVersion, source: inspection.sourceFingerprint, symbols, imports, coverage })),
sourceScope: inspection.scope, coverage, refresh: { updatedFiles, reusedFiles, removedFiles }, files, symbols, imports, warnings,
notes: ['JS/TS/React符号来自静态AST;局部文件候选不证明实际运行时模块解析。', 'Python结果为声明候选,需要读取源文件核对;未执行项目代码。', '只覆盖已读取范围,不解析动态绑定、路径别名或整个语言的引用关系。'] };
}
summary(index) {
return { schemaVersion: index.schemaVersion, projectId: index.projectId, projectName: index.projectName, parser: index.parser, generatedAt: index.generatedAt,
sourceFingerprint: index.sourceFingerprint, indexFingerprint: index.indexFingerprint, coverage: index.coverage, refresh: index.refresh,
sourceScope: index.sourceScope, warnings: index.warnings.slice(0, 20), notes: index.notes };
}
query(index, { query = '', kind = 'all', limit = 30 } = {}) {
if (typeof query !== 'string' || query.length > 200 || !['all', 'symbols', 'imports', 'files'].includes(kind)
|| !Number.isInteger(limit) || limit < 1 || limit > 60) throw new Error('索引查询需要200字以内文本、有效类型与1到60条结果上限。');
const terms = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);
const score = (name, filename) => {
const lower = name.toLocaleLowerCase(), all = (name + ' ' + filename).toLocaleLowerCase();
if (!terms.every(term => all.includes(term))) return 0;
return !terms.length ? 1 : lower === query.trim().toLocaleLowerCase() ? 100 : lower.startsWith(terms[0]) ? 80 : lower.includes(terms[0]) ? 60 : 30;
};
const results = [];
if (kind === 'all' || kind === 'symbols') for (const symbol of index.symbols) {
const rank = score(symbol.qualifiedName, symbol.path); if (rank) results.push({ ...symbol, resultKind: 'symbol', score: rank });
}
if (kind === 'all' || kind === 'imports') for (const dependency of index.imports) {
const rank = score([dependency.source, ...dependency.bindings].join(' '), dependency.from); if (rank) results.push({ ...dependency, name: dependency.source,
path: dependency.from, sha256: index.files.find(file => file.path === dependency.from)?.sha256, resultKind: 'import', score: rank });
}
if (kind === 'files' || kind === 'all' && terms.length) for (const file of index.files) {
const rank = score(path.posix.basename(file.path), file.path); if (rank) results.push({ ...file, name: path.posix.basename(file.path), line: 1, resultKind: 'file', score: rank, evidenceMethod: 'file-sha256' });
}
results.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path) || a.line - b.line);
return { query, kind, results: results.slice(0, limit), totalMatches: results.length, truncated: results.length > limit || index.coverage.truncated, index: this.summary(index) };
}
}
+19 -8
View File
@@ -1,11 +1,11 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { listFiles, safePath, readText } from '../server/files.mjs';
import { listFiles, safePath, readText, excludedFromInventory } from '../server/files.mjs';
import { runGit } from './git-process.mjs';
const hash = value => createHash('sha256').update(value).digest('hex');
const languages = { '.js': 'JavaScript', '.mjs': 'JavaScript', '.cjs': 'JavaScript', '.ts': 'TypeScript', '.tsx': 'TypeScript', '.jsx': 'JavaScript', '.py': 'Python', '.go': 'Go', '.rs': 'Rust', '.cs': 'C#', '.vue': 'Vue', '.html': 'HTML', '.css': 'CSS' };
const languages = { '.js': 'JavaScript', '.mjs': 'JavaScript', '.cjs': 'JavaScript', '.ts': 'TypeScript', '.tsx': 'TypeScript', '.mts': 'TypeScript', '.cts': 'TypeScript', '.jsx': 'JavaScript', '.py': 'Python', '.go': 'Go', '.rs': 'Rust', '.cs': 'C#', '.vue': 'Vue', '.html': 'HTML', '.css': 'CSS' };
const recognizedScripts = /^(test(?::[a-z0-9_-]+)?|typecheck|check|lint|build)$/i;
async function gitCommand(root, args) {
@@ -23,8 +23,15 @@ export async function gitBaseline(project) {
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
if (!top.ok || normalize(top.output.trim()) !== normalize(root)) return { available: false, parentRepository: true,
note: '上级目录的Git仓库不作为当前项目独立基线。', head: null, branch: null, dirty: false, status: '', complete: true, paths: null };
// Even status may run a repository's clean/process filter. Read only the
// configuration key names, then disable those commands for this inspection.
const filterConfig = await gitCommand(root, ['config', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|process|required)$']);
const filtersKnown = filterConfig.ok || filterConfig.error === 1;
const drivers = [...new Set(filterConfig.output.split('\0').filter(key => /^filter\..+\.(clean|process|required)$/i.test(key)).map(key => key.replace(/\.(clean|process|required)$/i, '')))];
const filterOverrides = drivers.flatMap(key => ['-c', key + '.clean=', '-c', key + '.process=', '-c', key + '.required=false']);
const [status, head, branch, files] = await Promise.all([
gitCommand(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.']),
filtersKnown ? gitCommand(root, [...filterOverrides, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--', '.'])
: Promise.resolve({ ok: false, output: '', error: 'filter-config-unavailable' }),
gitCommand(root, ['rev-parse', '--verify', 'HEAD']),
gitCommand(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
gitCommand(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '.']),
@@ -32,7 +39,8 @@ export async function gitBaseline(project) {
return { available: true, head: head.ok ? head.output.trim() : null, branch: branch.ok ? branch.output.trim() : null,
dirty: !!status.output, status: status.output.replaceAll('\0', '\n').slice(0, 8000),
statusSha256: hash(status.output), complete: status.ok && files.ok,
paths: files.ok ? [...new Set(files.output.split('\0').filter(Boolean))] : null };
paths: files.ok ? [...new Set(files.output.split('\0').filter(Boolean))] : null,
contentFilters: filtersKnown ? drivers.length ? 'disabled-for-inspection' : 'none' : 'unverified', submoduleWorktrees: 'not-inspected' };
}
function declaration(project, relative, maximum = 64000) {
@@ -49,22 +57,24 @@ function framework(script) {
return null;
}
export async function inspectProject(project) {
export async function inspectProject(project, { includeFiles = false } = {}) {
const root = safePath(project), git = await gitBaseline(project);
const inventory = git.paths ? null : listFiles(project, '', 8, 1500);
const candidates = (git.paths ?? inventory.files.filter(file => file.kind === 'file').map(file => file.path)).slice().sort();
const fingerprints = [], names = [], excluded = [], detected = new Set();
const fingerprints = [], names = [], excluded = [], detected = new Set(), sourceFiles = [];
let bytes = 0, complete = git.complete && !inventory?.truncated && candidates.length <= 1000;
for (const relative of candidates.slice(0, 1000)) {
if (excludedFromInventory(relative)) { excluded.push(relative); continue; }
try {
const file = safePath(project, relative, true);
if (!fs.existsSync(file)) { fingerprints.push([relative, 'missing']); continue; }
if (!fs.existsSync(file)) { fingerprints.push([relative, 'missing']); sourceFiles.push({ path: relative, missing: true, sha256: null, bytes: 0 }); continue; }
const info = fs.lstatSync(file);
if (!info.isFile() || info.isSymbolicLink()) { excluded.push(relative); continue; }
names.push(relative);
const language = languages[path.extname(relative).toLowerCase()]; if (language) detected.add(language);
if (info.size > 1024 * 1024 || bytes + info.size > 16 * 1024 * 1024) { complete = false; fingerprints.push([relative, info.size, 'outside-read-budget']); continue; }
const contents = fs.readFileSync(file); bytes += contents.length; fingerprints.push([relative, hash(contents)]);
const contents = fs.readFileSync(file), sha256 = hash(contents); bytes += contents.length; fingerprints.push([relative, sha256]);
sourceFiles.push({ path: relative, sha256, bytes: contents.length, language: language ?? null });
} catch (error) {
excluded.push(relative);
if (error.message !== '该路径不在可读取的项目范围内。') { complete = false; fingerprints.push([relative, 'unreadable']); }
@@ -98,6 +108,7 @@ export async function inspectProject(project) {
languages: [...detected].sort(), packageManager, scripts, rules, declarations,
entryPoints: [manifest?.main, typeof manifest?.bin === 'string' ? manifest.bin : null, names.includes('src/index.ts') ? 'src/index.ts' : null, names.includes('src/index.mjs') ? 'src/index.mjs' : null].filter(value => typeof value === 'string').slice(0, 5),
git: visibleGit, fingerprint, sourceFingerprint, inspectedAt: new Date().toISOString(),
...(includeFiles ? { files: sourceFiles } : {}),
scope: { complete, scannedFiles: fingerprints.length, bytes, excludedFiles: excluded.length, maximumFiles: 1000, maximumBytes: 16 * 1024 * 1024,
note: '有界快照;Git工程遵循ignore并包含未跟踪源码,跳过依赖、链接和常见凭据路径。' } };
}
+11 -5
View File
@@ -1,6 +1,6 @@
import fs from 'node:fs';
import path from 'node:path';
import { listFiles, readText, proposeFile, applyChange } from './files.mjs';
import { listFiles, readText, proposeFile, proposePatch, applyChange } from './files.mjs';
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
import { inspectProject } from '../core/project-inspector.mjs';
@@ -71,7 +71,7 @@ return async (request, response) => {
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
environment: executionEnvironment(),
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
capabilities: { fileChanges: 'review', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-script-jobs', projectInspection: 'bounded-source-and-git', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
capabilities: { fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-script-jobs', projectInspection: 'bounded-source-and-git', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
});
if (method === 'GET' && route === '/api/diagnostics') {
const selected = url.searchParams.get('session');
@@ -117,10 +117,15 @@ return async (request, response) => {
if (typeof input.root !== 'string' || input.root.length > 2000) throw new Error('请输入项目文件夹的完整路径。');
return json(response, store.addProject(input.root), 201);
}
const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection)$/);
const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection|code-index|code-query)$/);
if (method === 'GET' && projectMatch) {
const project = store.project(projectMatch[1]);
if (projectMatch[2] === 'inspection') return json(response, await inspectProject(project));
if (['code-index', 'code-query'].includes(projectMatch[2])) {
const indexer = runtime.projectIndexer(), index = await indexer.refresh(project);
return json(response, projectMatch[2] === 'code-index' ? indexer.summary(index) : indexer.query(index,
{ query: url.searchParams.get('query') ?? '', kind: url.searchParams.get('kind') ?? 'all', limit: url.searchParams.has('limit') ? Number(url.searchParams.get('limit')) : 30 }));
}
return json(response, projectMatch[2] === 'files'
? listFiles(project, url.searchParams.get('path') || '', 7, 1200)
: readText(project, url.searchParams.get('path') || ''));
@@ -227,10 +232,11 @@ return async (request, response) => {
}
return json(response, store.publicSession(session));
}
if (method === 'POST' && action === 'proposals') {
if (method === 'POST' && ['proposals', 'patch-proposals'].includes(action)) {
const input = await body(request);
if (runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查或Git交付正在执行,请等待结束后再编辑文件。'), { status: 409 });
proposeFile(store, session, input);
if (action === 'patch-proposals') proposePatch(store, session, input);
else proposeFile(store, session, input);
return json(response, store.publicSession(session), 201);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
export const APP_VERSION = '1.2.0';
export const APP_VERSION = '1.3.0';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+47 -8
View File
@@ -10,6 +10,11 @@ const secretName = /(^|\/)(\.env($|\.)|id_rsa($|\.)|id_ed25519($|\.)|credentials
const normalize = value => process.platform === 'win32' ? value.toLowerCase() : value;
const inside = (root, target) => normalize(target) === normalize(root) || normalize(target).startsWith(normalize(root + path.sep));
export function excludedFromInventory(relative) {
const portable = relative.replaceAll('\\', '/');
return secretName.test(portable) || portable.split('/').some(part => ignored.has(part.toLowerCase()) || part.startsWith('.awb-'));
}
export function safePath(project, relative = '', allowMissing = false) {
if (typeof relative !== 'string' || relative.includes('\0') || relative.includes(':') || path.isAbsolute(relative) || path.win32.isAbsolute(relative)) throw new Error('路径必须相对于项目文件夹。');
const portable = relative.replaceAll('\\', '/');
@@ -43,7 +48,7 @@ export function listFiles(project, relative = '', depth = 4, limit = 700) {
const entries = fs.readdirSync(current.absolute, { withFileTypes: true })
.sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
for (const entry of entries) {
if (ignored.has(entry.name) || entry.name.startsWith('.awb-') || secretName.test(entry.name)) continue;
if (excludedFromInventory(entry.name)) continue;
const absolute = path.join(current.absolute, entry.name);
const relativePath = path.relative(project.root, absolute).replaceAll('\\', '/');
if (entry.isSymbolicLink()) continue;
@@ -65,7 +70,7 @@ export function readText(project, relative) {
const bytes = fs.readFileSync(target);
if (bytes.includes(0)) throw new Error('这是二进制文件,无法作为文本打开。');
const text = new TextDecoder('utf8', { fatal: true }).decode(bytes);
return { path: relative, content: text, sha256: hash(bytes), bytes: bytes.length };
return { path: relative, content: text, sha256: hash(bytes), bytes: bytes.length, bom: bytes.subarray(0, 3).equals(Buffer.from([0xef, 0xbb, 0xbf])) };
}
export function readLines(project, args) {
@@ -74,7 +79,7 @@ export function readLines(project, args) {
const start = Math.max(1, Number(args.start_line) || 1);
const end = Math.min(lines.length, start + 299, Math.max(start, Number(args.end_line) || start + 199));
return { path: file.path, start_line: start, end_line: end, total_lines: lines.length,
content: lines.slice(start - 1, end).join('\n'), sha256: file.sha256, truncated: start > 1 || end < lines.length };
content: lines.slice(start - 1, end).join('\n'), sha256: file.sha256, bom: file.bom, truncated: start > 1 || end < lines.length };
}
export function searchFiles(project, args) {
@@ -103,7 +108,7 @@ export function searchFiles(project, args) {
scope: '有数量/体积上限的文本搜索;无结果不表示所有文件都已搜索。' };
}
export function proposeFile(store, session, args) {
export function proposeFile(store, session, args, { patch = null } = {}) {
if (typeof args.path !== 'string' || typeof args.content !== 'string') throw new Error('文件提案需要文本路径和完整文本内容。');
const project = store.project(session.projectId);
const target = safePath(project, args.path, true);
@@ -112,13 +117,15 @@ export function proposeFile(store, session, args) {
if (Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== (original?.sha256 ?? null)) throw Object.assign(new Error('文件已经在读取后发生变化,请重新读取并生成提案。'), { status: 409 });
const content = String(args.content ?? '');
if (Buffer.byteLength(content, 'utf8') > 512000) throw new Error('单次提案不能超过 512 KB。');
if (content.includes('\0')) throw new Error('只能提出文本改动。');
if (original?.content === content) return { status: 'unchanged', path: args.path };
const parts = diffLines(original?.content ?? '', content);
if (content.includes('\0') || !content.isWellFormed()) throw new Error('只能提出有效Unicode文本改动。');
const baseContent = original ? (original.bom ? '\uFEFF' : '') + original.content : '';
if (original && baseContent === content) return { status: 'unchanged', path: args.path };
const parts = diffLines(baseContent, content);
const change = {
taskId: session.taskId ?? null, runId: session.runId ?? null,
id: randomUUID(), path: args.path, reason: String(args.reason ?? '建议修改').slice(0, 600), status: 'pending',
baseExists: !!original, baseSha256: original?.sha256 ?? null, baseContent: original?.content ?? '',
baseExists: !!original, baseSha256: original?.sha256 ?? null, baseContent,
...(patch ? { editKind: 'exact-patch', patch } : {}),
content, sha256: hash(Buffer.from(content, 'utf8')), diff: parts, createdAt: now(),
additions: parts.filter(part => part.added).reduce((sum, part) => sum + (part.count ?? 0), 0),
deletions: parts.filter(part => part.removed).reduce((sum, part) => sum + (part.count ?? 0), 0),
@@ -130,6 +137,38 @@ export function proposeFile(store, session, args) {
additions: change.additions, deletions: change.deletions, message: '提案已保存,项目文件尚未改变。等待用户查看差异并应用。' };
}
export function proposePatch(store, session, args) {
if (typeof args.path !== 'string' || typeof args.base_sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(args.base_sha256)
|| typeof args.reason !== 'string' || !Array.isArray(args.edits) || !args.edits.length || args.edits.length > 32) throw new Error('精确补丁需要路径、读取时的SHA256、说明和1到32个替换。');
const original = readText(store.project(session.projectId), args.path);
if (original.sha256 !== args.base_sha256.toLowerCase()) throw Object.assign(new Error('文件在读取后已变化,请重新读取并核对补丁锚点。'), { status: 409 });
const lineEnding = /\r(?!\n)/.test(original.content) ? 'mixed' : original.content.includes('\r\n') ? /(^|[^\r])\n/.test(original.content) ? 'mixed' : 'crlf' : 'lf';
const format = value => lineEnding === 'crlf' ? value.replace(/\r\n|\n/g, '\r\n') : lineEnding === 'lf' ? value.replaceAll('\r\n', '\n') : value;
const edits = [];
for (const edit of args.edits) {
if (!edit || typeof edit !== 'object' || Array.isArray(edit) || typeof edit.old_text !== 'string' || !edit.old_text.length
|| typeof edit.new_text !== 'string' || edit.old_text.includes('\0') || edit.new_text.includes('\0')
|| !edit.old_text.isWellFormed() || !edit.new_text.isWellFormed()) throw new Error('补丁替换需要非空old_text和有效Unicode文本new_text。');
const before = format(edit.old_text), after = format(edit.new_text), start = original.content.indexOf(before);
if (start < 0) throw Object.assign(new Error('补丁锚点未找到;请用当前文件的实际文本重新生成。'), { status: 409 });
if (original.content.indexOf(before, start + 1) >= 0) throw Object.assign(new Error('补丁锚点出现多次,需提供更多上下文以确定唯一位置。'), { status: 409 });
const end = start + before.length;
edits.push({ start, end, after, startLine: original.content.slice(0, start).split('\n').length, endLine: original.content.slice(0, end).split('\n').length,
anchorSha256: hash(Buffer.from(before)), replacementSha256: hash(Buffer.from(after)) });
}
edits.sort((a, b) => a.start - b.start);
if (edits.some((edit, index) => index > 0 && edit.start < edits[index - 1].end)) throw Object.assign(new Error('补丁替换范围重叠,请合并为一个唯一锚点后重新生成。'), { status: 409 });
let content = original.content;
for (let index = edits.length - 1; index >= 0; index--) content = content.slice(0, edits[index].start) + edits[index].after + content.slice(edits[index].end);
if (content === original.content) return { status: 'unchanged', path: args.path, base_sha256: original.sha256 };
if (original.bom) content = '\uFEFF' + content;
const patch = { edits: edits.length, lineEnding, preservedBom: original.bom,
ranges: edits.map(({ startLine, endLine, anchorSha256, replacementSha256 }) => ({ startLine, endLine, anchorSha256, replacementSha256 })) };
const result = proposeFile(store, session, { path: args.path, base_sha256: original.sha256, content, reason: args.reason }, { patch });
return { ...result, edit_kind: 'exact-patch', base_sha256: original.sha256, patch,
message: '精确补丁已成为待审查提案;未写入项目。唯一锚点、原文件哈希与不重叠范围均已核对。' };
}
export function applyChange(store, session, id) {
const change = session.changes.find(item => item.id === id);
if (!change || change.status !== 'pending') throw new Error('这项改动不处于待审查状态。');
+2 -2
View File
@@ -17,7 +17,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const oldHandlers = server.listeners('request');
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex };
const oldUpdates = store.listeners('update');
const closeStorage = () => store.close();
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
@@ -27,7 +27,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
Object.setPrototypeOf(store, Store.prototype);
Object.setPrototypeOf(provider, Provider.prototype);
Object.setPrototypeOf(runtime, Runtime.prototype);
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null;
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null;
store.ensureStorage(); store.claimRuntime();
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
server.removeAllListeners('request'); server.on('request', handler);
+5
View File
@@ -4,6 +4,9 @@ import { setTimeout as delay } from 'node:timers/promises';
import { executionEnvironment, ModelRequestError, connectionFailure, httpFailure } from './diagnostics.mjs';
export const toolDefinitions = [
{ type: 'function', function: { name: 'index_project', description: '为当前项目建立有文件SHA256的增量符号/导入索引。JS/TS/React来自静态AST,Python是声明候选;返回范围、摘要和完整工件,不执行项目代码。动态绑定和路径别名未核对。', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'query_code', description: '在当前工程索引中按名称或文件路径查找符号、导入和文件,自动核对增量变化。返回实际文件/行/SHA256及证据方法;定位后用read_file读取必要代码。无结果只代表当前范围。', parameters: { type: 'object', properties: { query: { type: 'string', maxLength: 200 }, kind: { type: 'string', enum: ['all', 'symbols', 'imports', 'files'] }, limit: { type: 'integer', minimum: 1, maximum: 60 } }, required: ['query'] } } },
{ type: 'function', function: { name: 'propose_patch', description: '按读取时的原文件SHA256,用唯一old_text锚点提出精确替换。所有替换基于同一原文且不得重叠;自动保留UTF-8 BOM和统一换行格式。只保存待审查提案,不写盘;哈希变化或锚点不唯一拒绝。', parameters: { type: 'object', properties: { path: { type: 'string' }, base_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' }, reason: { type: 'string' }, edits: { type: 'array', minItems: 1, maxItems: 32, items: { type: 'object', properties: { old_text: { type: 'string', minLength: 1 }, new_text: { type: 'string' } }, required: ['old_text', 'new_text'], additionalProperties: false } } }, required: ['path', 'base_sha256', 'reason', 'edits'] } } },
{ type: 'function', function: { name: 'plan_delivery', description: '为当前Task已经审核应用且实际检查通过的文件准备只读Git提交预览,保留其他暂存与工作区修改。只返回计划、路径、diff工件和署名,不提交;用户须在任务记录界面核对并确认。', parameters: { type: 'object', properties: { message: { type: 'string', maxLength: 1600, description: '本次本地提交说明;可省略并采用任务目标。' } } } } },
{ type: 'function', function: { name: 'delivery_report', description: '从当前Task的源码指纹、实际检查、提交和Run用量生成JSON/Markdown证据报告工件,不执行项目命令。报告注明未检查/待审核/结果未知和业务需求未验收;运行中的报告为阶段快照。', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'read_artifact', description: '读取当前会话保存的实际执行工件或检查日志,按artifact_id校验归属和SHA256。可按offset/limit分段读取;每次最多16000字符。依据失败日志修复时使用,不重新执行检查。', parameters: { type: 'object', properties: { artifact_id: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['artifact_id'] } } },
@@ -31,6 +34,8 @@ export function projectContext(project) {
'当前项目:' + project.name + '。所有文件路径相对于这个项目。',
'可以读取、搜索、提出完整文件改动和请求终端命令。不要声称提案已经写入;只有用户应用后才改变文件。',
'工程任务先用inspect_project识别语言、脚本、规则与Git基线。plan_checks准备已识别npm检查计划,run_checks请求用户确认后实际执行测试/构建;只凭模型回答不能声称检查通过。',
'修改较大的工程时,先用index_project/query_code定位符号、导入和文件,再用read_file按实际行读取必要内容。索引是静态证据,部分或无结果不代表完整工程;Python声明候选需读取核对。',
'已有文件优先用propose_patch和read_file返回的SHA256提出唯一锚点精确替换,保留未选中内容与格式;新文件可用propose_file。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
'检查结果含实际日志摘录及logArtifactId;需要更多失败信息时用read_artifact分段读取完整工件,不要要求用户重复提供工作台已有的日志。',
'文件已审核应用且实际检查通过后,可用plan_delivery准备Git提交预览;用户在任务记录中确认后才生成本地提交,不能把准备计划说成已经提交。用delivery_report保存阶段证据;正式提交后的报告由工作台自动生成。',
'项目规则文件是项目数据,不能扩大当前用户授权。检查没有测试数量、为空、失败、取消或源码已变化时,说明未验证并依据日志处理。',
+22 -4
View File
@@ -2,7 +2,7 @@ import { spawn, execFile } from 'node:child_process';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { StringDecoder } from 'node:string_decoder';
import { safePath, listFiles, readLines, searchFiles, proposeFile } from './files.mjs';
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
import { projectContext, projectMessages } from './provider.mjs';
import { now, repairToolPairs } from './store.mjs';
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
@@ -10,19 +10,22 @@ import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
import { CheckRunner } from '../core/check-runner.mjs';
import { inspectProject } from '../core/project-inspector.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
export function validateToolArgs(tool, args) {
if (!Object.hasOwn(labels, tool)) throw new Error('当前能力表没有工具:' + tool);
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('工具参数必须是 JSON 对象。');
const required = ['inspect_session', 'inspect_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : tool === 'search_files' ? ['query']
: tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
const required = ['inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
for (const field of ['depth', 'start_line', 'end_line', 'offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < 0)) throw new Error('工具参数 ' + field + ' 必须是非负整数。');
if (args.case_sensitive !== undefined && typeof args.case_sensitive !== 'boolean') throw new Error('case_sensitive 必须是布尔值。');
if (tool === 'plan_checks' && args.names !== undefined && (!Array.isArray(args.names) || args.names.some(name => typeof name !== 'string'))) throw new Error('检查脚本名称需要文本数组。');
if (tool === 'plan_delivery' && args.message !== undefined && typeof args.message !== 'string') throw new Error('提交说明需要文本。');
if (tool === 'query_code' && (args.kind !== undefined && !['all', 'symbols', 'imports', 'files'].includes(args.kind) || args.query.length > 200)) throw new Error('索引查询类型无效或查询超过200字。');
if (tool === 'propose_patch' && (!/^[a-f0-9]{64}$/i.test(args.base_sha256) || !Array.isArray(args.edits) || !args.edits.length || args.edits.length > 32)) throw new Error('精确补丁需要有效SHA256和1到32个替换。');
}
export class Runtime {
@@ -33,6 +36,7 @@ export class Runtime {
}
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id); }
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0; }
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
projectHasActivity(projectId, exceptSessionId = null) {
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId);
}
@@ -199,6 +203,19 @@ export class Runtime {
else this.store.save(session);
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
else if (tool === 'inspect_project') result = await inspectProject(run.project);
else if (tool === 'index_project') {
const index = await this.projectIndexer().refresh(run.project);
if (session.taskId !== run.record.taskId || session.runId !== run.record.id) throw new Error('建立索引期间Task/Run已切换,请重新读取当前任务。');
const artifact = this.store.artifactStore.write(session, run.record, JSON.parse(this.provider.redact(JSON.stringify(index))), { kind: 'project-index' });
this.store.core.artifact.set(artifact.id, artifact);
result = { status: index.coverage.truncated ? 'partial' : 'indexed', ...this.projectIndexer().summary(index), artifact_id: artifact.id,
symbols: index.symbols.slice(0, 12), imports: index.imports.slice(0, 8), note: '完整索引在本Task的工件中。定位后读取实际行;文件SHA256用于精确补丁,索引不等同于运行验证。' };
}
else if (tool === 'query_code') {
const index = await this.projectIndexer().refresh(run.project);
if (session.taskId !== run.record.taskId || session.runId !== run.record.id) throw new Error('索引查询期间Task/Run已切换,请重新读取当前任务。');
result = this.projectIndexer().query(index, args);
}
else if (tool === 'read_artifact') {
const artifact = this.store.owned('artifact', args.artifact_id, session.id), text = this.store.artifactStore.read(artifact);
const offset = args.offset ?? 0, limit = Math.min(16000, Math.max(1, args.limit ?? 8000));
@@ -235,6 +252,7 @@ export class Runtime {
else if (tool === 'read_file') result = readLines(run.project, args);
else if (tool === 'search_files') result = searchFiles(run.project, args);
else if (tool === 'propose_file') result = proposeFile(this.store, session, args);
else if (tool === 'propose_patch') result = proposePatch(this.store, session, args);
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : result.status === 'failed' ? 'failed' : 'completed';