feat: add project index and exact patch review
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
|
||||
本仓库专注AI编程与能力研究工作台。其他项目不纳入本项目计划或代码。用户确定的研究对象为Codex、Claude Code、Cursor、DeepSeek Harness、WorkBuddy及DSH-purge;目标是将有证据的机制独立开发成自有Harness内置能力。
|
||||
|
||||
1.0.0是已保存的基础里程碑;1.1.0已交付M1可靠内核,1.2.0增加当前Task的本地Git交付及证据报告。后续实现与真实工程验收见docs/PRODUCT-PLAN.md、docs/CAPABILITIES.md和docs/RESEARCH-ROADMAP.md。计划中的能力不能写成已经实现。
|
||||
1.0.0是已保存的基础里程碑;1.1.0已交付M1可靠内核,1.2.0增加当前Task的本地Git交付及证据报告,1.3.0增加有界工程索引与精确补丁。后续实现与真实工程验收见docs/PRODUCT-PLAN.md、docs/CAPABILITIES.md和docs/RESEARCH-ROADMAP.md。计划中的能力不能写成已经实现。
|
||||
|
||||
## 研究与来源
|
||||
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
# Agent Workbench 更新记录
|
||||
|
||||
## 1.3.0 · 2026-10-29
|
||||
|
||||
- 增加当前项目的工程索引:JS/TS/React静态声明与导入、Python声明候选、逐文件SHA256增量复用及覆盖范围;新增index_project/query_code模型工具和Task所属索引工件。
|
||||
- 右侧「索引」查询符号、导入与文件,结果定位实际文件行;项目切换忽略旧响应,文件变化后提示刷新并核对新位置,桌面与390px可用。
|
||||
- 新增propose_patch:按原文件SHA256、唯一锚点和不重叠范围产生审核提案,保留BOM、统一LF/CRLF与未选择原字节,拒绝旧基线、模糊锚点和无效Unicode。
|
||||
- 长文件差异定位首处实际改动,审查页展示精确替换数与格式;标签保持单行,索引失败有明确项目归属和重试入口。
|
||||
- 工程只读Git检查先禁用配置的clean/process过滤脚本并跳过子模块工作区;依赖、常见凭据与链接沿统一清单规则排除。
|
||||
- 完整112项行为/API/实际退出恢复检查通过。新索引界面8组流程通过;发行、真实模型与全部界面的最终证据汇总到[验收记录](docs/VALIDATION.md)。
|
||||
|
||||
## 1.2.0 · 2026-10-29
|
||||
|
||||
- 任务记录增加本地Git提交预览、实际文件diff、署名和说明;确认只提交当前Task已应用且检查有效的文件,保留其他暂存与工作区改动。
|
||||
|
||||
@@ -11,3 +11,5 @@
|
||||
桌面三栏,较窄屏幕收起右侧检视区;移动宽度改为对话、项目和检视标签切换。按钮、错误与空状态使用用户能操作的动作名称。减少动态效果,尊重 reduced-motion。
|
||||
|
||||
模型未连接时明确显示离线演示;演示使用固定脚本和真实本地工具流程,不能表现为真实模型推理。
|
||||
|
||||
1.3.0索引与文件/差异/轨迹/任务共用右侧五标签。结果按实际声明、路径、行和文件指纹组织,候选和部分范围直接标明;数字来自当前索引,输入保持单一焦点。文件和差异仅滚动各自容器,长文件审查直接定位首处改动;390px保持标签单行与指纹换行。
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# 本地 Agent 工作台
|
||||
|
||||
Agent Workbench 1.2.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。任务与运行记录、实际工程检查、文件审查、本地Git提交及交付报告现在可以在同一个Task中完成。
|
||||
Agent Workbench 1.3.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。工程索引、代码定位、精确补丁、实际检查、文件审查、本地Git提交及交付报告可以在同一个Task中完成。
|
||||
|
||||
每次运行保留模型与预算、已完成工具和日志工件。检查通过需要实际退出码、测试数量和对应源码快照;应用改动后可点击「继续检查与交付」,沿用原目标进行测试与修复。提交前查看实际文件、diff、署名和检查结果,确认后生成本地提交及可下载的JSON/Markdown报告。版本改动见 [CHANGELOG](CHANGELOG.md),本轮验收范围见 [QA-1.2](docs/QA-1.2.md)。
|
||||
每次运行保留模型与预算、已完成工具和日志工件。索引结果可打开实际文件行,精确补丁按文件SHA256和唯一锚点保留未修改内容与格式。检查通过需要实际退出码、测试数量和对应源码快照;应用改动后可点击「继续检查与交付」,沿用原目标进行测试与修复。提交前查看实际文件、diff、署名和检查结果,确认后生成本地提交及可下载的JSON/Markdown报告。版本改动见 [CHANGELOG](CHANGELOG.md),能力范围见[索引与补丁契约](docs/CODE-INDEX-AND-PATCHES.md)。
|
||||
|
||||
## 后续产品与能力建设
|
||||
|
||||
@@ -13,7 +13,7 @@ Agent Workbench 1.2.0 将 Claude Code 与 Cursor 的机制研究整合为独立
|
||||
- [研究路线](docs/RESEARCH-ROADMAP.md)与[目标来源登记](research/targets.json):版本、来源、SDK限制及未解决问题。
|
||||
- [本地Git流程](docs/GIT-WORKFLOW.md)与[项目执行规范](AGENTS.md):源码仓库已建立,main基线`bac87da`、标签`v1.0.0-baseline`;后续按独立小步检查并及时提交。
|
||||
|
||||
1.2.0实现有界工程识别、Node/npm检查job、当前Task已审核文件的Git交付及证据报告。增量工程索引、任务依赖图、patch/ChangeSet、隔离worktree、多worker、外部引擎、REA执行和桌面/手机配对按后续阶段建设。
|
||||
1.3.0实现有界JS/TS/React静态索引、Python声明候选和精确补丁,沿用Node/npm检查job、当前Task已审核文件的Git交付及证据报告。任务依赖图、语义引用、ChangeSet、隔离worktree、多类工程检查器、外部引擎、REA执行和桌面/手机配对继续按后续阶段建设。
|
||||
|
||||
## 直接运行
|
||||
|
||||
@@ -29,6 +29,7 @@ Windows x64 便携包自带 Node.js 24.22.1和npm。解压后双击 `Start-Workb
|
||||
6. 遇到请求失败,点击错误卡片的「查看运行诊断」。可在同一会话提问,助手通过本地 `inspect_session` 核对错误来源、近期工具和文件实际状态。
|
||||
7. 点击「查看任务记录」查看目标、各轮运行、累计用量与工件。准备工程检查后,核对npm脚本再执行;查看实际测试数量与日志。应用全部提案后,用「继续检查与交付」继续同一目标。
|
||||
8. 检查通过后,在任务记录中「预览Git提交」,核对已审核路径、差异、署名和说明,再「确认创建本地提交」。工作台保留其他暂存与工作区改动,结果未知时提供「核对提交结果」;报告可直接查看和下载。Git需要本机安装,具体范围见[Git交付契约](docs/GIT-DELIVERY.md)。
|
||||
9. 右侧「索引」按函数、类、路径或导入查找代码,结果可定位原文件行。文件在索引后变化时打开当前内容并提示刷新;Python声明候选与局部模块文件候选显示各自范围。长文件差异可直接「定位首处改动」。
|
||||
|
||||
## 模型连接
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Agent Workbench 能力目标与验收矩阵
|
||||
|
||||
日期:2026-10-29。1.0.0为基础里程碑,1.1.0实现M1,1.2.0实现首个内置Git交付切片。下表保留1.0.0缺口与完整产品目标;每项完成范围以实际验证记录为准。
|
||||
日期:2026-10-29。1.0.0为基础里程碑,1.1.0实现M1,1.2.0实现首个内置Git交付切片,1.3.0增加工程索引和精确补丁。下表保留1.0.0缺口与完整产品目标;每项完成范围以实际验证记录为准。
|
||||
|
||||
总体方案见 [PRODUCT-PLAN.md](PRODUCT-PLAN.md),研究问题与来源见 [RESEARCH-ROADMAP.md](RESEARCH-ROADMAP.md)。
|
||||
|
||||
@@ -28,6 +28,13 @@
|
||||
- C11/C24:源码与Git基线分别验证,检查日志完整性和测试数量仍须满足;92项完整行为检查、9组桌面/390px交付界面通过。
|
||||
- C08、多类工程与完整M2/M6成功率仍待后续实施。范围见[QA-1.2](QA-1.2.md)与[Git交付契约](GIT-DELIVERY.md)。
|
||||
|
||||
### 1.3.0 M2工程定位与精确补丁切片
|
||||
|
||||
- C03/C04:JS/TS/React静态AST声明与导入、Python声明候选、逐文件SHA256增量复用、依赖候选重算与当前项目绑定;工具工件有Task/Run归属。暂不提供编译器级引用、路径别名或动态模块解析。
|
||||
- C08:唯一锚点/原SHA256的局部补丁、BOM和LF/CRLF保留、旧基线与重叠/重复锚点拒绝;继续由逐文件审查/备份流程应用,完整多文件ChangeSet仍待实现。
|
||||
- C07/C23:只读Git检查禁用配置过滤脚本,统一清单排除依赖/凭据/链接;索引范围、格式、Unicode、项目切换、原文件行定位、工件恢复和API契约有实际检查。
|
||||
- 完整112项行为/API/实际退出检查通过,新索引UI8组通过;源码/发行与真实模型工程验收以[验收记录](VALIDATION.md)为准。详见[索引与补丁契约](CODE-INDEX-AND-PATCHES.md)。React/Python真实工程交付、worktree和完整M2/M6仍继续实施。
|
||||
|
||||
| ID / 能力 | 当前1.0.0基础与缺口 | 后续产品目标 | 参考问题 / 模块 / 阶段 | 必须看到的验收证据 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| C01 需求与任务规划 | 有对话和有限步数工具循环,没有任务依赖图 | 固定目标、约束和完成标准;拆任务、判断依赖、接收追加要求与重规划 | CX-1、WB-1 / tasks / M1–M2 | 追加要求后仍保留原目标;任务完成由验收条件决定 |
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# 工程索引与精确补丁契约 · 1.3.0
|
||||
|
||||
本切片将工程声明定位与局部编辑接入工作台已有的任务、审核、实际检查和Git交付。来源机制映射到C03/C04/C08;自有实现、契约检查与真实模型结果分别保存。
|
||||
|
||||
## 索引范围与依据
|
||||
|
||||
`ProjectIndex`为当前项目重新核对有界文件快照,并按每个文件SHA256复用或更新分析结果。导入目标候选每次重算,新增/删除文件也会改变结果。缓存最多8个项目,项目ID和真实根目录共同隔离;目前每次仍核对文件内容,没有后台文件监听或语义向量检索。
|
||||
|
||||
JS/TS/JSX/TSX/MTS/CTS采用MIT许可的`@babel/parser 7.29.11`,登记函数、类、方法、顶层变量、TS类型/接口/枚举与静态导出;导入、重导出、字面动态导入、字面require调用和TS import-equals来自语法节点。相对路径只比较当前范围的文件候选,包含JS→TS和MJS/CJS→MTS/CTS;有实际文件时优先该文件。候选附目标SHA256和`runtimeResolution: not_verified`,路径别名、调用绑定和动态参数仍需进一步分析。
|
||||
|
||||
Python采用移除注释/字符串体并识别缩进及声明的有界候选定位。结果明确显示`python-declaration-candidate`,保留行、名称、文件SHA256,使用前读取实际源码。没有执行Python代码,也没有进行Python编译器、完整引用或类型分析。
|
||||
|
||||
快照最多1000个候选文件/16MB;常规读取单文件最多1MB,声明分析最多256000字节,每文件300个符号/80000个AST节点,结果最多6000个符号与6000个导入。损坏文本、解析错误、读取/分析超限、无法确定静态目标的导入和不完整快照都显示范围。无匹配只表示当前查询范围;Go/Rust/Vue等暂保留文件指纹。
|
||||
|
||||
Git工程遵循ignore,常见依赖/生成目录、常见凭据、链接和子模块工作区排除。Git status可能运行配置的clean/process脚本,因此先只读取配置键名并在本次状态查询禁用这些脚本;未能确认配置时不声称基线完整。运行命令仍走原有独立确认流程。
|
||||
|
||||
## 使用与工件
|
||||
|
||||
- `index_project`:摘要、覆盖范围、增量计数和有限示例;完整索引成为当前Task/Run的SHA256工件。
|
||||
- `query_code`:按名称/路径查找all/symbols/imports/files,查询最多200字,结果1–60条,附实际文件、行、SHA256和依据。
|
||||
- 项目只读API:`GET /api/projects/:id/code-index`、`GET /api/projects/:id/code-query`。单独浏览索引无需创建Task;模型执行保存任务工件。
|
||||
- 右侧「索引」可查找并打开原文件行。打开时重新读取文件;SHA256已变化时显示当前内容和刷新提示,清除旧行高亮。滚动限于代码容器,切换项目忽略旧请求返回。
|
||||
|
||||
## 精确编辑
|
||||
|
||||
`propose_patch`及`POST /api/sessions/:id/patch-proposals`要求现有文件路径、读取时64位SHA256、说明和1–32个`old_text`/`new_text`替换。非空锚点须在同一原文中恰好出现一次,全部范围不得重叠;输入顺序不会改变匹配基线。重叠、重复、未找到、过期SHA256、NUL和无效Unicode拒绝,空改动不产生提案。
|
||||
|
||||
统一LF/CRLF按原文件格式匹配与生成替换;混合换行按原文严格匹配。UTF-8 BOM单独保留。提案记录基线和结果SHA256、格式、替换数、原行范围及锚点/替换SHA256,保留未选中内容。新文件继续使用完整文本提案。
|
||||
|
||||
提案只保存到工作台,不写入工程;用户查看差异后应用。应用前再次核对实际文件基线,备份原字节并写入建议内容,冲突保留外部修改。精确补丁沿用逐文件状态,不提供多文件原子应用、改名/删除或worktree合并。长文件差异可定位首处实际改动,应用后的检查/提交仍由已有Task契约负责。
|
||||
|
||||
## 验证与剩余工作
|
||||
|
||||
源码检查覆盖实际AST行与导出、Python候选/多行签名、项目隔离、增量更新/删除与目标重算、MTS/CTS候选、过滤脚本不执行、损坏/大文件范围、BOM/CRLF/混合格式、唯一/重叠锚点、Unicode、冲突、Task工件/API与恢复。完整112项通过,见[m2-index-tests-validation.json](m2-index-tests-validation.json)。
|
||||
|
||||
界面验收包含独立浏览、长文件行定位、旧SHA、延迟项目请求、Python/导入依据、实际审查应用、390px及失败重试。真实模型使用四模块封存验收,源码增加420行受保护说明,其中两个模块有BOM/CRLF,要求仅定位正文并提交精确补丁;结果随[VALIDATION](VALIDATION.md)保存。完整多类工程、ChangeSet/worktree、引擎适配、桌面端/手机配对继续按产品计划开发。
|
||||
@@ -144,8 +144,8 @@ Purge的包声明Apache-2.0,另有商业许可联系说明;Harness声明MIT
|
||||
|
||||
## 9. 下一轮最先执行的三个开发切片
|
||||
|
||||
1. 定义Task/Run/Step/Event/Tool/Artifact契约,将现有模型循环的状态从UI会话表述中拆出;先保留兼容层。
|
||||
2. 抽象Storage,给JSON→SQLite迁移和崩溃/重放边界建立可验证样本;同时生成首批真实工程任务基准。
|
||||
3. 实现工程识别、TestRunner检查计划/planId/jobId/结果及Git基线,完成一个“跨文件修改→实际测试→修复→diff→提交”的最小工程交付。
|
||||
1. 1.1.0的Task/Run/工件/SQLite及1.2.0的检查/Git/report切片已交付;1.3.0继续完成工程索引和精确补丁,按独立包与长文件真实模型验收发布。
|
||||
2. 下一批实现多文件ChangeSet与可恢复应用、任务工作区/worktree隔离,再完成React/TypeScript及Python专用检查与封存任务;当前单Node样本不计为三类工程完成。
|
||||
3. 在写入/取消/事件归属边界稳定后按M3接入REA及Codex/DeepSeek EngineAdapter的契约探针,分别固定Harness/Purge/profile版本,再比较真实同题工程收益。桌面Electron与手机配对网关复用同一执行宿主,按M5推进。
|
||||
|
||||
这些切片优先复用已验证的文件范围、基线备份、UTF-8、取消与诊断能力。研究结论每次至少绑定一个实现模块、一个契约检查和一个用户场景,按实际失败分类持续调整顺序。
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# 1.3.0工程索引与精确补丁验收
|
||||
|
||||
本轮交付当前项目的JS/TS/React静态声明与导入索引、Python声明候选、原SHA256与唯一锚点的精确补丁,接入实际工程检查、审核、Git和报告。完整多文件ChangeSet、React/Python专用检查器、隔离worktree与引擎/桌面/手机配对继续按产品计划实施。
|
||||
|
||||
| 用户可见行为 | 实际检查 | 已验证结果 |
|
||||
| --- | --- | --- |
|
||||
| 工程声明与导入能定位真实源码 | AST行/导出、Python候选、MTS/CTS、动态目标范围 | 112项完整行为/API/进程恢复全部通过 |
|
||||
| 索引增量更新且项目隔离 | 原SHA256复用、增加/删除目标重算、缓存隔离 | 文件变化返回新符号与目标,不污染旧证据 |
|
||||
| 只读工程检查保持只读范围 | Git过滤脚本探针、ignore/依赖/凭据/链接 | 未执行配置的clean脚本,Git索引字节保留 |
|
||||
| 精确补丁先审核再写入 | BOM/LF/CRLF/混合格式、Unicode、唯一/重叠锚点 | 提案不写入;冲突保留owner字节,应用备份原字节 |
|
||||
| 结果打开实际文件行 | 181→184行、旧SHA不高亮、容器内滚动 | 输入和顶部保持可见 |
|
||||
| 切换项目及失败处理 | 延迟旧响应、部分覆盖、失败重试 | 旧响应忽略,旧结果禁用并可恢复 |
|
||||
| 长文件审查与手机宽度 | 首处实际修改、五标签、指纹换行、390px | 新索引8组及原有35组界面通过 |
|
||||
|
||||
基础10/诊断9/任务7/Git交付9/索引8共43组界面全部通过,页面/请求异常为零。结构化结果分别为[m2-index-tests-validation.json](m2-index-tests-validation.json)、[基础](m2-index-basic-ui-validation.json)、[诊断](m2-index-diagnostics-ui-validation.json)、[任务](m2-index-execution-ui-validation.json)、[Git交付](m2-index-delivery-ui-validation.json)和[索引](m2-index-index-ui-validation.json)。
|
||||
|
||||
桌面及390px的索引、文件行与精确差异截图已目视核对,见[screenshots](screenshots/1.3-index-desktop.png)。初始两项Windows Node HTTP连接重置已独立复验并采用有限QA请求独立连接,完整112项最终回归全部通过;没有自动重试副作用请求。
|
||||
|
||||
便携包、独立源码安装/构建、原进程升级与真实模型长文件精确交付的最终结果汇总到[VALIDATION](VALIDATION.md)。真实模型样本增加420行受保护说明及两种BOM/换行格式,要求用索引定位正文、仅读取必要源码并提出精确补丁,沿原Task完成14项测试、Git和报告;不由单个样本推断完整M2/M6成功率。
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"success": true,
|
||||
"url": "http://127.0.0.1:52944",
|
||||
"browser": "Microsoft Edge 156.0.4314.42",
|
||||
"date": "2026-10-29T09:53:02.565Z",
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\ui-79c795e4-ec52-40a9-aebf-aee109426e81\\ui-project",
|
||||
"viewports": [
|
||||
1440,
|
||||
780,
|
||||
390
|
||||
],
|
||||
"passed": [
|
||||
"project selection and real file preview",
|
||||
"real command consent, execution and stale snapshot rejection",
|
||||
"diff review and verified file application",
|
||||
"manual editor creates a reviewable proposal",
|
||||
"file responses stay with the current selection",
|
||||
"denial, session selection, reload, stale response rejection and export",
|
||||
"project inventory responses cannot replace another project",
|
||||
"780 and 390 px: project drawer, file, diff and trace controls, no page overflow",
|
||||
"unified and detailed research reports render",
|
||||
"model list, ephemeral key, compatible fixture tool loop and return to offline mode"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"modelValidation": "controlled local HTTP fixture; no real model",
|
||||
"version": "1.3.0"
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.3.0",
|
||||
"testedAt": "2026-10-29T09:54:11.002Z",
|
||||
"browser": "156.0.4314.42",
|
||||
"passed": [
|
||||
"actual failing tests and four source proposals retain the original project and task",
|
||||
"reviewed changes continue the same Task through 14 real tests and model-prepared Git review",
|
||||
"review shows actual paths, diffs, tests, author and policy; cancelling leaves Git unchanged",
|
||||
"an index change after confirmation preview refuses the stale job and preserves both staged owners",
|
||||
"390px confirmation keeps file hashes, diffs and actions inside the modal",
|
||||
"double confirmation creates one four-file commit, retains owner bytes and publishes report with completion",
|
||||
"report viewing and Markdown/JSON downloads preserve verified artifact bytes and truthful acceptance limits",
|
||||
"mobile report preview closes cleanly and keeps the task input fixed",
|
||||
"unknown Git results block new submission and the explicit reconcile action restores the existing commit"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\delivery-ui-5786ccd4-434a-41d2-939f-ce6269a39070\\四模块交付工程",
|
||||
"projectId": "dd123252-c383-4f92-a26d-4c2a599cc0e8",
|
||||
"sessionId": "a64178fc-1939-4a40-ab52-a76492deff11",
|
||||
"taskId": "9c146230-85e9-47e9-a496-bb9d184db3a6",
|
||||
"commit": "ad61b9ee20b163c8ed706d9b6dc7b86b7b45500f",
|
||||
"recoveryCommit": "ab1afdcb8f17774d1a20246e24a48ea1fbba054d",
|
||||
"testCounts": {
|
||||
"baselineFailed": 13,
|
||||
"passed": 14
|
||||
},
|
||||
"model": "controlled local HTTP fixture",
|
||||
"confirmations": 2
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.3.0",
|
||||
"url": "http://127.0.0.1:52944",
|
||||
"date": "2026-10-29T09:53:18.523Z",
|
||||
"passed": [
|
||||
"model response validation checks the tentative connection before saving",
|
||||
"a model failure after successful tools shows source, attempts and local runtime diagnosis",
|
||||
"explicit retry preserves the completed tool result without replaying the task",
|
||||
"an error question receives the actual session diagnosis and formatted answer",
|
||||
"review state exposes the review action and prevents application during a running request",
|
||||
"approved Unicode commands execute in the declared shell and retain Chinese output",
|
||||
"authentication errors do not retry and error/diagnostic controls fit a 390 px viewport",
|
||||
"stop cancels pending retry and clears running model state",
|
||||
"a transient service failure recovers within the bounded retry policy"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"modelValidation": "controlled local HTTP fixture; actual configured model is verified separately"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"success": true,
|
||||
"version": "1.3.0",
|
||||
"testedAt": "2026-10-29T09:53:39.177Z",
|
||||
"browser": "156.0.4314.42",
|
||||
"passed": [
|
||||
"model-selected checks wait for approval and display actual counted results",
|
||||
"verified artifact preview shows the real check log and hash",
|
||||
"changed source invalidates old checks and manual confirmation runs the new plan",
|
||||
"390px task drawer, log preview, close controls and fixed composer remain operable",
|
||||
"reconnection synchronizes missed session changes in other projects",
|
||||
"budget controls pause before tools and preserve the goal across recorded runs",
|
||||
"applied proposals continue the original task into actual engineering verification"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\execution-ui-f35e1e33-7a89-4726-8752-7c490d6f50d8\\project",
|
||||
"model": "controlled local HTTP fixture"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"checkedAt": "2026-10-29T09:54:16.255Z",
|
||||
"version": "1.3.0",
|
||||
"passed": [
|
||||
"工程索引可独立于任务使用,实际覆盖范围与损坏文件显示明确",
|
||||
"真实AST查询打开原文件第181行并仅滚动代码容器,输入区和顶部保持可见",
|
||||
"查询词保留;过期SHA不高亮旧位置,增量刷新后正确定位第184行",
|
||||
"切换项目时延迟返回的旧索引不覆盖新项目结果",
|
||||
"Python候选、字符串误报排除和局部导入文件候选保留真实证据标签",
|
||||
"两处唯一锚点成为待审核提案,真实界面应用后BOM/CRLF和未选择原字节保留",
|
||||
"390px索引查询、范围和完整指纹可读且无横向溢出,实际文件行定位通过",
|
||||
"索引刷新失败保留归属和解释,旧结果禁用并可重试恢复"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\index-ui-8c1879b7-0cae-4317-abf3-0d8a08053ab4",
|
||||
"primaryProjectId": "aac0e660-995b-45b8-80f9-9d4600016791",
|
||||
"otherProjectId": "02811d53-9145-446d-bf0e-057b4bca3af9"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"version": "1.3.0",
|
||||
"testedAt": "2026-10-29T09:52:45.109Z",
|
||||
"platform": "win32",
|
||||
"node": "v24.22.1",
|
||||
"command": "npm test",
|
||||
"tests": 112,
|
||||
"passed": 112,
|
||||
"failed": 0,
|
||||
"skipped": 0,
|
||||
"cancelled": 0,
|
||||
"durationMs": 147134.9173,
|
||||
"logSha256": "382482cce71e278acda6d64d40793164840ec076ba80db9db26a1a2b090e5622",
|
||||
"initialRun": {
|
||||
"tests": 110,
|
||||
"passed": 108,
|
||||
"failed": 2,
|
||||
"reason": "Windows Node HTTP ECONNRESET in restart/event fixtures; isolated repro passed 2/2, finite QA requests use independent connections and record response phase, without replay."
|
||||
},
|
||||
"scope": "Behavior, API, index/patch contracts, real process recovery and consecutive in-place upgrade; no M2/M6 completion-rate claim."
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 184 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 114 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 182 KiB |
@@ -139,3 +139,9 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
|
||||
- 修复后15项恢复/升级专项和92项完整回归全部通过;基础10/诊断9/任务7/交付9组界面均通过且0页面/请求异常。新QA宿主4321/PID38288独立于4318原进程。
|
||||
- Git与报告完成状态必须同次保存;实际模型验收从旧的验收器自行提交改为确认工作台的持久Git job,并校验报告SHA256、commit和原owner索引。源码包验收脚本采用独立解压、离线npm安装和构建逐字节比较。
|
||||
- 便携验收不能使用固定4320端口:残留1.1.0QA会被启动器视为可复用。验收器改用随机空闲端口,并在操作/停止之前证明自己拥有该data/PID/发行路径;失败记录保留。
|
||||
|
||||
## 1.3.0工程索引与精确补丁
|
||||
|
||||
- 首轮14项专项10通过/4失败,实际暴露默认箭头导出/TS声明函数遗漏、Python候选跨字符串及旧作用域误报、Git文件清单中的依赖目录未排除和Unicode半字符可被补丁选择。已分别补齐AST导出、跨行词法状态、统一清单排除与有效Unicode约束;待复验。
|
||||
- 精确补丁BOM/CRLF、LF与混合换行、32个编辑上限、同一原文的唯一锚点和重叠/过期冲突已通过首轮检查;未应用前不写入,实际应用备份原字节。
|
||||
- 合成Git工程证实普通status及当前inspectProject会运行配置的clean过滤器。已先只读取得过滤器键名,在本次status禁用clean/process/required,并跳过子模块工作区;无法确认配置时保持未完成基线,避免以只读索引隐式执行项目代码。专项同时核对Git索引原字节,待复验。
|
||||
|
||||
Generated
+3
-6
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.0",
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
"diff": "^8.0.2",
|
||||
"lucide-react": "^0.548.0",
|
||||
"react": "^19.2.0",
|
||||
@@ -170,7 +171,6 @@
|
||||
"version": "7.29.11",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz",
|
||||
"integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
@@ -180,7 +180,6 @@
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
|
||||
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
@@ -214,7 +213,6 @@
|
||||
"version": "7.29.11",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.11.tgz",
|
||||
"integrity": "sha512-OZ6+oaK7GMyg3IfCpj8JOmn8n+w2rJbDT0LLfVDTLb1ZFeKDh3AiNELgCMUw175IJHSkLl74hG0M0VLsvx+gag==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.11"
|
||||
@@ -296,7 +294,6 @@
|
||||
"version": "7.29.11",
|
||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz",
|
||||
"integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/helper-string-parser": "^7.29.11",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
|
||||
@@ -14,6 +14,7 @@
|
||||
"package": "node scripts/package.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
"diff": "^8.0.2",
|
||||
"lucide-react": "^0.548.0",
|
||||
"react": "^19.2.0",
|
||||
|
||||
+15
@@ -110,3 +110,18 @@
|
||||
- 后续继续1.3.0工程符号索引与带SHA256的精确补丁,按实际定位、格式保留、冲突和项目归属验证推进。
|
||||
- 最终1.2.0包使用独立带时间戳目录,原已验证发行不覆盖。最终2116份便携/254份源码清单及ZIP CRC/SHA通过;54份核心/测试/声明与独立源码验收逐字节一致,6份构建文件一致。原PID23080已切换最终1.2.0实现,连接与全部当时会话保持。
|
||||
- 1.3.0索引实现将复用已安装@babel/parser 7.29.11(MIT),提升为明确运行依赖;JS/TS/React静态AST证据与Python声明定位分开标明,动态绑定不假定已经解析。
|
||||
|
||||
## 2026-10-29 1.3.0继续全量开发
|
||||
|
||||
- 接续5ec85b0之后的索引/精确补丁未提交实现,读取AGENTS和既有计划。正式4318保持1.2.0/PID23080,源码1.3.0尚未通过功能验收或部署。
|
||||
- 本轮先核对AST导出/定位、Python候选范围、增量依赖变化与项目隔离;补丁核对BOM/换行/唯一锚点/重叠/冲突,再接入第五个索引检视页与真实文件行定位。
|
||||
- 新读取时PowerShell不展开rg的src/client/*.css路径参数,改为rg -g '*.css' src/client;输出过长采用文件段落与独立预算,不把截断内容当完整核对。
|
||||
- 14项首轮专项10通过/4失败,修正AST默认导出、Python候选词法/作用域、依赖清单与Unicode补丁边界后14/14通过;另补真实Git clean执行探针,修正只读检查后1/1通过。
|
||||
- 第五个索引检视页、结果类型/范围/增量统计、原文件SHA256核对及容器内行定位已接入;精确补丁在审查页展示替换数与格式。1.3.0源码完整构建通过,随后做API/Runtime与实际桌面/390px流程。
|
||||
- 索引/补丁/API/模型工具与工件恢复18/18专项通过;Python与随附Python均缺Playwright模块,继续使用仓库已安装并经过验收的Node Playwright测试,未为此安装或替换环境。webapp-testing的with_server --help已核对。
|
||||
- 首轮索引UI8/8通过,零页面/请求异常。桌面与390px截图显示实际文件/行/候选依据;目视发现带待审查数量时标签会折行、长文件差异初始只见说明行,正在改善标签和首处实际改动定位。
|
||||
- 首轮完整110项108通过/2失败,最终错误是Windows Node HTTP连接ECONNRESET,并非已确认的任务等待超时;两项实际重启/SSE专项独立复跑2/2通过。沿用既有升级验收的独立连接策略,将QA有限API请求设为Connection:close并记录请求阶段,不重试副作用请求;随后完整复验。
|
||||
- 标签保持单行和长差异首处改动定位已完成,索引UI再次8/8通过。目视发现sticky差异标题需背景以免文字穿透,已修正;补充Python多行签名及TS import-equals/MTS/CTS和动态导入范围专项。
|
||||
- 新增两项声明/候选专项2/2通过,重建后完整112/112通过,零失败/跳过/取消。验收记录已保存;本轮QA有限请求不自动重试任何副作用。
|
||||
- 已关闭本轮旧QA11548并以新编译源码/独立数据启动38436,原4318/PID23080保持。接续全部基础/诊断/任务/Git/索引UI,之后保存实现本地提交并验证发行与真实模型精确补丁样本。
|
||||
- 新源码独立QA完整基础10/诊断9/任务7/Git9/索引8共43组全部通过,零页面/请求异常。索引/行定位/首处差异及390px截图已核对,证据复制到docs;开始保存实现本地Git提交并生成独立1.3.0包。
|
||||
|
||||
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
|
||||
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
|
||||
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
|
||||
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
|
||||
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
|
||||
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
|
||||
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
|
||||
let protocol, socket, enabledHere = false, paused = false;
|
||||
const breakpoints = [];
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { chromium, expect } from 'playwright/test';
|
||||
|
||||
const url = process.env.AGENT_WORKBENCH_URL;
|
||||
if (!url || !/^http:\/\/127\.0\.0\.1:(?!4318(?:\/|$))\d+\/?$/.test(url)) throw new Error('Set AGENT_WORKBENCH_URL to an independent local QA service.');
|
||||
const root = path.resolve('.qa', 'index-ui-' + randomUUID()), primaryRoot = path.join(root, 'index-ui-project'), otherRoot = path.join(root, 'index-ui-other');
|
||||
fs.mkdirSync(path.join(primaryRoot, 'src'), { recursive: true }); fs.mkdirSync(otherRoot, { recursive: true }); fs.mkdirSync('.qa/screenshots', { recursive: true });
|
||||
const sourcePath = path.join(primaryRoot, 'src', 'invoice.ts');
|
||||
const banner = Array.from({ length: 180 }, (_, line) => '// 保留的项目说明 ' + (line + 1) + ' · 原文🙂').join('\r\n') + '\r\n';
|
||||
const original = '\uFEFF' + banner + 'export function total(amount: number, discount: number) { return amount - discount; }\r\nexport const currency = "CNY";\r\n';
|
||||
fs.writeFileSync(sourcePath, original);
|
||||
fs.writeFileSync(path.join(primaryRoot, 'src', 'Card.tsx'), 'import { total } from "./invoice.js";\nexport const Card = () => <p>{total(10, 2)}</p>;\n');
|
||||
fs.writeFileSync(path.join(primaryRoot, 'legacy.py'), '# def FakeComment():\n"""def FakeString():"""\ndef repair():\n pass\n');
|
||||
fs.writeFileSync(path.join(primaryRoot, 'broken.js'), 'export function unfinished(');
|
||||
fs.writeFileSync(path.join(primaryRoot, 'package.json'), JSON.stringify({ name: 'index-ui-project', type: 'module' }));
|
||||
fs.writeFileSync(path.join(otherRoot, 'other.ts'), 'export function otherOnly() { return true; }\n');
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
assert.equal(bootstrap.version, '1.3.0'); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
|
||||
const api = async (route, input) => {
|
||||
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) });
|
||||
const value = await response.json(); assert.ok(response.ok, value.error); return value;
|
||||
};
|
||||
const primary = await api('/projects', { root: primaryRoot }), other = await api('/projects', { root: otherRoot });
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }), page = await context.newPage();
|
||||
const passed = [], pageErrors = [], requestFailures = []; let heldRelease;
|
||||
page.on('pageerror', cause => pageErrors.push(cause.message));
|
||||
page.on('requestfailed', request => { if (request.resourceType() !== 'eventsource') requestFailures.push(request.url() + ': ' + request.failure()?.errorText); });
|
||||
const panel = () => page.getByLabel('工程索引', { exact: true });
|
||||
const indexTab = () => page.locator('.inspector-tabs').getByRole('button', { name: '索引', exact: true });
|
||||
const screenshot = name => page.screenshot({ path: '.qa/screenshots/' + name + '.png', scale: 'css' });
|
||||
async function find(query, kind = 'symbols') {
|
||||
await panel().getByLabel('索引查询').fill(query);
|
||||
if (await panel().getByLabel('索引结果类型').inputValue() !== kind) await panel().getByLabel('索引结果类型').selectOption(kind);
|
||||
else await panel().getByRole('button', { name: '查找', exact: true }).click();
|
||||
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
|
||||
await expect(panel().getByRole('status')).toContainText('“' + query + '”');
|
||||
}
|
||||
async function checkPosition(line) {
|
||||
await expect(page.locator('.code-line-target')).toHaveAttribute('data-line', String(line));
|
||||
await expect.poll(() => page.evaluate(() => {
|
||||
const line = document.querySelector('.code-line-target').getBoundingClientRect(), area = document.querySelector('.code-view').getBoundingClientRect();
|
||||
return line.top >= area.top && line.bottom <= area.bottom;
|
||||
})).toBe(true);
|
||||
const layout = await page.evaluate(() => ({ scrollY, header: document.querySelector('.work-header').getBoundingClientRect().top,
|
||||
composerBottom: document.querySelector('.composer-wrap').getBoundingClientRect().bottom, height: innerHeight }));
|
||||
assert.equal(layout.scrollY, 0); assert.ok(layout.header >= 0); assert.ok(layout.composerBottom <= layout.height + 1);
|
||||
}
|
||||
try {
|
||||
await page.goto(url); await page.waitForLoadState('networkidle');
|
||||
await page.getByLabel('当前项目', { exact: true }).selectOption(primary.id);
|
||||
fs.writeFileSync(path.join(root, 'initial-dom.html'), await page.content());
|
||||
assert.ok((await page.locator('.inspector-tabs button').allTextContents()).some(value => value === '索引'));
|
||||
await indexTab().click(); await expect(panel()).toBeVisible();
|
||||
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
|
||||
await expect(panel()).toContainText('当前项目 · index-ui-project'); await expect(panel()).toContainText('部分结果');
|
||||
assert.equal((await api('/sessions')).filter(value => value.projectId === primary.id).length, 0);
|
||||
passed.push('工程索引可独立于任务使用,实际覆盖范围与损坏文件显示明确');
|
||||
|
||||
await find('total'); await expect(panel().locator('.index-result-location')).toContainText(':181');
|
||||
await screenshot('m2-index-desktop');
|
||||
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 181 行 total', exact: true }).click();
|
||||
await checkPosition(181); await screenshot('m2-index-desktop-line');
|
||||
passed.push('真实AST查询打开原文件第181行并仅滚动代码容器,输入区和顶部保持可见');
|
||||
|
||||
await indexTab().click(); await expect(panel().getByLabel('索引查询')).toHaveValue('total');
|
||||
fs.writeFileSync(sourcePath, '\uFEFF// 新说明1\r\n// 新说明2\r\n// 新说明3\r\n' + original.slice(1));
|
||||
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 181 行 total', exact: true }).click();
|
||||
await expect(page.getByText('文件在索引后已变化,已打开当前内容。请回到索引刷新后重新定位。', { exact: true })).toBeVisible();
|
||||
await expect(page.locator('.code-line-target')).toHaveCount(0); await expect(page.locator('.code-view')).toContainText('新说明3');
|
||||
await indexTab().click(); await panel().getByRole('button', { name: '刷新工程索引' }).click();
|
||||
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
|
||||
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 184 行 total', exact: true }).click(); await checkPosition(184);
|
||||
passed.push('查询词保留;过期SHA不高亮旧位置,增量刷新后正确定位第184行');
|
||||
|
||||
await indexTab().click(); let held = false;
|
||||
const gate = new Promise(resolve => { heldRelease = resolve; });
|
||||
const routePattern = new RegExp('/api/projects/' + primary.id + '/code-query\\?');
|
||||
await page.route(routePattern, async route => { const response = await route.fetch(); held = true; await gate; await route.fulfill({ response }); });
|
||||
await panel().getByRole('button', { name: '刷新工程索引' }).click(); await expect.poll(() => held).toBe(true);
|
||||
await page.getByLabel('当前项目', { exact: true }).selectOption(other.id);
|
||||
await expect(panel()).toContainText('当前项目 · index-ui-other'); await expect(panel()).toContainText('otherOnly');
|
||||
heldRelease(); await page.waitForTimeout(300); await page.unroute(routePattern);
|
||||
await expect(panel()).not.toContainText('src/invoice.ts'); await expect(panel()).toContainText('otherOnly');
|
||||
passed.push('切换项目时延迟返回的旧索引不覆盖新项目结果');
|
||||
|
||||
await page.getByLabel('当前项目', { exact: true }).selectOption(primary.id);
|
||||
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled(); await find('repair');
|
||||
await expect(panel()).toContainText('Python 候选 · 需读源码核对'); await expect(panel().locator('.index-result-location')).toContainText('legacy.py');
|
||||
await find('FakeString'); await expect(panel().getByText('当前范围没有匹配', { exact: true })).toBeVisible();
|
||||
await find('invoice.js', 'imports'); await expect(panel()).toContainText('文件候选 → src/invoice.ts');
|
||||
await panel().getByText('查看索引范围与依据', { exact: true }).click(); await expect(panel()).toContainText('不证明实际运行时模块解析');
|
||||
passed.push('Python候选、字符串误报排除和局部导入文件候选保留真实证据标签');
|
||||
|
||||
const current = await api('/projects/' + primary.id + '/file?path=src%2Finvoice.ts'), before = fs.readFileSync(sourcePath);
|
||||
const session = await api('/sessions', { projectId: primary.id });
|
||||
const proposed = await api('/sessions/' + session.id + '/patch-proposals', { path: 'src/invoice.ts', base_sha256: current.sha256, reason: '精确调整金额与币种', edits: [
|
||||
{ old_text: 'return amount - discount;', new_text: 'return Math.max(0, amount - discount);' }, { old_text: 'currency = "CNY"', new_text: 'currency = "USD"' }] });
|
||||
assert.deepEqual(fs.readFileSync(sourcePath), before);
|
||||
await page.evaluate(id => localStorage.setItem('awb-session', id), session.id); await page.reload(); await page.waitForLoadState('networkidle');
|
||||
await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
|
||||
await expect(page.locator('.patch-detail')).toHaveText('精确补丁 · 2 处替换 · 保留 CRLF 换行 · 保留 BOM');
|
||||
await expect.poll(() => page.evaluate(() => {
|
||||
const row = document.querySelector('.diff-removed').getBoundingClientRect(), area = document.querySelector('.diff-view').getBoundingClientRect();
|
||||
return row.top > area.top && row.bottom <= area.bottom;
|
||||
})).toBe(true);
|
||||
await page.evaluate(() => { document.querySelector('.diff-view').scrollTop = 0; });
|
||||
await page.getByRole('button', { name: '定位首处改动', exact: true }).click();
|
||||
await expect.poll(() => page.evaluate(() => document.querySelector('.diff-view').scrollTop > 0)).toBe(true);
|
||||
await screenshot('m2-index-patch-desktop'); await page.getByRole('button', { name: '应用这项改动', exact: true }).click();
|
||||
await expect(page.getByText('这项改动已写入项目。', { exact: true })).toBeVisible();
|
||||
const expected = before.toString('utf8').replace('return amount - discount;', 'return Math.max(0, amount - discount);').replace('currency = "CNY"', 'currency = "USD"');
|
||||
assert.deepEqual(fs.readFileSync(sourcePath), Buffer.from(expected)); assert.equal((await api('/sessions/' + proposed.id)).changes[0].status, 'applied');
|
||||
passed.push('两处唯一锚点成为待审核提案,真实界面应用后BOM/CRLF和未选择原字节保留');
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 }); await expect(page.getByRole('button', { name: '查看文件', exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: '查看文件', exact: true }).click(); await indexTab().click();
|
||||
await panel().getByRole('button', { name: '刷新工程索引' }).click(); await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
|
||||
await find('total'); await panel().getByText('查看索引范围与依据', { exact: true }).click();
|
||||
const bounds = await page.evaluate(() => ({ page: document.documentElement.scrollWidth <= innerWidth,
|
||||
panel: document.querySelector('.code-index-panel').scrollWidth <= document.querySelector('.code-index-panel').clientWidth + 1,
|
||||
tabs: document.querySelector('.inspector-tabs').scrollWidth <= document.querySelector('.inspector-tabs').clientWidth + 1 }));
|
||||
assert.deepEqual(bounds, { page: true, panel: true, tabs: true }); await screenshot('m2-index-mobile');
|
||||
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 184 行 total', exact: true }).click(); await checkPosition(184); await screenshot('m2-index-mobile-line');
|
||||
passed.push('390px索引查询、范围和完整指纹可读且无横向溢出,实际文件行定位通过');
|
||||
|
||||
await indexTab().click(); const errorPattern = new RegExp('/api/projects/' + primary.id + '/code-query\\?'); let failNext = true;
|
||||
await page.route(errorPattern, route => { if (failNext) { failNext = false; return route.fulfill({ status: 409, contentType: 'application/json', body: JSON.stringify({ error: '建立索引期间文件已变化,请刷新工程索引。' }) }); } return route.continue(); });
|
||||
await panel().getByRole('button', { name: '刷新工程索引' }).click(); await expect(panel().getByRole('alert')).toContainText('索引未刷新');
|
||||
await expect(panel().locator('.index-result').first()).toBeDisabled(); await panel().getByRole('button', { name: '重试索引' }).click();
|
||||
await expect(panel().getByRole('alert')).toHaveCount(0); await expect(panel().locator('.index-result').first()).toBeEnabled(); await page.unroute(errorPattern);
|
||||
passed.push('索引刷新失败保留归属和解释,旧结果禁用并可重试恢复');
|
||||
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
|
||||
const result = { checkedAt: new Date().toISOString(), version: bootstrap.version, passed, pageErrors, requestFailures, root, primaryProjectId: primary.id, otherProjectId: other.id };
|
||||
fs.writeFileSync('.qa/index-ui-result.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
|
||||
} catch (cause) {
|
||||
fs.writeFileSync('.qa/index-ui-failure.json', JSON.stringify({ passed, pageErrors, requestFailures, message: cause.message, root }, null, 2));
|
||||
await screenshot('m2-index-failure').catch(() => {}); throw cause;
|
||||
} finally { heldRelease?.(); await browser.close(); }
|
||||
@@ -8,32 +8,43 @@ import { APP_VERSION } from '../src/server/diagnostics.mjs';
|
||||
// Operates only on a fresh synthetic project. The configured model remains in
|
||||
// the running host; bootstrap contains an API session token, never its model key.
|
||||
const workspace = process.cwd();
|
||||
const precision = process.argv.includes('--precision');
|
||||
const bannerLines = 420;
|
||||
const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4318';
|
||||
const origin = new URL(url);
|
||||
assert.equal(origin.hostname, '127.0.0.1'); assert.equal(origin.protocol, 'http:');
|
||||
const bootstrap = await (await fetch(origin.origin + '/api/bootstrap')).json();
|
||||
const bootstrap = await (await fetch(origin.origin + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
|
||||
assert.equal(bootstrap.version, APP_VERSION); assert.equal(bootstrap.config.mode, 'compatible');
|
||||
assert.ok(bootstrap.config.model, 'Configure a model on the running Workbench first.');
|
||||
const api = async (route, input) => {
|
||||
const response = await fetch(origin.origin + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token },
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' },
|
||||
...(input === undefined ? {} : { body: JSON.stringify(input) }), signal: AbortSignal.timeout(15000) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw Object.assign(new Error(result.error ?? 'Workbench HTTP ' + response.status), { status: response.status });
|
||||
return result;
|
||||
};
|
||||
|
||||
const caseRoot = path.resolve('.qa', 'live-delivery-' + randomUUID());
|
||||
const projectRoot = path.join(caseRoot, '交付报告工程');
|
||||
const caseRoot = path.resolve('.qa', (precision ? 'live-precision-' : 'live-delivery-') + randomUUID());
|
||||
const projectRoot = path.join(caseRoot, precision ? '精确补丁交付工程' : '交付报告工程');
|
||||
const allowed = ['src/normalize.mjs', 'src/summary.mjs', 'src/render.mjs', 'src/cli.mjs'];
|
||||
const scripts = { test: 'node --test test/*.test.mjs', build: 'node scripts/build.mjs' };
|
||||
fs.mkdirSync(caseRoot, { recursive: true });
|
||||
fs.cpSync(path.join(workspace, 'benchmarks/node-delivery-v1/baseline'), projectRoot, { recursive: true });
|
||||
const sourcePrefixes = {}, sourceFormats = {};
|
||||
if (precision) for (const file of allowed) {
|
||||
const target = path.join(projectRoot, file), body = fs.readFileSync(target, 'utf8').replaceAll('\r\n', '\n');
|
||||
const bom = ['src/normalize.mjs', 'src/cli.mjs'].includes(file), ending = bom ? '\r\n' : '\n';
|
||||
const banner = Array.from({ length: bannerLines }, (_, line) => '// 保留工程说明 ' + (line + 1) + ' · ' + file + ' · 原文🙂').join(ending) + ending;
|
||||
const prefix = (bom ? '\uFEFF' : '') + banner;
|
||||
sourcePrefixes[file] = Buffer.from(prefix); sourceFormats[file] = { bom, lineEnding: bom ? 'crlf' : 'lf', firstSourceLine: bannerLines + 1 };
|
||||
fs.writeFileSync(target, prefix + body.replaceAll('\n', ending));
|
||||
}
|
||||
fs.writeFileSync(path.join(projectRoot, '.gitignore'), 'dist/\n');
|
||||
fs.writeFileSync(path.join(projectRoot, 'OWNER-NOTES.md'), '# Owner notes\nBaseline owner content.\n');
|
||||
fs.writeFileSync(path.join(projectRoot, 'OWNER-STAGED.txt'), 'Baseline staged owner content.\n');
|
||||
const git = args => execFileSync('git', ['-c', 'core.autocrlf=false', '-c', 'user.name=Agent Workbench QA', '-c', 'user.email=qa@workbench.local', '-C', projectRoot, ...args], { encoding: 'utf8', windowsHide: true });
|
||||
git(['init', '--initial-branch=main']); git(['add', '.']); git(['commit', '-m', 'test: seal delivery-report acceptance baseline']);
|
||||
git(['init', '--initial-branch=main']); git(['config', 'core.autocrlf', 'false']); git(['add', '.']); git(['commit', '-m', 'test: seal delivery-report acceptance baseline']);
|
||||
const baselineCommit = git(['rev-parse', 'HEAD']).trim();
|
||||
fs.appendFileSync(path.join(projectRoot, 'OWNER-NOTES.md'), 'Existing owner edit: ' + randomUUID() + '\n');
|
||||
fs.writeFileSync(path.join(projectRoot, 'UNTRACKED-OWNER.txt'), 'Existing untracked owner file: ' + randomUUID() + '\n');
|
||||
@@ -49,6 +60,12 @@ const assertProtected = () => {
|
||||
for (const [file, hash] of Object.entries(protectedHashes)) assert.equal(sha(file), hash, 'Protected input changed: ' + file);
|
||||
assert.equal(git(['diff', '--', 'OWNER-NOTES.md']), ownerDiff, 'Existing owner edits changed.');
|
||||
assert.equal(git(['diff', '--cached', '--', 'OWNER-STAGED.txt']), ownerStagedDiff, 'Existing owner stage changed.');
|
||||
if (precision) for (const file of allowed) {
|
||||
const bytes = fs.readFileSync(path.join(projectRoot, file)); assert.deepEqual(bytes.subarray(0, sourcePrefixes[file].length), sourcePrefixes[file], 'Protected source banner changed: ' + file);
|
||||
const text = bytes.toString('utf8');
|
||||
if (sourceFormats[file].lineEnding === 'crlf') assert.ok(!/(^|[^\r])\n/.test(text), 'CRLF changed: ' + file);
|
||||
else assert.ok(!text.includes('\r'), 'LF changed: ' + file);
|
||||
}
|
||||
};
|
||||
const project = await api('/projects', { root: projectRoot });
|
||||
const session = await api('/sessions', { projectId: project.id });
|
||||
@@ -56,14 +73,17 @@ const started = Date.now(), applied = [], decisions = [], reviewLimit = 4;
|
||||
let reviewedRounds = 0, state, succeeded = false, lastProgress = '', originalTaskId;
|
||||
const saveEvidence = result => {
|
||||
fs.writeFileSync(path.join(caseRoot, 'result.json'), JSON.stringify(result, null, 2));
|
||||
fs.writeFileSync(path.join(workspace, '.qa/live-delivery-validation.json'), JSON.stringify(result, null, 2));
|
||||
fs.writeFileSync(path.join(workspace, precision ? '.qa/live-precision-validation.json' : '.qa/live-delivery-validation.json'), JSON.stringify(result, null, 2));
|
||||
};
|
||||
|
||||
try {
|
||||
await api('/sessions/' + session.id + '/messages', { content:
|
||||
'完成当前 Delivery Report 工程,严格实现 README.md 的七项要求。先用 inspect_project 识别工程,' +
|
||||
'再用 plan_checks 选择 test/build,并用 run_checks 实际运行封存输入,取得失败的测试和日志。' +
|
||||
'依据实际失败读取有关文件,使用 read_artifact 进一步核对失败日志。只能用 propose_file 修改 src/normalize.mjs、src/summary.mjs、src/render.mjs、src/cli.mjs;' +
|
||||
'依据实际失败读取有关文件,使用 read_artifact 进一步核对失败日志。' + (precision
|
||||
? '先用 index_project 建立工程索引,再用 query_code 的 symbols/imports 结果定位源码,特别是CLI入口的实际导入行。每个源码模块前420行都是须原字节保留的说明;用 read_file 指定start_line至少421的必要行范围,取得最新SHA256。已有源码只能用 propose_patch 及该SHA256、唯一old_text锚点精确修改;保留BOM及原LF/CRLF,不使用 propose_file,不读整个说明块。'
|
||||
: '只能用 propose_file 修改 src/normalize.mjs、src/summary.mjs、src/render.mjs、src/cli.mjs;') +
|
||||
'允许修改的源码仅为 src/normalize.mjs、src/summary.mjs、src/render.mjs、src/cli.mjs。' +
|
||||
'测试、fixtures、构建脚本、package.json、README 和 OWNER 文件必须保留。四模块都需修复,不能修改验收来通过。' +
|
||||
'本工程没有第三方依赖,不用安装。不要使用 run_command、不要自己提交Git;本轮终端仅通过已识别的npm检查计划运行。' +
|
||||
'提案等待审查应用,随后继续同一目标并实际重新运行 test/build,依据日志修复直至通过。检查通过后用 plan_delivery 准备本Task的四文件本地Git预览,等待用户独立确认;最后用中文报告实际测试数量、构建结果和改动。' });
|
||||
@@ -80,6 +100,12 @@ try {
|
||||
lastProgress = progress;
|
||||
}
|
||||
for (const proposal of state.changes.filter(change => ['pending', 'conflict'].includes(change.status))) assert.ok(allowed.includes(proposal.path), 'Out-of-scope proposal: ' + proposal.path);
|
||||
if (precision) {
|
||||
assert.ok(!state.events.some(event => event.tool === 'propose_file'), 'Precision sample must use exact patch proposals only.');
|
||||
for (const event of state.events.filter(event => event.tool === 'read_file' && allowed.includes(event.input?.path))) {
|
||||
assert.ok(event.input.start_line >= bannerLines + 1, 'Source reads must target indexed implementation lines: ' + event.input.path);
|
||||
}
|
||||
}
|
||||
for (const approval of state.approvals.filter(item => item.status === 'pending')) {
|
||||
const plan = state.execution.plans?.find(item => item.id === approval.checkPlanId);
|
||||
const allow = !!plan && plan.taskId === originalTaskId && plan.checks.length > 0 && plan.checks.length <= 2
|
||||
@@ -103,9 +129,15 @@ try {
|
||||
for (const proposal of pending) {
|
||||
assert.equal(sha(proposal.path), proposal.baseSha256, 'Proposal baseline changed.');
|
||||
assert.notEqual(proposal.content.trim(), '', 'Empty source proposal.');
|
||||
if (precision) {
|
||||
assert.equal(proposal.editKind, 'exact-patch'); assert.ok(proposal.patch.edits > 0);
|
||||
assert.ok(proposal.patch.ranges.every(range => range.startLine >= bannerLines + 1), 'Patch must not select the preserved banner.');
|
||||
assert.deepEqual(Buffer.from(proposal.content).subarray(0, sourcePrefixes[proposal.path].length), sourcePrefixes[proposal.path]);
|
||||
assert.equal(proposal.patch.preservedBom, sourceFormats[proposal.path].bom); assert.equal(proposal.patch.lineEnding, sourceFormats[proposal.path].lineEnding);
|
||||
}
|
||||
const beforeApply = await api('/sessions/' + session.id + '/changes/' + proposal.id + '/apply', {});
|
||||
assert.equal(sha(proposal.path), proposal.sha256, 'Applied bytes do not match the reviewed proposal.');
|
||||
applied.push({ id: proposal.id, path: proposal.path, sha256: proposal.sha256, taskId: originalTaskId });
|
||||
applied.push({ id: proposal.id, path: proposal.path, sha256: proposal.sha256, taskId: originalTaskId, ...(precision ? { editKind: proposal.editKind, patch: proposal.patch } : {}) });
|
||||
assert.ok(beforeApply.session ?? beforeApply, 'No apply response.'); assertProtected();
|
||||
}
|
||||
await api('/sessions/' + session.id + '/continue-reviewed', {}); continue;
|
||||
@@ -120,6 +152,16 @@ try {
|
||||
assert.deepEqual([...new Set(applied.map(item => item.path))].sort(), [...allowed].sort());
|
||||
for (const file of allowed) assert.notEqual(sha(file), beforeSources[file], 'Module was not repaired: ' + file);
|
||||
assertProtected();
|
||||
let precisionEvidence = null;
|
||||
if (precision) {
|
||||
const indexed = state.events.filter(event => event.tool === 'index_project' && event.phase === 'completed'), queries = state.events.filter(event => event.tool === 'query_code' && event.phase === 'completed');
|
||||
assert.ok(indexed.length > 0 && queries.length > 0, 'The model must use project index and symbol/import queries.');
|
||||
const sourceReads = state.events.filter(event => event.tool === 'read_file' && event.phase === 'completed' && allowed.includes(event.input?.path));
|
||||
for (const file of allowed) assert.ok(sourceReads.some(event => event.input.path === file), 'Each patched source must be read by its actual lines: ' + file);
|
||||
precisionEvidence = { bannerLines, formats: sourceFormats, preservedPrefixes: Object.fromEntries(allowed.map(file => [file, { bytes: sourcePrefixes[file].length, sha256: createHash('sha256').update(sourcePrefixes[file]).digest('hex') }])),
|
||||
indexCalls: indexed.length, queryCalls: queries.length, sourceReads: sourceReads.map(event => ({ path: event.input.path, startLine: event.input.start_line, endLine: event.input.end_line ?? null, runId: event.runId })),
|
||||
exactPatchesOnly: true, sourcePrefixesPreserved: true, formatPreserved: true };
|
||||
}
|
||||
const built = spawnSync(process.execPath, [path.join(projectRoot, 'dist/cli.mjs'), path.join(projectRoot, 'fixtures/tasks.json'), '--json'], { cwd: projectRoot, encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(built.status, 0); assert.equal(built.stderr, '');
|
||||
assert.deepEqual(JSON.parse(built.stdout), { total: 4, counts: { todo: 0, doing: 1, done: 2, blocked: 1 }, completedPercent: 50, remainingMinutes: 50 });
|
||||
@@ -165,14 +207,14 @@ try {
|
||||
do { log = await api('/artifacts/' + result.logArtifactId + '?session=' + session.id + '&offset=' + offset + '&limit=16000'); text += log.content; offset += log.content.length; } while (log.truncated && log.content.length);
|
||||
fs.writeFileSync(path.join(caseRoot, job.id + '-' + result.name + '.log'), text);
|
||||
}
|
||||
const result = { success: true, version: bootstrap.version, testedAt: new Date().toISOString(), model: bootstrap.config.model,
|
||||
const result = { success: true, version: bootstrap.version, mode: precision ? 'indexed-exact-patch' : 'whole-file', testedAt: new Date().toISOString(), model: bootstrap.config.model,
|
||||
projectRoot, projectId: project.id, sessionId: session.id, taskId: originalTaskId, baselineCommit, deliveredCommit, deliveryPlan, deliveryJob,
|
||||
elapsedSeconds: Math.round((Date.now() - started) / 1000), runs: state.execution.runs.length, reviewRounds: reviewedRounds, applied,
|
||||
protectedHashes, ownerEditsPreserved: true, ownerStagePreserved: true, reportStatus: report.status, reportPath: path.join(caseRoot, 'delivery-report.md'), buildOutput: JSON.parse(built.stdout), usage: state.execution.task.usage,
|
||||
protectedHashes, ownerEditsPreserved: true, ownerStagePreserved: true, precisionEvidence, reportStatus: report.status, reportPath: path.join(caseRoot, 'delivery-report.md'), buildOutput: JSON.parse(built.stdout), usage: state.execution.task.usage,
|
||||
checks: state.execution.checks, decisions, diffPath: path.join(caseRoot, 'reviewed-changes.diff'), sessionPath: path.join(caseRoot, 'session.json'),
|
||||
credentialsHandling: 'Calls use the running host model configuration; no model key was read, copied or saved.',
|
||||
intervention: 'Verifier approved only sealed npm scripts, reviewed and applied four source proposals, and confirmed an owned Git preview through the Workbench API. Implementation came from the configured model; the Workbench generated and verified the commit and evidence reports.',
|
||||
scope: 'One synthetic Node engineering sample; does not establish M2 or M6 delivery success rates.' };
|
||||
scope: 'One synthetic Node engineering sample; does not establish all M2 engineering classes, ChangeSet/worktree or M6 delivery success rates.' };
|
||||
saveEvidence(result); succeeded = true;
|
||||
console.log(JSON.stringify({ success: true, model: result.model, testsPassed: 14, buildPassed: true, deliveredCommit, elapsedSeconds: result.elapsedSeconds, reviewRounds: reviewedRounds, projectRoot, sessionId: session.id }, null, 2));
|
||||
} catch (error) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createHash } from 'node:crypto';
|
||||
const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4318';
|
||||
const sessionId = process.env.AGENT_WORKBENCH_SESSION || '569c9457-d399-46e6-b53e-4b1fdbb02109';
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
assert.ok(['1.0.0', '1.1.0', '1.2.0'].includes(bootstrap.version));
|
||||
assert.ok(['1.0.0', '1.1.0', '1.2.0', '1.3.0'].includes(bootstrap.version));
|
||||
assert.equal(bootstrap.config.mode, 'compatible');
|
||||
assert.ok(bootstrap.config.hasKey, 'The existing in-memory connection must be present.');
|
||||
const api = async (route, input) => {
|
||||
|
||||
+29
-12
@@ -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>
|
||||
|
||||
@@ -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}}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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
@@ -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 }
|
||||
|
||||
@@ -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) };
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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,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
@@ -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('这项改动不处于待审查状态。');
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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';
|
||||
|
||||
+4
-4
@@ -156,7 +156,7 @@
|
||||
|
||||
目标:补齐从工程结构/符号定位实际文件、按原文件SHA256提出精确改动的能力,减少对完整文件替换及长上下文的依赖。先完善确定性索引、来源与编辑契约,再接入模型工具和桌面/390px界面;多文件ChangeSet、Python检查器、worktree及M3引擎研究继续按完整路线推进。
|
||||
|
||||
1. [in_progress] JS/TS/React采用已安装MIT @babel/parser 7.29.11的静态符号/导入索引,逐文件SHA256增量复用并绑定项目;Python只登记有明确范围的声明定位。
|
||||
2. [pending] 带原文件SHA256、唯一锚点与不重叠范围的精确补丁提案;保留原有字节格式和审核/备份/冲突检查。
|
||||
3. [pending] 索引/查询/补丁模型工具、只读API及任务面板;结果能定位实际文件/行并核对来源。
|
||||
4. [pending] 相关契约、实际模型工程样本、桌面/390px回归、独立发行与本地Git提交。
|
||||
1. [complete] JS/TS/React采用已安装MIT @babel/parser 7.29.11的静态符号/导入索引,逐文件SHA256增量复用并绑定项目;Python只登记有明确范围的声明定位。9项索引专项包含Git过滤脚本不执行已通过。
|
||||
2. [complete] 带原文件SHA256、唯一锚点与不重叠范围的精确补丁提案;保留原有字节格式和审核/备份/冲突检查。6项补丁专项通过。
|
||||
3. [complete] 索引/查询/补丁模型工具、只读API及任务面板;结果能定位实际文件/行并核对来源。完整112项行为/API与43组桌面/390px流程通过。
|
||||
4. [in_progress] 相关契约、实际模型工程样本、桌面/390px回归、独立发行与本地Git提交。开始保存实现并验证1.3.0发行;真实模型/正式部署结果待完成后登记。
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, compatibleFixture, completion, call, until, assertToolPairs, launchWorkbench } from './helpers.mjs';
|
||||
import { Runtime, validateToolArgs } from '../src/server/runtime.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { applyChange, hash } from '../src/server/files.mjs';
|
||||
|
||||
test('model code tools keep Task/Run ownership, index evidence and exact proposals across storage recovery', async t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'compute.ts'), original = '\uFEFF// protected banner\r\nexport function compute() { return 1; }\r\n';
|
||||
fs.writeFileSync(target, original); let rounds = 0, fileSha = '';
|
||||
const model = await compatibleFixture(t, (_url, input) => {
|
||||
assertToolPairs(input.messages); rounds++;
|
||||
const output = id => JSON.parse(input.messages.find(value => value.tool_call_id === id).content);
|
||||
if (rounds === 1) {
|
||||
for (const name of ['index_project', 'query_code', 'propose_patch']) assert.ok(input.tools.some(value => value.function.name === name));
|
||||
return completion([call('index', 'index_project', {}), call('query', 'query_code', { query: 'compute', kind: 'symbols', limit: 5 })]);
|
||||
}
|
||||
if (rounds === 2) {
|
||||
assert.equal(output('index').projectId, f.project.id); assert.equal(output('query').results[0].line, 2);
|
||||
assert.ok(output('index').artifact_id); assert.equal(output('query').results[0].evidenceMethod, 'javascript-typescript-ast');
|
||||
return completion([call('read', 'read_file', { path: 'compute.ts', start_line: 2, end_line: 2 })]);
|
||||
}
|
||||
if (rounds === 3) {
|
||||
fileSha = output('read').sha256; assert.equal(output('read').bom, true);
|
||||
return completion([call('patch', 'propose_patch', { path: 'compute.ts', base_sha256: fileSha, reason: 'Repair precise implementation', edits: [{ old_text: 'return 1;', new_text: 'return 2;' }] })]);
|
||||
}
|
||||
assert.equal(output('patch').status, 'awaiting_review'); assert.equal(output('patch').patch.lineEnding, 'crlf');
|
||||
return completion([], '精确补丁已准备,请审核当前项目的差异。');
|
||||
});
|
||||
f.store.saveConfig({ ...f.store.config, mode: 'compatible', baseUrl: model.baseUrl, model: 'index-tool-fixture' });
|
||||
const provider = new Provider(); provider.setKey('synthetic-index-key'); const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'Use project index and exact patches'); await until(() => !runtime.isActive(f.session.id), 15000);
|
||||
assert.equal(rounds, 4); assert.equal(f.session.changes.length, 1); assert.equal(fs.readFileSync(target, 'utf8'), original);
|
||||
const change = f.session.changes[0], run = f.store.executionSnapshot(f.session).run;
|
||||
assert.equal(change.editKind, 'exact-patch'); assert.equal(change.runId, run.id); assert.equal(change.taskId, run.taskId); assert.equal(change.baseSha256, fileSha);
|
||||
const artifact = f.store.executionSnapshot(f.session).artifacts.find(value => value.kind === 'project-index');
|
||||
const owned = f.store.owned('artifact', artifact.id, f.session.id), content = f.store.artifactStore.read(owned), index = JSON.parse(content);
|
||||
assert.equal(owned.runId, run.id); assert.equal(owned.taskId, run.taskId); assert.equal(owned.sha256, hash(Buffer.from(content))); assert.equal(index.projectId, f.project.id);
|
||||
assert.ok(!content.includes('synthetic-index-key')); assert.equal(index.symbols.find(value => value.name === 'compute').sha256, fileSha);
|
||||
const other = f.store.createSession(f.project.id); assert.throws(() => f.store.owned('artifact', artifact.id, other.id));
|
||||
applyChange(f.store, f.session, change.id); assert.equal(fs.readFileSync(target, 'utf8'), original.replace('return 1;', 'return 2;'));
|
||||
f.store.close(); const recovered = new Store(f.data); f.onCleanup(() => recovered.close());
|
||||
assert.deepEqual(recovered.session(f.session.id).changes[0].patch, change.patch);
|
||||
assert.equal(recovered.artifactStore.read(recovered.owned('artifact', artifact.id, f.session.id)), content);
|
||||
});
|
||||
|
||||
test('bundled code APIs isolate project results, validate queries and create review-only patches with conflicts', async t => {
|
||||
const f = fixture(t); fs.writeFileSync(path.join(f.projectRoot, 'code.mjs'), 'export const currentOnly = 1;\n');
|
||||
const otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot); fs.writeFileSync(path.join(otherRoot, 'code.mjs'), 'export const otherOnly = 1;\n');
|
||||
const other = f.store.addProject(otherRoot), server = await launchWorkbench(t, f.data);
|
||||
assert.equal(server.bootstrap.capabilities.codeIndex, 'bounded-ast-and-candidates'); assert.equal(server.bootstrap.capabilities.exactPatches, 'sha256-unique-anchors');
|
||||
assert.equal((await fetch(server.url + '/api/projects/' + f.project.id + '/code-index')).status, 403);
|
||||
const index = await server.api('/projects/' + f.project.id + '/code-index'); assert.equal(index.projectId, f.project.id); assert.equal(index.coverage.astFiles, 1);
|
||||
const own = await server.api('/projects/' + f.project.id + '/code-query?query=currentOnly&kind=symbols'); assert.equal(own.results[0].path, 'code.mjs'); assert.equal(own.results[0].line, 1);
|
||||
const separate = await server.api('/projects/' + other.id + '/code-query?query=currentOnly'); assert.equal(separate.results.length, 0); assert.equal(separate.index.projectId, other.id);
|
||||
for (const query of ['kind=references', 'limit=0', 'limit=61', 'limit=abc', 'query=' + 'a'.repeat(201)]) await assert.rejects(server.api('/projects/' + f.project.id + '/code-query?' + query), { status: 400 });
|
||||
const args = { path: 'code.mjs', base_sha256: own.results[0].sha256, reason: 'Exact API edit', edits: [{ old_text: 'currentOnly = 1', new_text: 'currentOnly = 2' }] };
|
||||
const proposed = await server.api('/sessions/' + f.session.id + '/patch-proposals', args); assert.equal(proposed.changes[0].editKind, 'exact-patch');
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'code.mjs'), 'utf8'), 'export const currentOnly = 1;\n');
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'code.mjs'), 'export const owner = 3;\n');
|
||||
await assert.rejects(server.api('/sessions/' + f.session.id + '/patch-proposals', args), { status: 409 });
|
||||
await assert.rejects(server.api('/sessions/' + f.session.id + '/changes/' + proposed.changes[0].id + '/apply', {}), { status: 409 });
|
||||
const refreshed = await server.api('/projects/' + f.project.id + '/code-query?query=owner'); assert.equal(refreshed.results[0].name, 'owner'); assert.notEqual(refreshed.index.indexFingerprint, own.index.indexFingerprint);
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'code.mjs'), 'utf8'), 'export const owner = 3;\n');
|
||||
});
|
||||
|
||||
test('code tool arguments reject malformed ownership-independent inputs before side effects', () => {
|
||||
for (const [name, args] of [['query_code', { query: 'q', kind: 'references' }], ['query_code', { query: [] }], ['query_code', { query: 'q', limit: 1.5 }],
|
||||
['propose_patch', { path: 'a', base_sha256: 'invalid', reason: 'x', edits: [] }], ['propose_patch', { path: 'a', base_sha256: 'a'.repeat(64), reason: 'x', edits: [] }]]) assert.throws(() => validateToolArgs(name, args));
|
||||
validateToolArgs('query_code', { query: 'compute', kind: 'symbols', limit: 5 });
|
||||
validateToolArgs('propose_patch', { path: 'a', base_sha256: 'a'.repeat(64), reason: 'x', edits: [{ old_text: 'a', new_text: 'b' }] });
|
||||
});
|
||||
+11
-5
@@ -90,12 +90,18 @@ export async function launchWorkbench(t, data, extraEnv = {}) {
|
||||
child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); });
|
||||
await until(() => url || child.exitCode !== null);
|
||||
assert.ok(url, 'Workbench launch failed: ' + errors);
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
|
||||
const api = async (route, input) => {
|
||||
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token },
|
||||
...(input === undefined ? {} : { body: JSON.stringify(input) }) });
|
||||
const result = await response.json();
|
||||
const method = input === undefined ? 'GET' : 'POST';
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url + '/api' + route, { method,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' },
|
||||
...(input === undefined ? {} : { body: JSON.stringify(input) }) });
|
||||
} catch (cause) { throw Object.assign(new Error('QA API transport failed before response headers: ' + method + ' ' + route, { cause }), { stage: 'response_headers', method, route }); }
|
||||
let result;
|
||||
try { result = await response.json(); }
|
||||
catch (cause) { throw Object.assign(new Error('QA API transport failed while reading response: ' + method + ' ' + route, { cause }), { stage: 'response_body', method, route }); }
|
||||
if (!response.ok) throw Object.assign(new Error(result.error), { status: response.status });
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture } from './helpers.mjs';
|
||||
import { proposePatch, proposeFile, readText, applyChange, hash } from '../src/server/files.mjs';
|
||||
|
||||
test('exact patches preserve BOM/CRLF, unicode and all unselected bytes and back up the original on apply', t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'code.ts');
|
||||
const before = Buffer.from('\uFEFF// 保留🙂\r\nexport const value = 1;\r\n\r\nexport function keep() { return "原文"; }\r\n'); fs.writeFileSync(target, before);
|
||||
const file = readText(f.project, 'code.ts'); assert.equal(file.bom, true);
|
||||
const result = proposePatch(f.store, f.session, { path: file.path, base_sha256: file.sha256.toUpperCase(), reason: 'precise replacement',
|
||||
edits: [{ old_text: 'export const value = 1;\n', new_text: 'export const value = 2;\nexport const added = true;\n' }] });
|
||||
assert.equal(result.status, 'awaiting_review'); assert.equal(result.patch.lineEnding, 'crlf'); assert.equal(result.patch.preservedBom, true);
|
||||
assert.deepEqual(fs.readFileSync(target), before);
|
||||
const change = f.session.changes[0]; assert.equal(change.editKind, 'exact-patch'); assert.equal(change.baseContent, before.toString('utf8')); assert.equal(change.baseSha256, hash(before));
|
||||
assert.equal(change.patch.ranges[0].startLine, 2); assert.equal(change.patch.ranges[0].anchorSha256, hash(Buffer.from('export const value = 1;\r\n')));
|
||||
applyChange(f.store, f.session, result.change_id);
|
||||
const expected = Buffer.from(before.toString('utf8').replace('export const value = 1;\r\n', 'export const value = 2;\r\nexport const added = true;\r\n'));
|
||||
assert.deepEqual(fs.readFileSync(target), expected); assert.deepEqual(fs.readFileSync(path.join(f.data, 'backups', f.session.id, change.id + '.txt')), before);
|
||||
});
|
||||
|
||||
test('several patches are matched against one original snapshot in any input order and keep LF', t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'code.js'); fs.writeFileSync(target, 'const first = 1;\nconst second = 2;\n// trailing\n');
|
||||
const file = readText(f.project, 'code.js');
|
||||
const result = proposePatch(f.store, f.session, { path: file.path, base_sha256: file.sha256, reason: 'two edits', edits: [
|
||||
{ old_text: 'const second = 2;\r\n', new_text: 'const second = 20;\r\n' }, { old_text: 'const first = 1;', new_text: 'const first = 10;' }] });
|
||||
assert.equal(result.patch.edits, 2); assert.deepEqual(result.patch.ranges.map(value => value.startLine), [1, 2]);
|
||||
applyChange(f.store, f.session, result.change_id); assert.equal(fs.readFileSync(target, 'utf8'), 'const first = 10;\nconst second = 20;\n// trailing\n');
|
||||
});
|
||||
|
||||
test('mixed line endings require exact anchors and preserve untouched formatting', t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'mixed.txt'); fs.writeFileSync(target, 'first\r\nsecond\nthird\r\n');
|
||||
const file = readText(f.project, 'mixed.txt'), args = { path: file.path, base_sha256: file.sha256, reason: 'mixed' };
|
||||
assert.throws(() => proposePatch(f.store, f.session, { ...args, edits: [{ old_text: 'first\nsecond', new_text: 'changed' }] }), { status: 409 });
|
||||
const result = proposePatch(f.store, f.session, { ...args, edits: [{ old_text: 'second\n', new_text: 'replacement\n' }] });
|
||||
assert.equal(result.patch.lineEnding, 'mixed'); applyChange(f.store, f.session, result.change_id);
|
||||
assert.equal(fs.readFileSync(target, 'utf8'), 'first\r\nreplacement\nthird\r\n');
|
||||
});
|
||||
|
||||
test('ambiguous, overlapping, missing and malformed patch anchors never create a proposal or write', t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'anchors.txt'); const original = 'repeat repeat\nabcdef\n'; fs.writeFileSync(target, original);
|
||||
const file = readText(f.project, 'anchors.txt'), args = { path: file.path, base_sha256: file.sha256, reason: 'reject invalid' };
|
||||
const invalid = [[], [{ old_text: '', new_text: 'x' }], [{ old_text: 'repeat', new_text: 'x' }], [{ old_text: 'missing', new_text: 'x' }],
|
||||
[{ old_text: 'abc', new_text: 'x' }, { old_text: 'bcd', new_text: 'y' }], [null], [{ old_text: 1, new_text: 'x' }],
|
||||
[{ old_text: 'abc', new_text: '\0' }], [{ old_text: 'abc', new_text: 42 }], Array.from({ length: 33 }, () => ({ old_text: 'abc', new_text: 'x' }))];
|
||||
for (const edits of invalid) assert.throws(() => proposePatch(f.store, f.session, { ...args, edits }));
|
||||
assert.throws(() => proposePatch(f.store, f.session, { ...args, base_sha256: 'invalid', edits: [{ old_text: 'abc', new_text: 'x' }] }));
|
||||
assert.throws(() => proposePatch(f.store, f.session, { ...args, path: '../anchors.txt', edits: [{ old_text: 'abc', new_text: 'x' }] }));
|
||||
assert.equal(f.session.changes.length, 0); assert.equal(fs.readFileSync(target, 'utf8'), original);
|
||||
});
|
||||
|
||||
test('stale original hashes and changes before apply preserve owner edits and mark conflicts', t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'value.txt'); fs.writeFileSync(target, 'value = 1\n');
|
||||
const file = readText(f.project, 'value.txt'), args = { path: file.path, base_sha256: file.sha256, reason: 'fix', edits: [{ old_text: 'value = 1', new_text: 'value = 2' }] };
|
||||
const result = proposePatch(f.store, f.session, args); fs.writeFileSync(target, 'owner = 3\n');
|
||||
assert.throws(() => proposePatch(f.store, f.session, args), { status: 409 });
|
||||
assert.throws(() => applyChange(f.store, f.session, result.change_id), { status: 409 }); assert.equal(f.session.changes[0].status, 'conflict'); assert.equal(fs.readFileSync(target, 'utf8'), 'owner = 3\n');
|
||||
});
|
||||
|
||||
test('no-op BOM patches/full content produce no change and replacements cannot split Unicode bytes', t => {
|
||||
const f = fixture(t), target = path.join(f.projectRoot, 'unicode.txt'); const contents = '\uFEFFkeep🙂\n'; fs.writeFileSync(target, contents);
|
||||
const file = readText(f.project, 'unicode.txt'), args = { path: file.path, base_sha256: file.sha256, reason: 'noop' };
|
||||
assert.equal(proposePatch(f.store, f.session, { ...args, edits: [{ old_text: 'keep', new_text: 'keep' }] }).status, 'unchanged');
|
||||
assert.equal(proposeFile(f.store, f.session, { path: file.path, content: contents }).status, 'unchanged');
|
||||
assert.throws(() => proposePatch(f.store, f.session, { ...args, edits: [{ old_text: '\ud83d', new_text: 'x' }] }));
|
||||
assert.throws(() => proposePatch(f.store, f.session, { ...args, edits: [{ old_text: 'keep', new_text: '\ud83d' }] }));
|
||||
assert.equal(f.session.changes.length, 0); assert.equal(fs.readFileSync(target, 'utf8'), contents);
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { ProjectIndex } from '../src/core/context/project-index.mjs';
|
||||
import { inspectProject } from '../src/core/project-inspector.mjs';
|
||||
import { readText } from '../src/server/files.mjs';
|
||||
import { fixture } from './helpers.mjs';
|
||||
|
||||
function write(f, relative, contents) {
|
||||
const target = path.join(f.projectRoot, relative);
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, contents);
|
||||
}
|
||||
const gitFor = f => args => execFileSync('git', ['-C', f.projectRoot, '-c', 'core.autocrlf=false', ...args], { windowsHide: true, encoding: 'utf8' });
|
||||
function initGit(f) {
|
||||
const git = gitFor(f); git(['init', '--initial-branch=main']); git(['add', '.']);
|
||||
git(['-c', 'user.name=Workbench QA', '-c', 'user.email=qa@workbench.local', 'commit', '-m', 'Index fixture']); return git;
|
||||
}
|
||||
|
||||
test('JS/TS/React AST indexes actual declarations, exports, imports and verified source lines', async t => {
|
||||
const f = fixture(t);
|
||||
write(f, 'src/shape.ts', ['// function Fake() {}', 'const text = "class Imaginary {}";', 'import type { Point } from "./point.js";',
|
||||
'export interface Shape { area(): number; }', 'export type Size = number;', 'export enum Mode { Active }',
|
||||
'export function area(size: Size) { function square() { return size * size; } return square(); }',
|
||||
'export class Box { area() { return 1; } privateFn = () => 2; }', 'const alias = (x: number) => x;', 'export { alias };',
|
||||
'export * from "./point.js";', 'const later = import("./point.js");', 'const required = require("./point.js");', ''].join('\n'));
|
||||
write(f, 'src/point.ts', 'export interface Point { x: number; }\n');
|
||||
write(f, 'src/Card.tsx', 'import React from "react";\nexport const Card = () => <button>查看</button>;\n');
|
||||
const indexer = new ProjectIndex(), index = await indexer.refresh(f.project);
|
||||
assert.equal(index.coverage.astFiles, 3); assert.equal(index.coverage.truncated, false);
|
||||
const symbols = index.symbols.filter(value => value.path === 'src/shape.ts');
|
||||
for (const name of ['Shape', 'Size', 'Mode', 'area', 'Box', 'alias', 'Box.area', 'Box.privateFn', 'area.square']) assert.ok(symbols.some(value => value.qualifiedName === name), name);
|
||||
assert.ok(!symbols.some(value => ['Fake', 'Imaginary'].includes(value.name)));
|
||||
assert.equal(symbols.find(value => value.name === 'Shape').line, 4);
|
||||
assert.equal(symbols.find(value => value.name === 'alias').exported, true);
|
||||
assert.equal(symbols.find(value => value.name === 'area' && value.kind === 'function').sha256, readText(f.project, 'src/shape.ts').sha256);
|
||||
assert.ok(index.symbols.find(value => value.name === 'Card').exported);
|
||||
const local = index.imports.filter(value => value.from === 'src/shape.ts'); assert.equal(local.length, 4);
|
||||
assert.deepEqual(local.map(value => value.kind), ['type-import', 're-export', 'literal-dynamic-import', 'literal-require-call']);
|
||||
for (const value of local) { assert.equal(value.target, 'src/point.ts'); assert.equal(value.runtimeResolution, 'not_verified'); }
|
||||
const external = index.imports.find(value => value.source === 'react'); assert.equal(external.status, 'external-or-alias'); assert.equal(external.target, null);
|
||||
const found = indexer.query(index, { query: 'Box area', kind: 'symbols' }); assert.equal(found.results[0].qualifiedName, 'Box.area');
|
||||
assert.match(index.indexFingerprint, /^[a-f0-9]{64}$/); assert.equal(indexer.summary(index).sourceFingerprint, index.sourceFingerprint);
|
||||
});
|
||||
|
||||
test('default expressions, named default exports and declared functions retain their AST evidence', async t => {
|
||||
const f = fixture(t);
|
||||
write(f, 'arrow.mjs', 'export default (value) => value + 1;\n');
|
||||
write(f, 'named.mjs', 'function calculate() { return 1; }\nexport default calculate;\n');
|
||||
write(f, 'class.mjs', 'export default class { run() { return 1; } }\n');
|
||||
write(f, 'overload.ts', 'export declare function convert(value: string): number;\n');
|
||||
const index = await new ProjectIndex().refresh(f.project);
|
||||
assert.ok(index.symbols.find(value => value.path === 'arrow.mjs' && value.name === 'default' && value.exported && value.kind === 'function'));
|
||||
assert.ok(index.symbols.find(value => value.name === 'calculate' && value.exported));
|
||||
assert.ok(index.symbols.find(value => value.path === 'class.mjs' && value.qualifiedName === 'default.run'));
|
||||
assert.ok(index.symbols.find(value => value.name === 'convert' && value.kind === 'function'));
|
||||
});
|
||||
|
||||
test('incremental refresh invalidates changed/deleted symbols and recalculates reused import targets', async t => {
|
||||
const f = fixture(t); write(f, 'src/use.mjs', 'import { value } from "./new.mjs";\nexport function read() { return value; }\n');
|
||||
const indexer = new ProjectIndex(), first = await indexer.refresh(f.project);
|
||||
assert.equal(first.imports[0].status, 'unresolved-local');
|
||||
const unchanged = await indexer.refresh(f.project); assert.equal(unchanged.refresh.updatedFiles, 0); assert.equal(unchanged.indexFingerprint, first.indexFingerprint);
|
||||
write(f, 'src/new.mjs', 'export const value = 1;\n');
|
||||
const added = await indexer.refresh(f.project); assert.equal(added.imports[0].target, 'src/new.mjs'); assert.equal(added.refresh.updatedFiles, 1); assert.ok(added.refresh.reusedFiles >= 2);
|
||||
write(f, 'src/new.mjs', 'export const different = 2;\n');
|
||||
const changed = await indexer.refresh(f.project); assert.ok(changed.symbols.some(value => value.name === 'different')); assert.ok(!changed.symbols.some(value => value.name === 'value'));
|
||||
assert.notEqual(changed.imports[0].targetSha256, added.imports[0].targetSha256);
|
||||
fs.unlinkSync(path.join(f.projectRoot, 'src/new.mjs'));
|
||||
const removed = await indexer.refresh(f.project); assert.equal(removed.refresh.removedFiles, 1); assert.equal(removed.imports[0].target, null); assert.ok(!removed.symbols.some(value => value.name === 'different'));
|
||||
assert.equal(first.imports[0].target, null, 'refresh must not mutate previously returned evidence');
|
||||
});
|
||||
|
||||
test('Python candidates exclude comments and multiline strings and declare limited evidence', async t => {
|
||||
const f = fixture(t);
|
||||
write(f, 'main.py', ['"""', 'def fake_doc():', 'class FakeDoc:', '"""', '# def fake_comment():', 'text = "def fake_text():"',
|
||||
'class Service:', ' def run(self):', ' return 1', 'if True:', ' def conditional():', ' return 2',
|
||||
"continued = 'example\\", 'def fake_continued():\\', "end'", 'async def actual():', ' pass', 'from .tools import helper', ''].join('\n'));
|
||||
write(f, 'tools.py', 'def helper():\n return 1\n');
|
||||
const index = await new ProjectIndex().refresh(f.project);
|
||||
assert.equal(index.coverage.pythonCandidateFiles, 2);
|
||||
const symbols = index.symbols.filter(value => value.path === 'main.py');
|
||||
assert.deepEqual(symbols.map(value => value.qualifiedName), ['Service', 'Service.run', 'conditional', 'actual']);
|
||||
assert.ok(symbols.every(value => value.evidenceMethod === 'python-declaration-candidate'));
|
||||
assert.equal(symbols.find(value => value.name === 'actual').line, 16);
|
||||
assert.equal(index.imports.find(value => value.source === '.tools').runtimeResolution, 'not_verified');
|
||||
assert.match(index.notes.join(' '), /候选/);
|
||||
});
|
||||
|
||||
test('indexes isolate project identity and root and evict bounded caches without sharing results', async t => {
|
||||
const f = fixture(t), otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot); fs.writeFileSync(path.join(otherRoot, 'README.md'), 'other');
|
||||
fs.writeFileSync(path.join(otherRoot, 'unique.ts'), 'export const otherOnly = true;\n'); write(f, 'unique.ts', 'export const hereOnly = true;\n');
|
||||
const other = { ...f.project, root: fs.realpathSync.native(otherRoot) };
|
||||
const indexer = new ProjectIndex({ maximumProjects: 1 });
|
||||
const firstPromise = indexer.refresh(f.project); assert.equal(indexer.refresh(f.project), firstPromise);
|
||||
const first = await firstPromise, second = await indexer.refresh(other);
|
||||
assert.ok(first.symbols.some(value => value.name === 'hereOnly')); assert.ok(!second.symbols.some(value => value.name === 'hereOnly'));
|
||||
assert.ok(second.symbols.some(value => value.name === 'otherOnly')); assert.notEqual(first.indexFingerprint, second.indexFingerprint);
|
||||
assert.equal(indexer.projects.size, 1); const again = await indexer.refresh(f.project); assert.ok(again.refresh.updatedFiles > 0); assert.equal(indexer.pending.size, 0);
|
||||
});
|
||||
|
||||
test('Git ignore, credential paths and links stay outside the index and no project files are executed', async t => {
|
||||
const f = fixture(t); write(f, '.gitignore', 'ignored/\n.env\n'); write(f, 'main.mjs', 'export function safe() { throw new Error("do not execute"); }\n');
|
||||
initGit(f); write(f, 'ignored/hidden.mjs', 'export const hidden = true;\n'); write(f, '.env', 'credential-sentinel');
|
||||
write(f, 'credentials.json', 'credential-sentinel'); write(f, 'node_modules/dependency/index.js', 'export const dependencyHidden = true;\n');
|
||||
const outside = path.join(f.root, 'outside'); fs.mkdirSync(outside); fs.writeFileSync(path.join(outside, 'private.js'), 'export const linkedHidden = true;');
|
||||
fs.symlinkSync(outside, path.join(f.projectRoot, 'linked'), process.platform === 'win32' ? 'junction' : 'dir');
|
||||
const index = await new ProjectIndex().refresh(f.project), text = JSON.stringify(index);
|
||||
for (const sentinel of ['credential-sentinel', 'dependencyHidden', 'linkedHidden', 'hidden =']) assert.ok(!text.includes(sentinel));
|
||||
assert.ok(!index.files.some(value => /^(ignored|node_modules|linked)\//.test(value.path)));
|
||||
assert.equal(index.symbols.find(value => value.name === 'safe').path, 'main.mjs');
|
||||
});
|
||||
|
||||
test('malformed, binary, non-UTF8 and bounded files expose partial coverage while good files remain searchable', async t => {
|
||||
const f = fixture(t); write(f, 'good.ts', 'export const valid = true;\n'); write(f, 'broken.ts', 'export function broken( {');
|
||||
write(f, 'binary.js', Buffer.from([0, 1, 2])); write(f, 'encoding.ts', Buffer.from([0xff])); write(f, 'large.js', '// padding\n'.repeat(25));
|
||||
const indexer = new ProjectIndex({ maximumFileBytes: 128 }), index = await indexer.refresh(f.project);
|
||||
assert.equal(index.coverage.truncated, true); assert.equal(index.coverage.unindexedFiles, 4);
|
||||
assert.ok(index.warnings.find(value => value.path === 'broken.ts').line > 0);
|
||||
assert.equal(index.files.find(value => value.path === 'large.js').status, 'outside-index-budget');
|
||||
assert.equal(indexer.query(index, { query: 'valid' }).results[0].name, 'valid');
|
||||
assert.equal(indexer.query(index, { query: 'not found' }).truncated, true);
|
||||
const limited = await new ProjectIndex({ maximumSymbolsPerFile: 1, maximumSymbols: 1 }).refresh(f.project);
|
||||
assert.ok(limited.symbols.length <= 1); assert.equal(limited.coverage.truncated, true);
|
||||
});
|
||||
|
||||
test('index query rejects invalid limits/types and does not imply reference or alias resolution', async t => {
|
||||
const f = fixture(t); write(f, 'app.ts', 'import { worker } from "@app/worker";\nconst a = 1;\nconst b = 2;\n');
|
||||
const indexer = new ProjectIndex(), index = await indexer.refresh(f.project);
|
||||
for (const args of [{ query: null }, { query: 'x'.repeat(201) }, { kind: 'references' }, { limit: 0 }, { limit: 61 }, { limit: 1.5 }]) assert.throws(() => indexer.query(index, args));
|
||||
const result = indexer.query(index, { query: '', kind: 'symbols', limit: 1 }); assert.equal(result.results.length, 1); assert.equal(result.totalMatches, 2); assert.equal(result.truncated, true);
|
||||
assert.equal(index.imports[0].status, 'external-or-alias'); assert.equal(index.imports[0].target, null);
|
||||
});
|
||||
|
||||
test('read-only engineering inspection disables configured Git clean filters and preserves index bytes', async t => {
|
||||
const f = fixture(t), marker = path.join(f.root, 'filter-executed.txt'), script = path.join(f.root, 'filter.mjs');
|
||||
write(f, '.gitattributes', '*.mjs filter=fixture\n'); write(f, 'main.mjs', 'export const value = 1;\n');
|
||||
const git = initGit(f);
|
||||
fs.writeFileSync(script, "import fs from 'node:fs'; fs.writeFileSync(" + JSON.stringify(marker) + ", 'filter executed'); process.stdin.pipe(process.stdout);\n");
|
||||
git(['config', 'filter.fixture.clean', '"' + process.execPath.replaceAll('\\', '/') + '" "' + script.replaceAll('\\', '/') + '"']);
|
||||
git(['config', 'filter.fixture.required', 'true']);
|
||||
write(f, 'main.mjs', 'export const value = 2;\n');
|
||||
git(['status', '--porcelain=v1']); assert.equal(fs.existsSync(marker), true, 'the fixture must prove ordinary Git status executes the custom filter'); fs.unlinkSync(marker);
|
||||
const indexBytes = fs.readFileSync(path.join(f.projectRoot, '.git/index'));
|
||||
const inspection = await inspectProject(f.project);
|
||||
assert.equal(fs.existsSync(marker), false, 'read-only inspection must not execute project filter commands');
|
||||
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, '.git/index')), indexBytes);
|
||||
assert.equal(inspection.git.available, true); assert.equal(inspection.git.dirty, true);
|
||||
const index = await new ProjectIndex().refresh(f.project); assert.equal(index.symbols.find(value => value.name === 'value').path, 'main.mjs');
|
||||
assert.equal(fs.existsSync(marker), false);
|
||||
});
|
||||
|
||||
test('Python multiline declarations retain candidate scope without interpreting expressions as declarations', async t => {
|
||||
const f = fixture(t); write(f, 'multiline.py', 'class Worker:\n def run(\n self,\n value\n ):\n def inner():\n return value\n return inner()\n');
|
||||
const index = await new ProjectIndex().refresh(f.project);
|
||||
assert.deepEqual(index.symbols.map(value => value.qualifiedName), ['Worker', 'Worker.run', 'Worker.run.inner']);
|
||||
write(f, 'one.py', 'def one():\n pass\n');
|
||||
const bounded = await new ProjectIndex({ maximumSymbolsPerFile: 1 }).refresh(f.project);
|
||||
assert.equal(bounded.files.find(value => value.path === 'one.py').truncated, false);
|
||||
assert.equal(bounded.files.find(value => value.path === 'multiline.py').truncated, true);
|
||||
});
|
||||
|
||||
test('TypeScript module candidates support import-equals and MTS/CTS while opaque imports stay explicit', async t => {
|
||||
const f = fixture(t);
|
||||
write(f, 'main.ts', 'import helper = require("./helper.cjs");\nimport { value } from "./module.mjs";\nconst pathName = "./module.mjs";\nconst dynamic = import(pathName);\n');
|
||||
write(f, 'helper.cts', 'export const helper = true;\n'); write(f, 'module.mts', 'export const value = 1;\n');
|
||||
const index = await new ProjectIndex().refresh(f.project), imports = index.imports.filter(value => value.from === 'main.ts');
|
||||
assert.equal(imports.length, 2); assert.equal(imports[0].kind, 'import-equals'); assert.equal(imports[0].target, 'helper.cts'); assert.deepEqual(imports[0].bindings, ['helper']);
|
||||
assert.equal(imports[1].target, 'module.mts'); assert.equal(imports[1].runtimeResolution, 'not_verified');
|
||||
assert.equal(index.coverage.truncated, true); assert.match(index.warnings.find(value => value.path === 'main.ts').message, /动态导入/);
|
||||
write(f, 'module.mjs', 'export const value = 2;\n');
|
||||
const exact = await new ProjectIndex().refresh(f.project); assert.equal(exact.imports.find(value => value.source === './module.mjs').target, 'module.mjs');
|
||||
});
|
||||
Reference in New Issue
Block a user