diff --git a/.github/workflows/native-windows.yml b/.github/workflows/native-windows.yml new file mode 100644 index 0000000..0388edc --- /dev/null +++ b/.github/workflows/native-windows.yml @@ -0,0 +1,56 @@ +name: Native Windows WorkBuddy (pinned, synthetic) +on: + push: + paths: + - 'src/**' + - 'plugins/**' + - 'scripts/**' + - 'ci/**' + - '.github/workflows/native-windows.yml' + pull_request: + paths: + - 'src/**' + - 'plugins/**' + - 'scripts/**' + - 'ci/**' + - '.github/workflows/native-windows.yml' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }} + cancel-in-progress: true +permissions: + contents: read +jobs: + native: + runs-on: windows-2025 + timeout-minutes: 20 + env: + PYTHONUTF8: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Build the native plugin + run: python scripts/build_plugins.py + - name: Windows unit and actual PowerShell parser gates + working-directory: src/plugin + run: python -m unittest discover -s tests -v + - name: Download verified official artifact and statically extract (never run installer) + shell: pwsh + run: ./scripts/prepare_windows_runtime.ps1 -Output (Join-Path $env:RUNNER_TEMP 'wb-pinned-runtime') + - name: Actual native CLI using only a synthetic isolated profile + shell: pwsh + run: python scripts/native_smoke.py --node $env:WORKBUDDY_TEST_NODE --cli $env:WORKBUDDY_TEST_CLI --output (Join-Path $env:RUNNER_TEMP 'wb-native-smoke') + - name: Preserve synthetic diagnostics, never vendor binaries + if: always() + uses: actions/upload-artifact@v4 + with: + name: native-windows-synthetic-diagnostics + path: | + ${{ runner.temp }}/wb-native-smoke/result.json + ${{ runner.temp }}/wb-native-smoke/logs/*.txt + ${{ runner.temp }}/wb-pinned-runtime/runtime.json + if-no-files-found: ignore diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..37c9bb0 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,33 @@ +name: Synthetic tests +on: [push, pull_request, workflow_dispatch] +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }} + cancel-in-progress: true +permissions: + contents: read +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + python: ['3.10', '3.12'] + runs-on: ${{ matrix.os }} + env: + PYTHONUTF8: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Build native plugin + run: python scripts/build_plugins.py + - name: Compile + run: python -m compileall -q src plugins + - name: Synthetic regression tests (no WorkBuddy binary or API calls) + working-directory: src/plugin + run: python -m unittest discover -s tests -v + - name: Check plugin packaging + run: python -m unittest discover -s tests -v diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..58cb6da --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +__pycache__/ +*.py[cod] +.venv/ +.env +.env.* +*.db +*.db-* +*.jsonl +.conversation-tools.json +.codebuddy/ +.workbuddy/ +*operations/ +runtime/ +source_reference/ +*.zip +.DS_Store +Thumbs.db diff --git a/.workbuddy-plugin/marketplace.json b/.workbuddy-plugin/marketplace.json new file mode 100644 index 0000000..61e219e --- /dev/null +++ b/.workbuddy-plugin/marketplace.json @@ -0,0 +1,13 @@ +{ + "name": "workbuddy-plugins", + "owner": { + "name": "WorkBuddy Conversation Tools" + }, + "plugins": [ + { + "name": "workbuddy-tools", + "source": "./plugins/workbuddy-tools", + "version": "0.2.0" + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md index 15e7ca7..178e916 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,111 @@ -# workbuddy-plugins -Combined conversation branching and style plugin for WorkBuddy on Windows. +# WorkBuddy 会话分支/思考风格 seed 原生插件 + +一个原生插件,同时提供会话分支和显式最小思考风格 seed。**Windows 优先,Linux 回归**;不是独立 GUI,不是 Git 分支工具。 + +安装名 `workbuddy-tools`,统一命名空间 `/workbuddy-tools:`。代码位于一个仓库,可公开发布;不包含私人 seed 或账号历史。 + +当前版本 `0.2.0`。已在 GitHub 云端 Windows Server 2025 上使用官方 WorkBuddy 5.9.3.42398134 / CLI 2.165.0 完成真实原生回归;Windows/Linux × Python 3.10/3.12 合成测试也全部通过。覆盖原生 CLI、hook、会话持久化和本地登记,不冒充桌面 GUI 或真实模型效果验证。详细证据见 [VERIFICATION.md](VERIFICATION.md)。 + +## 安装前检查 + +- Windows:WorkBuddy 5.9.3,bundled CLI package 2.165.0;已完成固定版本真实原生云端回归;未知 CLI 版本或数据库结构会拒绝写入。 +- Linux:WorkBuddy 5.6.2.40046327 / CLI 2.147.0,最终合并版本的原生分支、hook、seed、DB 及丢输出 fail-closed 压力回归均已通过。 +- Python **3.10+**,Windows 还必须有 **PowerShell 7 `pwsh`**,并可被 WorkBuddy 子进程 PATH 找到。不会安装软件或更改执行策略。 +- 仅支持本地磁盘;拒绝 UNC、junction/reparse point、符号链接。Windows 新会话原子发布需要支持硬链接的文件系统(通常 NTFS);不宣称网络盘/FAT 支持。 +- Node/CLI 使用你确认的官方安装文件或受信任的现有 Node;不从网络下载运行时。部分 Windows 安装把 bundled Node 留在 `resources/vendor/node.zip`,本工具不擅自解压或修改厂商安装。 + +```powershell +py -3 -X utf8 .\plugins\workbuddy-tools\scripts\discover.py +Get-Command pwsh +``` + +`discover.py` 只查标准安装路径;非标准安装可先设置 `$env:WORKBUDDY_INSTALL_DIR`。结果仅为候选,必须确认属于目标 WorkBuddy 安装。可以直接给脚本明确的 `--cli` 与 `--node`。 + +## Windows PowerShell 安装 + +将仓库放到固定目录,不要在安装后移动。下面变量改为你实际路径: + +```powershell +$Repo = 'C:\Tools\workbuddy-plugins' +$Python = 'C:\Path\To\python.exe' # 3.10+ +$Node = 'C:\Path\To\node.exe' +$Cli = 'C:\Path\To\WorkBuddy\resources\app.asar.unpacked\cli\bin\codebuddy' +$Project = 'C:\Projects\My Project' +$env:CODEBUDDY_CONFIG_DIR = Join-Path $HOME '.workbuddy' +$env:WORKBUDDY_CONFIG_DIR = $env:CODEBUDDY_CONFIG_DIR +$env:CODEBUDDY_FORCE_LITE_WB_BUNDLE = '1' # Windows pinned distribution ships lite-WB only +& $Node $Cli plugin validate $Repo +& $Node $Cli plugin marketplace add $Repo +& $Node $Cli plugin install 'workbuddy-tools@workbuddy-plugins' +& $Node $Cli plugin list --json +& $Python -X utf8 "$Repo\plugins\workbuddy-tools\scripts\manage.py" install --project $Project --cli $Cli --node $Node --hook-shell powershell +``` + +只需安装这一个插件。原生插件默认 hook 故意为空:宿主首次 prompt 存在异步加载竞态,因此确定性命令使用上述安装器注册的**项目级原生 UserPromptSubmit hook**。Windows 明确指定 `shell: powershell`,固定 argv 单引号转义;用户命令参数只从 stdin JSON 读取,从不拼进 shell。Linux 使用 `--hook-shell posix`,并设置 `CODEBUDDY_FORCE_HEADLESS_BUNDLE=1`(不要沿用 Windows lite-WB 变量)。 + +安装器保留其它 hooks/权限,首次备份 settings;插件使用唯一项目 router hook 按命名空间分发,避免宿主多 hook 结果聚合与快速退出丢 stdout 的问题。已处理命令无论成功或失败都使用原生退出码 2 阻断;shell 包装将解释器/脚本异常同样映射为 2,不依赖延时。普通 prompt 则无输出退出 0。共享 `.conversation-tools.json` 仅保存官方 CLI argv;不信任新工作区、不修改权限、账号、密钥或默认模型。 + +安装后重启会话或 `/reload-plugins`。先在实际 WorkBuddy 会话执行 `/workbuddy-tools:status`,必须看到本地适配器信息;若出现认证/模型回答或缺失 hook 结果,停止使用创建命令,检查实际宿主的 pwsh/Python PATH。shell 自身无法启动时,插件没有执行机会,宿主行为不在本工具控制内。用同一 Python 执行 `manage.py check --project $Project --hook-shell powershell` 检查插件。 + +## 使用 + +```text +/workbuddy-tools:points +/workbuddy-tools:branch {"at":"latest","title":"方案 B"} +/workbuddy-tools:branch {"at":"完整回复的小写 UUID","title":"从此处分支"} +/workbuddy-tools:style-new {"seed":"C:\\Templates\\we-need.json","title":"带 seed 的新会话"} +/workbuddy-tools:status +/workbuddy-tools:status +``` + +JSON Windows 路径反斜杠需写成 `\\`,也可以使用 `C:/Templates/we-need.json`。完成结果含新会话 UUID 与 `workbuddy://chat/`,由你手动打开;GUI 跳转及列表刷新未验证。不自动向模型发 prompt。 + +`examples/minimal-seed.json` 与 `examples/we-need-demo.json` 在每个插件目录下,都是公开合成示例。后者是简短的 “We need” 规划摘要,不是私人思考记录。seed schema 1:1–2 组严格交替 user/assistant `{role,text}`;assistant 可带纯文本 `reasoning`。不允许 providerData、签名、旧环境、权限、凭证或任意历史结构。文件限 16 KiB,单条可见文字 2000 字、reasoning 4000 字。 + +已证明原生 JSONL 能保留 reasoning/rawContent;Linux 官方离线转换器在模型能力条件满足时能回填 reasoning_content。**没有调用真实模型验证效果,不保证 We need 措辞、固定风格、推理能力提升或原私人模板的等价效果**。默认关闭,只作用于显式创建的新会话,不切换模型。 + +## 安全与恢复 + +本工具从不写源历史/源 DB 行,只克隆并校验本次新目标。宿主自己可能追加 slash 命令与 hook 结果,因此不承诺整个源文件跨操作字节完全相等。未知 CLI 版本、schema、未闭合工具、子代理图或路径越界均拒绝写入。 + +官方 EOF fork 的选定边界不一定持久化;本工具核验克隆契约后,只原子修正新目标。操作回执保存 ID、摘要与状态,不存完整历史。DB insert-only 事务、幂等 UUID、提交前后摘要核验;不创建/迁移数据库。 + +```text +/workbuddy-tools:recover {"operation_id":"操作 UUID"} +/workbuddy-tools:recover {"operation_id":"操作 UUID"} +``` + +恢复只接受已准备摘要与归属一致的目标。来源/目标变化、未确定克隆或 schema 变化时保留诊断,不自动重克隆/删除。源桌面行变化可能导致登记恢复安全停止,需要人工核对。 + +## 卸载 + +```powershell +& $Python -X utf8 "$Repo\plugins\workbuddy-tools\scripts\manage.py" uninstall --project $Project --hook-shell powershell +& $Node $Cli plugin uninstall 'workbuddy-tools@workbuddy-plugins' +``` + +其它用户 hooks 保持不变。卸载依据持久安装归属删除自己的 hook,不删源/新会话、seed、回执或其它设置。不要移动安装目录后直接删除文件,先卸载原项目 hook。 + +## 构建与 CI + +```text +python scripts/build_plugins.py +cd src/plugin +python -m unittest discover -s tests -v +cd ../.. +python -m unittest discover -s tests -v +``` + +`src/plugin` 为共享实现与合成测试;`plugins/workbuddy-tools` 为原生插件产物;`.workbuddy-plugin/marketplace.json` 为原生 marketplace。GitHub Actions 在 Windows/Linux、Python 3.10/3.12 运行无 API 合成测试。CI 配置存在不等于远端 CI 已执行。 + +没有附加开源许可授权;公开可读不等于授权再分发,许可由所有者另行选择。发行物不含厂商二进制、私人历史、账户配置或原始私人项目引用文件。 + +## 可选真实宿主回归(不下载运行时) + +```text +python scripts/native_smoke.py --node /absolute/node --cli /absolute/codebuddy --output /new/isolated/output +``` + +输出目录必须不存在。脚本仅新建合成 HOME/profile/workspace 和数据库,白名单环境不继承凭证;验证安装幂等、会话分支、reasoning EOF、归属卸载。普通 CI 不执行它;另外提供代码路径 push/PR 自动触发、也可手动执行的 `Native Windows WorkBuddy (pinned, synthetic)` workflow,固定官方安装包 SHA256,使用预装 7-Zip 静态提取而不运行安装器。实际宿主任务已通过;更新后仍应检查对应提交的 CI 结果。 + +官方 Windows 固定包证据见 `ci/workbuddy-windows-pin.json`;[官方更新元数据](https://www.workbuddy.cn/v2/update?platform=workbuddy-win32-x64-user) 与实际下载 SHA256 已核对。下载脚本不使用浮动 latest、不接受外部传入 URL、不携带账号密钥;完整验证范围见 [原生验证协议](docs/NATIVE_VERIFICATION.md)。 diff --git a/VERIFICATION.md b/VERIFICATION.md new file mode 100644 index 0000000..b6a6951 --- /dev/null +++ b/VERIFICATION.md @@ -0,0 +1,36 @@ +# Verification — 2026-11-01 + +## Real Windows cloud result: PASS + +Verified implementation commit: [`63c1b4e31f0818d59d5b411da0f750c912e5990b`](https://github.com/bartholo4/workbuddy-plugins/commit/63c1b4e31f0818d59d5b411da0f750c912e5990b). + +- [Native Windows run 41301284752](https://github.com/bartholo4/workbuddy-plugins/actions/runs/41301284752): **success**, GitHub-hosted Windows Server 2025. +- [Windows/Linux × Python 3.10/3.12 matrix 41301284940](https://github.com/bartholo4/workbuddy-plugins/actions/runs/41301284940): **all four jobs successful**. +- Native diagnostic artifact `13081881016`, SHA256 `497d18185319d6d80ed451e47d64282299fdce25a3ac19e93410236c82332484` (retention limited by GitHub). + +The Windows job downloaded official WorkBuddy **5.9.3.42398134**, verified pinned SHA256, statically extracted NSIS/app-64.7z/Node ZIP without executing the installer, and ran its real **CLI 2.165.0** with bundled **Node 22.22.2**. It selected the shipped **lite-WB** bundle; the separate Linux adapter selects its headless bundle. + +Passed in the real Windows host: + +- Native plugin validate, marketplace add/install/list, unified five-command namespace. +- Selected-boundary conversation branching; same workspace; source database row unchanged. +- Insert-only registration against the exact synthetic 40-column schema. +- Reasoning seed creation and native EOF resume/fork roundtrip; **API duration 0**. +- Five additional independent style creations. +- Entire hook stdout/stderr discarded: final shell exit **2** still blocks. +- Missing interpreter: shell guard still blocks rather than forwarding to a model. +- Owned uninstall and installation idempotence. + +Unit gates cover 57 core cases plus 2 packaging cases. Windows actually executes cross-process file-lock and PowerShell parser tests, including spaces, quotes, metacharacters and non-ASCII arguments; external Python exits 1 and 2 both produce final PowerShell exit 2. Platform-inapplicable POSIX/symlink-privilege cases are explicitly skipped; a missing Windows `pwsh` fails, never silently skips. + +## Linux regression: PASS + +Real official Linux WorkBuddy **5.6.2.40046327 / CLI 2.147.0** completed the same combined-plugin native flow, five-repeat style stress, discarded-output guard, missing-interpreter guard and synthetic database checks. The shared-core Linux run passed 54 cases with 3 genuine Windows/PowerShell-specific skips; both packaging cases passed. + +## Scope and remaining limitations + +- Desktop GUI buttons, list refresh and `workbuddy://chat` navigation are **not tested or claimed**. Windows proof is the real native CLI/hook/storage path, not a visual GUI simulation. +- Live model effects are **not tested or promised**. No paid model call is part of these tests. Reasoning persistence is not a guarantee of intelligence, wording or provider behavior. +- All native tests use newly created synthetic HOME/profile/workspace and a credential-free environment. No existing user profile, account, source history, security setting or vendor installation was modified. +- The public repository does not bundle vendor executables, private history, original private source files or credentials. +- Source code changes after the linked commit must be revalidated. Version/verification-document promotion does not replace CI for its resulting commit. diff --git a/ci/workbuddy-windows-pin.json b/ci/workbuddy-windows-pin.json new file mode 100644 index 0000000..28a623a --- /dev/null +++ b/ci/workbuddy-windows-pin.json @@ -0,0 +1,12 @@ +{ + "product": "WorkBuddy", + "platform": "workbuddy-win32-x64-user", + "version": "5.9.3.42398134", + "cli_version": "2.165.0", + "node_version": "22.22.2", + "metadata_url": "https://www.workbuddy.cn/v2/update?platform=workbuddy-win32-x64-user", + "url": "https://download.codebuddy.cn/workbuddy/saas/win32-x64-user/WorkBuddy-win32-x64-user-5.9.3.42398134-d4692421.exe", + "sha256": "b5edb52bd6c5b6c7296cf2fff697b019c86d11992a8a814c3010d611896852f9", + "format": "NSIS-3 Unicode; embedded $PLUGINSDIR/app-64.7z", + "verification": "Official update metadata and independent full artifact SHA256 matched; installer not executed." +} diff --git a/docs/NATIVE_VERIFICATION.md b/docs/NATIVE_VERIFICATION.md new file mode 100644 index 0000000..676e791 --- /dev/null +++ b/docs/NATIVE_VERIFICATION.md @@ -0,0 +1,56 @@ +# 原生 Windows 验证协议 + +此协议验证真实宿主,而非只把 Windows 分支代码跑在 Linux。使用现有可信安装,无下载、无账号、无模型调用;不修改 WorkBuddy 安装目录或现有 profile。 + +## 前置证据 + +记录 WorkBuddy EXE 文件版本、bundled CLI package 版本和实际 hook event.version。当前固定适配 Windows WorkBuddy 5.9.3 / CLI 2.165.0;仅 package 静态版本不足以证明 hook 动态契约。 + +确认 `python.exe` 3.10+、`pwsh` 7 与可信 `node.exe` 路径。若厂商只提供 `resources/vendor/node.zip`,允许将已核实的该归档解压到新建临时测试目录,**不写回厂商安装目录、不安装软件、不改执行策略/沙箱设置**。应使用官方配套 Node;替代 Node 必须记录版本及兼容性限制。 + +## 合成测试 + +```powershell +Set-Location "$Repo\src\plugin" +& $Python -X utf8 -m unittest discover -s tests -v +Set-Location $Repo +& $Python -X utf8 -m unittest discover -s tests -v +``` + +Windows 必须实际运行 `test_powershell_real_parser_and_error_guard` 和 Windows 文件锁测试;不得把其跳过当通过。POSIX 特有测试在 Windows 跳过是预期。symlink 权限缺失需明确报告,而不是更改系统权限。 + +PowerShell 测试覆盖空格、单引号、`$`、`&`、反引号、分号、括号和非 ASCII 路径;最终 **pwsh 进程退出码**必须为 2,不能只证明 Python 返回 2。Python 返回 1、2 或解释器缺失都要映射为 2。 + +## 原生隔离回归 + +选择短的、全新的本地 NTFS 临时目录,避免借此修改系统长路径策略: + +```powershell +$Out = Join-Path $env:TEMP ('wb-smoke-' + [guid]::NewGuid().ToString('N').Substring(0,8)) +& $Python -X utf8 "$Repo\scripts\native_smoke.py" --node $Node --cli $Cli --output $Out +``` + +脚本拒绝已有输出目录;构造隔离 HOME、USERPROFILE、APPDATA、LOCALAPPDATA、profile 和 workspace,子进程环境只继承必要系统路径,不继承 API keys。源历史和数据库均为合成数据。 + +必须证明: + +- 官方 plugin validate / marketplace add / install / list 成功。 +- 实际 `UserPromptSubmit` 触发且版本匹配;统一命名空间的五个命令走本地 hook。 +- 选定边界新会话不含后续回复,源数据库行不变;不会写源 JSONL。 +- seed reasoning 原生 EOF resume/fork 保留;API duration 0,未触发登录/模型路径。 +- 项目 hook 重复安装仅一个路由入口,卸载仅去掉本工具入口,保留其它设置。 +- 操作后回执可核查;GUI 打开、真实模型效果不属于此自动化证明。 + +## 退出码丢输出压力门槛 + +额外重复至少五次独立 `style-new`,每次使用唯一 operation UUID。每次都应成功返回回执,并且没有 Authentication required、模型调用或付费请求。 + +在合成项目内,暂时把**整个 hook shell 复合命令**的 stdout/stderr 丢弃,实际宿主仍必须根据最终 shell 退出码 2 阻断。不能只重定向复合命令最后一个子句。随后恢复合成配置。 + +同样测试缺失 Python/缺失 handler,必须阻断;普通 prompt 和其它 namespace 在依赖完好时静默退出 0。缺少宿主 shell 本身不在插件可执行范围内,应作为部署阻断项,不标记通过。 + +保留合成 `result.json`、日志和测试文件 SHA256。测试失败先诊断,不修改真实账号、真实历史或系统安全配置,也不把部分通过写成 Windows 已完成。 + +## 云 CI + +普通 GitHub Actions 运行 Windows/Linux 的无宿主合成测试。原生 workflow(相关代码 push/PR 自动触发,也支持手动)已使用 `ci/workbuddy-windows-pin.json` 固定的官方 5.9.3.42398134 安装包。完整下载的 SHA256 与官方元数据吻合;格式确认为 NSIS-3 Unicode。`prepare_windows_runtime.ps1` 使用预装 7-Zip 静态提取 `$PLUGINSDIR/app-64.7z`,再提取 `resources/vendor/node.zip`,校验 Node 22.22.2 与 CLI package 2.165.0;从不运行安装器。不得用猜测链接、第三方镜像或未固定版本替代。workflow 存在不代表 Windows 已通过,须核查实际任务结果。 diff --git a/plugins/workbuddy-tools/.workbuddy-plugin/plugin.json b/plugins/workbuddy-tools/.workbuddy-plugin/plugin.json new file mode 100644 index 0000000..70cd183 --- /dev/null +++ b/plugins/workbuddy-tools/.workbuddy-plugin/plugin.json @@ -0,0 +1,8 @@ +{ + "name": "workbuddy-tools", + "version": "0.2.0", + "description": "Windows-first native conversation branching and opt-in reasoning seed tools", + "author": { + "name": "Local Conversation Tools" + } +} \ No newline at end of file diff --git a/plugins/workbuddy-tools/commands/branch.md b/plugins/workbuddy-tools/commands/branch.md new file mode 100644 index 0000000..64ad1ec --- /dev/null +++ b/plugins/workbuddy-tools/commands/branch.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 branch(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/plugins/workbuddy-tools/commands/points.md b/plugins/workbuddy-tools/commands/points.md new file mode 100644 index 0000000..6a827d3 --- /dev/null +++ b/plugins/workbuddy-tools/commands/points.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 points(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/plugins/workbuddy-tools/commands/recover.md b/plugins/workbuddy-tools/commands/recover.md new file mode 100644 index 0000000..8e4a3e5 --- /dev/null +++ b/plugins/workbuddy-tools/commands/recover.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 recover(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/plugins/workbuddy-tools/commands/status.md b/plugins/workbuddy-tools/commands/status.md new file mode 100644 index 0000000..23eb95f --- /dev/null +++ b/plugins/workbuddy-tools/commands/status.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 status(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/plugins/workbuddy-tools/commands/style-new.md b/plugins/workbuddy-tools/commands/style-new.md new file mode 100644 index 0000000..be0c2b5 --- /dev/null +++ b/plugins/workbuddy-tools/commands/style-new.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 style-new(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/plugins/workbuddy-tools/examples/minimal-seed.json b/plugins/workbuddy-tools/examples/minimal-seed.json new file mode 100644 index 0000000..924ab23 --- /dev/null +++ b/plugins/workbuddy-tools/examples/minimal-seed.json @@ -0,0 +1 @@ +{"schema":1,"messages":[{"role":"user","text":"请先说明结论,再列出你确实核验过的依据;不确定之处直接指出。"},{"role":"assistant","text":"我会将结论、已核验依据和不确定项分开表达。具体回答仍取决于后续任务与模型能力。"}]} diff --git a/plugins/workbuddy-tools/examples/we-need-demo.json b/plugins/workbuddy-tools/examples/we-need-demo.json new file mode 100644 index 0000000..e73cd66 --- /dev/null +++ b/plugins/workbuddy-tools/examples/we-need-demo.json @@ -0,0 +1 @@ +{"schema":1,"messages":[{"role":"user","text":"请直接回答问题,并区分已核实的事实和不确定项。"},{"role":"assistant","text":"我会先给出结论,再说明核验依据和仍不确定的部分。","reasoning":"We need to answer the question directly and verify the facts before making claims."}]} diff --git a/plugins/workbuddy-tools/hooks/dispatch.py b/plugins/workbuddy-tools/hooks/dispatch.py new file mode 100644 index 0000000..7d9de0b --- /dev/null +++ b/plugins/workbuddy-tools/hooks/dispatch.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Native UserPromptSubmit dispatcher: only exact namespaced slash commands.""" +from __future__ import annotations +import json, os, sys, uuid +if sys.version_info < (3,10): + print('{"decision":"block","reason":"conversation-tools requires Python 3.10+; install using a compatible interpreter"}') + raise SystemExit(2) +if hasattr(sys.stdout,'reconfigure'):sys.stdout.reconfigure(encoding='utf-8') +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from workbuddy_native.model import OperationError, uid +from workbuddy_native.engine import Engine +MANIFEST=json.loads((Path(__file__).resolve().parents[1]/'.workbuddy-plugin/plugin.json').read_text(encoding='utf-8')) +PREFIX='/'+MANIFEST['name']+':' +SUPPORTED={'workbuddy-branch':{'branch','points','recover','status'},'workbuddy-style':{'style-new','recover','status'}}.get(MANIFEST['name'],{'branch','points','style-new','recover','status'}) + +def dispatch(event: dict) -> dict | None: + prompt=event.get('prompt') + if not isinstance(prompt,str) or not prompt.startswith(PREFIX): return None + command,_,raw=prompt.partition(' ') + try: + if event.get('hook_event_name')!='UserPromptSubmit': raise OperationError('不支持的事件') + expected='2.165.0' if sys.platform=='win32' else '2.147.0' + if event.get('version')!=expected: raise OperationError('CLI 版本不匹配当前平台适配器,停止写入;需要 '+expected) + if command not in {PREFIX+n for n in SUPPORTED}: raise OperationError('未知命令') + args=json.loads(raw) if raw.strip() else {} + if not isinstance(args,dict): raise OperationError('参数必须是 JSON 对象') + cwd=Path(event['cwd']) + if not cwd.is_absolute() or not cwd.is_dir(): raise OperationError('当前项目目录无效') + session=uid(event['session_id']) + transcript=Path(event['transcript_path']) + if not transcript.is_absolute() or transcript.name!=session+'.jsonl' or transcript.parent.parent.name!='projects' or transcript.is_symlink(): raise OperationError('宿主历史路径无效') + profile=transcript.parent.parent.parent.resolve() + config_path=cwd/'.conversation-tools.json' + if config_path.is_symlink(): raise OperationError('配置文件不能是符号链接') + config=json.loads(config_path.read_text(encoding='utf-8')) + if set(config)!={'schema','cli_argv'} or config['schema']!=1: raise OperationError('配置结构不支持') + engine=Engine(profile,config['cli_argv'],profile/'conversation-tools-operations') + name=command[len(PREFIX):] + allowed={'branch':{'at','title','operation_id'},'points':set(),'style-new':{'seed','title','operation_id'},'recover':{'operation_id'},'status':set()}[name] + if set(args)-allowed: raise OperationError('存在未知参数') + if name=='points': result=engine.points(session,cwd) + elif name=='branch': + op=args.get('operation_id') or str(uuid.uuid5(uuid.NAMESPACE_URL,session+':'+str(event.get('generation_id',prompt)))) + result=engine.branch(session,args.get('at','latest'),args.get('title',''),op,cwd) + from workbuddy_native.registry import register + if (profile/'workbuddy.db').exists(): result=dict(result,desktop_registration=register(engine,result)) + elif name=='recover': + result=engine.recover(uid(args.get('operation_id'))) + if (profile/'workbuddy.db').exists(): + from workbuddy_native.registry import register + registration=register(engine,result); result=dict(result,desktop_registration=registration) + elif name=='style-new': + from workbuddy_native.style import create_style + op=args.get('operation_id') or str(uuid.uuid5(uuid.NAMESPACE_URL,session+':'+str(event.get('generation_id',prompt)))) + result=create_style(engine,session,cwd,args,op) + if (profile/'workbuddy.db').exists(): + from workbuddy_native.registry import register + result=dict(result,desktop_registration=register(engine,result)) + else: result={'profile':str(profile),'adapter':('Windows WorkBuddy 5.9.3 / CLI 2.165.0' if sys.platform=='win32' else 'Linux WorkBuddy 5.6.2 / CLI 2.147.0'),'style_default':'off','database_present':(profile/'workbuddy.db').exists()} + if isinstance(result,dict) and result.get('target'): + result=dict(result,open_uri='workbuddy://chat/'+uid(result['target']),gui_open_verified=False) + return {'decision':'block','reason':json.dumps({'conversation_tools':result},ensure_ascii=False)} + except Exception as exc: + return {'decision':'block','reason':'conversation-tools:'+(str(exc) if isinstance(exc,OperationError) else type(exc).__name__)+';没有向模型提交此命令。'} + +if __name__=='__main__': + try: + raw=sys.stdin.buffer.read(1024*1024+1) + if len(raw)>1024*1024: raise ValueError('hook input too large') + output=dispatch(json.loads(raw)) + if output is not None: + print(json.dumps(output,ensure_ascii=False),flush=True) + print(output['reason'],file=sys.stderr,flush=True) + raise SystemExit(2) # Native unconditional stop, even if host loses stdout on exit. + except Exception: + output={'decision':'block','reason':'conversation-tools:无效的宿主事件,已拒绝处理。'} + print(json.dumps(output,ensure_ascii=False),flush=True) + print(output['reason'],file=sys.stderr,flush=True) + raise SystemExit(2) diff --git a/plugins/workbuddy-tools/hooks/hooks.json b/plugins/workbuddy-tools/hooks/hooks.json new file mode 100644 index 0000000..bd0b542 --- /dev/null +++ b/plugins/workbuddy-tools/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{}} diff --git a/plugins/workbuddy-tools/hooks/router.py b/plugins/workbuddy-tools/hooks/router.py new file mode 100644 index 0000000..a777b51 --- /dev/null +++ b/plugins/workbuddy-tools/hooks/router.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Installed project router: exactly one host hook, argv-only namespace dispatch.""" +import json,subprocess,sys +from pathlib import Path +if hasattr(sys.stdout,'reconfigure'):sys.stdout.reconfigure(encoding='utf-8') +def block(reason): + message='WorkBuddy conversation tools: '+reason + print(json.dumps({'decision':'block','reason':message},ensure_ascii=False),flush=True) + print(message,file=sys.stderr,flush=True) +def main(): + raw=sys.stdin.buffer.read(1024*1024+1) + if len(raw)>1024*1024:raise ValueError('event too large') + event=json.loads(raw);prompt=event.get('prompt','') + if not isinstance(prompt,str) or not prompt.startswith('/'):return + namespace=prompt.split(':',1)[0][1:] + if namespace not in {'workbuddy-tools','workbuddy-branch','workbuddy-style','conversation-tools'}:return False + path=Path(__file__).with_name('conversation-tools-installed.json') + if path.is_symlink():raise ValueError('ownership is a symlink') + owners=json.loads(path.read_text(encoding='utf-8')) + if owners.get('schema')!=2:raise ValueError('unsupported router ownership') + owner=owners.get('plugins',{}).get(namespace) + if owner is None:raise ValueError('requested plugin is not installed in this project') + if not isinstance(owner,dict) or set(owner)!={'python','handler','shell'}:raise ValueError('invalid plugin owner') + for key in ('python','handler'): + p=Path(owner[key]) + if not p.is_absolute() or not p.is_file() or p.is_symlink():raise ValueError('missing or linked '+key) + result=subprocess.run([owner['python'],'-X','utf8',owner['handler']],input=raw,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,timeout=100,check=False) + if result.returncode not in {0,2}:raise ValueError('operation handler failed') + output=json.loads(result.stdout) + if not isinstance(output,dict) or output.get('decision')!='block' or not isinstance(output.get('reason'),str):raise ValueError('handler did not safely stop the prompt') + print(json.dumps(output,ensure_ascii=False),flush=True) + print(output['reason'],file=sys.stderr,flush=True) + return True +if __name__=='__main__': + try: + handled=main() + raise SystemExit(2 if handled else 0) + except Exception as exc: + block('refused; '+type(exc).__name__+'; prompt processing stopped') + raise SystemExit(2) diff --git a/plugins/workbuddy-tools/scripts/discover.py b/plugins/workbuddy-tools/scripts/discover.py new file mode 100644 index 0000000..57a5af7 --- /dev/null +++ b/plugins/workbuddy-tools/scripts/discover.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Read-only local runtime discovery; never executes a candidate or scans profiles.""" +import json,os,sys +from pathlib import Path +roots=[] +if os.environ.get('WORKBUDDY_INSTALL_DIR'):roots.append(Path(os.environ['WORKBUDDY_INSTALL_DIR'])) +if os.name=='nt': + for env in ('LOCALAPPDATA','ProgramFiles','ProgramFiles(x86)'): + if os.environ.get(env): + root=Path(os.environ[env]);roots.extend([root/'WorkBuddy',root/'Programs'/'WorkBuddy',root/'Tencent'/'WorkBuddy']) +else:roots.extend([Path('/opt/WorkBuddy'),Path('/opt/workbuddy')]) +results=[] +for root in dict.fromkeys(roots): + if not root.is_dir():continue + resources=root/'resources' + nodes=[resources/'runtime/node/node.exe',resources/'runtime/node/bin/node.exe',resources/'runtime/node/bin/node'] + clis=[resources/'app.asar.unpacked/cli/bin/codebuddy',resources/'app.asar.unpacked/cli/bin/codebuddy.js'] + vendor=resources/'vendor/node.zip' + if vendor.is_file():results.append({'install_root':str(root),'bundled_node_archive':str(vendor),'note':'Archive is not executed or extracted; provide a trusted node.exe explicitly.'}) + for node in nodes: + for cli in clis: + if node.is_file() and cli.is_file():results.append({'install_root':str(root),'node':str(node.resolve()),'cli':str(cli.resolve())}) +print(json.dumps({'python':sys.executable,'python_version':sys.version.split()[0],'python_supported':sys.version_info>=(3,10),'platform':sys.platform,'candidates':results,'next':'Verify the intended official installation; pass --cli and --node explicitly. Set WORKBUDDY_INSTALL_DIR if not found.'},ensure_ascii=True,indent=2)) diff --git a/plugins/workbuddy-tools/scripts/install.ps1 b/plugins/workbuddy-tools/scripts/install.ps1 new file mode 100644 index 0000000..2fd28b6 --- /dev/null +++ b/plugins/workbuddy-tools/scripts/install.ps1 @@ -0,0 +1,29 @@ +# No execution-policy changes or downloads. Invoke from a trusted PowerShell session. +param( + [Parameter(Mandatory=$true)][ValidateSet('install','uninstall','check')][string]$Action, + [Parameter(Mandatory=$true)][string]$Project, + [string]$Cli, + [string]$Node, + [string]$Python, + [ValidateSet('powershell','posix')][string]$HookShell='powershell' +) +$ErrorActionPreference='Stop' +$candidates=@() +if ($Python) { $candidates+=,@($Python) } +else { + if (Get-Command py -ErrorAction SilentlyContinue) { $candidates+=,@('py','-3') } + if (Get-Command python -ErrorAction SilentlyContinue) { $candidates+=,@('python') } +} +$chosen=$null +foreach ($candidate in $candidates) { + $exe=$candidate[0];$prefix=@($candidate | Select-Object -Skip 1) + & $exe @prefix -c 'import sys; sys.exit(0 if sys.version_info >= (3,10) else 1)' + if ($LASTEXITCODE -eq 0) { $chosen=$candidate;break } +} +if (-not $chosen) { throw 'Python 3.10+ not found. Provide -Python path to a trusted compatible python.exe. Nothing installed.' } +$exe=$chosen[0];$prefix=@($chosen | Select-Object -Skip 1) +$params=@('-X','utf8',(Join-Path $PSScriptRoot 'manage.py'),$Action,'--project',$Project,'--hook-shell',$HookShell) +if ($Cli) { $params+=@('--cli',$Cli) } +if ($Node) { $params+=@('--node',$Node) } +& $exe @prefix @params +if ($LASTEXITCODE -ne 0) { throw "Native project hook $Action failed; inspect the preceding diagnostic." } diff --git a/plugins/workbuddy-tools/scripts/manage.py b/plugins/workbuddy-tools/scripts/manage.py new file mode 100644 index 0000000..90398d5 --- /dev/null +++ b/plugins/workbuddy-tools/scripts/manage.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Merge only owned native hook. No trust, permissions, credentials or history edits.""" +import argparse,json,os,shlex,sys,shutil +if sys.version_info < (3,10): + raise SystemExit('conversation-tools requires Python 3.10+; no settings changed') +if hasattr(sys.stdout,'reconfigure'):sys.stdout.reconfigure(encoding='utf-8') +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from workbuddy_native.engine import atomic +from workbuddy_native.model import no_links +from workbuddy_native.platform import lock +ROOT=Path(__file__).resolve().parents[1] +PLUGIN=json.loads((ROOT/'.workbuddy-plugin/plugin.json').read_text(encoding='utf-8'))['name'] + +def hook_command(argv, shell): + if shell=='posix':return shlex.join(argv) + if shell=='powershell': + if any(any(c in a for c in '\r\n\0') for a in argv):raise ValueError('unsupported control characters in hook path') + return '& '+ ' '.join("'"+a.replace("'","''")+"'" for a in argv) + raise ValueError('unsupported native hook shell') + +def guarded_hook_command(argv,shell): + command=hook_command(argv,shell) + if shell=='powershell': + return "$ErrorActionPreference='Stop'; try { "+command+"; if ($LASTEXITCODE -eq 0) { exit 0 } else { exit 2 } } catch { exit 2 }" + if shell=='posix': + return 'if '+command+'; then exit 0; else exit 2; fi' + raise ValueError('unsupported hook shell') + +def configure(a,project,folder,settings,config): + snapshot=settings.read_bytes() if settings.exists() else None + current=json.loads(snapshot) if snapshot is not None else {} + if not isinstance(current,dict):raise ValueError('invalid project settings') + entries=current.get('hooks',{}).get('UserPromptSubmit',[]) + if not isinstance(entries,list):raise ValueError('invalid hooks array') + ownership=folder/'conversation-tools-installed.json';router=folder/'conversation-tools-router.py' + no_links(ownership);no_links(router) + owners=json.loads(ownership.read_text(encoding='utf-8')) if ownership.exists() else {'schema':2,'plugins':{},'hook':None} + if not isinstance(owners,dict):raise ValueError('invalid ownership') + if owners.get('schema')!=2: + # Uninstall the old exact owned entry, without executing/parsing its shell. + if a.action!='uninstall':raise ValueError('legacy hook layout: uninstall each old plugin first') + previous=owners.pop(PLUGIN,None) + entries=[e for e in entries if e!=previous] + if entries:current.setdefault('hooks',{})['UserPromptSubmit']=entries + elif 'hooks' in current:current['hooks'].pop('UserPromptSubmit',None) + if current.get('hooks')=={}:current.pop('hooks') + atomic(settings,json.dumps(current,ensure_ascii=False,indent=2).encode()) + if owners:atomic(ownership,json.dumps(owners,ensure_ascii=False,indent=2).encode()) + else:atomic(ownership,b'{"schema":2,"plugins":{},"hook":null}') + return + if not {'schema','plugins','hook'}<=set(owners) or set(owners)-{'schema','plugins','hook','stale_hooks'} or not isinstance(owners['plugins'],dict):raise ValueError('invalid ownership schema') + previous=owners['hook'];plugins=owners['plugins'] + stale=owners.get('stale_hooks',[]) + if not isinstance(stale,list):raise ValueError('invalid ownership recovery list') + old_hooks=stale+([previous] if previous else []) + if a.action=='check': + print(json.dumps({'project':str(project),'plugin':PLUGIN,'hook_installed':PLUGIN in plugins and previous in entries,'router_exists':router.is_file(),'engine_config_present':config.is_file(),'python':sys.version.split()[0],'python_executable':sys.executable,'platform':sys.platform,'hook_shell':a.hook_shell,'hook_shell_available':a.hook_shell!='powershell' or bool(shutil.which('pwsh'))},ensure_ascii=False));return + if a.action=='install': + if a.hook_shell=='powershell' and not shutil.which('pwsh'):raise ValueError('PowerShell 7 pwsh not found on PATH; no installation changes') + if not a.cli or not Path(a.cli).is_absolute() or not Path(a.cli).is_file():raise ValueError('--cli must be the official bundled CLI absolute path') + argv=[str(Path(a.cli).resolve())] + if a.node: + if not Path(a.node).is_absolute() or not Path(a.node).is_file():raise ValueError('invalid --node') + argv.insert(0,str(Path(a.node).resolve())) + if os.name=='nt' and Path(argv[0]).suffix.lower() not in {'.exe','.com'}:raise ValueError('Windows needs --node pointing to trusted node.exe, not a batch launcher') + planned={'schema':1,'cli_argv':argv} + if config.exists() and json.loads(config.read_text(encoding='utf-8'))!=planned:raise ValueError('existing CLI configuration differs; refusing overwrite') + atomic(config,json.dumps(planned,ensure_ascii=False,indent=2).encode()) + plugins[PLUGIN]={'python':str(Path(sys.executable).resolve(strict=True)),'handler':str(ROOT/'hooks/dispatch.py'),'shell':a.hook_shell} + atomic(router,(ROOT/'hooks/router.py').read_bytes()) + else:plugins.pop(PLUGIN,None) + # One shared project router avoids the actual host's multi-hook result bug. + entries=[e for e in entries if e not in old_hooks] + owned=None + if plugins: + chosen=plugins[sorted(plugins)[0]] + command=guarded_hook_command([chosen['python'],'-X','utf8',str(router)],chosen['shell']) + hook={'type':'command','command':command,'timeout':110} + if chosen['shell']=='powershell':hook['shell']='powershell' + owned={'hooks':[hook]};entries.append(owned) + owners['hook']=owned + if entries:current.setdefault('hooks',{})['UserPromptSubmit']=entries + elif 'hooks' in current:current['hooks'].pop('UserPromptSubmit',None) + if current.get('hooks')=={}:current.pop('hooks') + if settings.exists(): + backup=settings.with_name('settings.local.json.conversation-tools.backup') + if not backup.exists():atomic(backup,settings.read_bytes()) + if (settings.read_bytes() if settings.exists() else None)!=snapshot:raise ValueError('settings changed concurrently; refusing overwrite') + # Durable intent remembers old and new exact hooks until settings commit. + owners['stale_hooks']=old_hooks+([owned] if owned else []) + atomic(ownership,json.dumps(owners,ensure_ascii=False,indent=2).encode()) + atomic(settings,json.dumps(current,ensure_ascii=False,indent=2).encode()) + owners['stale_hooks']=[] + atomic(ownership,json.dumps(owners,ensure_ascii=False,indent=2).encode()) + print(json.dumps({'status':a.action+'ed','plugin':PLUGIN,'project':str(project),'history_deleted':False},ensure_ascii=False)) + +def main(): + p=argparse.ArgumentParser();p.add_argument('action',choices=['install','uninstall','check']);p.add_argument('--project',required=True);p.add_argument('--cli');p.add_argument('--node');p.add_argument('--hook-shell',choices=['powershell','posix'],default='powershell' if os.name=='nt' else 'posix');a=p.parse_args() + project=Path(a.project).resolve(strict=True) + if not project.is_dir():raise ValueError('project is not directory') + folder=project/'.codebuddy';settings=folder/'settings.local.json';config=project/'.conversation-tools.json' + for path in (folder,settings,config):no_links(path) + if a.action=='check':configure(a,project,folder,settings,config);return + folder.mkdir(exist_ok=True) + with lock(folder/'conversation-tools-install.lock'):configure(a,project,folder,settings,config) +if __name__=='__main__': + try:main() + except Exception as e:print('Refused: '+str(e),file=sys.stderr);sys.exit(1) diff --git a/plugins/workbuddy-tools/skills/conversation-tools/SKILL.md b/plugins/workbuddy-tools/skills/conversation-tools/SKILL.md new file mode 100644 index 0000000..3307898 --- /dev/null +++ b/plugins/workbuddy-tools/skills/conversation-tools/SKILL.md @@ -0,0 +1,16 @@ +--- +name: conversation-tools +description: 本地会话分支和用户显式选择的最小风格 seed 的使用说明。 +disable-model-invocation: true +user-invocable: true +allowed-tools: [] +--- +这是说明技能,不授权模型写入会话文件或数据库。 +执行操作必须使用项目原生 UserPromptSubmit hook 的固定命令: +- `/workbuddy-tools:points` 查看当前会话可用完整回复 ID。 +- `/workbuddy-tools:branch {"at":"latest","title":"分支名称"}` 或将 at 设为完整回复 UUID。 +- `/workbuddy-tools:style-new {"seed":"/绝对路径/minimal-seed.json","title":"新会话"}` +- `/workbuddy-tools:recover {"operation_id":"操作 UUID"}` +- `/workbuddy-tools:status` +参数是 JSON,不是 shell。不要把参数插入 shell,也不要替代 hook 调用任何写入工具。 +如果 hook 未生效,停止并提示运行 `scripts/manage.py check`;不要自动模仿此操作。 diff --git a/plugins/workbuddy-tools/workbuddy_native/__init__.py b/plugins/workbuddy-tools/workbuddy_native/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/workbuddy-tools/workbuddy_native/engine.py b/plugins/workbuddy-tools/workbuddy_native/engine.py new file mode 100644 index 0000000..f828fbd --- /dev/null +++ b/plugins/workbuddy-tools/workbuddy_native/engine.py @@ -0,0 +1,113 @@ +"""No model requests, no source writes, argv-only official CLI cloning.""" +from __future__ import annotations +import json, os, subprocess, time, uuid +from pathlib import Path +from typing import Any +from .model import OperationError, uid, digest, records, boundaries, find, no_links +from .platform import lock, fsync_directory, same_path + +def atomic(path: Path, data: bytes) -> None: + no_links(path) + tmp=path.with_name(path.name+'.tmp-'+str(uuid.uuid4())) + fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) + try: + with os.fdopen(fd,'wb') as f: f.write(data); f.flush(); os.fsync(f.fileno()) + os.replace(tmp,path) + fsync_directory(path.parent) + finally: + if tmp.exists(): tmp.unlink() + +def encode(rows: list[dict]) -> bytes: return ''.join(json.dumps(r,ensure_ascii=False,separators=(',',':'))+'\n' for r in rows).encode() +def save(path: Path, data: dict) -> None: atomic(path,json.dumps(data,ensure_ascii=False,indent=2).encode()) + +class Engine: + def __init__(self, profile: Path, cli: list[str], state: Path): + no_links(profile); no_links(state) + self.profile=profile.resolve(); self.cli=cli; self.state=state + if not cli or any(not isinstance(s,str) or '\0' in s for s in cli): raise OperationError('CLI argv 配置无效') + state.mkdir(parents=True,exist_ok=True,mode=0o700) + if state.is_symlink(): raise OperationError('状态目录不能是符号链接') + + def points(self, session: str, cwd: Path) -> list[dict]: + _,_,rows=self.source(session,cwd) + return [{'message_id':r['id'],'turn':n,'preview':__import__('workbuddy_native.model',fromlist=['visible']).visible(r)[:180]} for n,(_,r) in enumerate(boundaries(rows),1)] + + def source(self, session: str, cwd: Path): + path=find(self.profile,session); data=path.read_bytes(); rows=records(data) + dirs=[r['cwd'] for r in rows if r.get('cwd')] + if not dirs or not all(same_path(d,cwd) for d in dirs) or not cwd.is_dir(): raise OperationError('源会话与当前项目目录不一致') + return path,data,rows + + def branch(self, session: str, boundary: str, title: str, operation: str, cwd: Path) -> dict: + uid(session); uid(operation) + if not isinstance(title,str) or len(title)>120 or any(ord(c)<32 for c in title): raise OperationError('标题应为 0–120 个普通字符') + source,data,rows=self.source(session,cwd) + points=boundaries(rows) + if not points: raise OperationError('没有已完成且工具闭合的回复') + if boundary=='latest': boundary=points[-1][1]['id'] + uid(boundary) + ends={r['id']:i for i,r in points} + if boundary not in ends: raise OperationError('请选择已完成且工具闭合的回复 ID') + request={'source':session,'boundary':boundary,'title_sha256':digest(title.encode()),'cwd':str(cwd.resolve())} + lock_path=self.state/(operation+'.lock') + no_links(lock_path); no_links(self.state/(operation+'.json')) + with lock(lock_path): + journal=self.state/(operation+'.json') + if journal.exists(): + old=json.loads(journal.read_text(encoding='utf-8')) + if old.get('request')!=request: raise OperationError('操作 ID 已用于不同请求') + if old.get('status')=='completed': + target=find(self.profile,old['target']) + if digest(target.read_bytes())!=old['target_sha256']: raise OperationError('目标已变化;禁止重复执行') + return old + raise OperationError('操作未确定;用 recover 命令核查,禁止再次克隆') + target_id=str(uuid.uuid4()); target=source.with_name(target_id+'.jsonl') + if target.exists(): raise OperationError('新目标冲突') + receipt={'operation':operation,'request':request,'target':target_id,'source_sha256':digest(data),'source_size':len(data),'status':'started','started_at':time.time()} + save(journal,receipt) + try: + env=dict(os.environ); env.update(CODEBUDDY_CONFIG_DIR=str(self.profile),WORKBUDDY_CONFIG_DIR=str(self.profile),DISABLE_TELEMETRY='1') + # The verified Windows distribution ships only the lite-WB bundle. + selected='CODEBUDDY_FORCE_LITE_WB_BUNDLE' if os.name=='nt' else 'CODEBUDDY_FORCE_HEADLESS_BUNDLE' + other='CODEBUDDY_FORCE_HEADLESS_BUNDLE' if os.name=='nt' else 'CODEBUDDY_FORCE_LITE_WB_BUNDLE' + env[selected]='1'; env.pop(other,None) + for k in ('CODEBUDDY_PROJECT_CONFIG_DIR','OTEL_LOG_RAW_API_BODIES'): env.pop(k,None) + run=subprocess.run(self.cli+['--print','--input-format','stream-json','--output-format','stream-json','--resume',session,'--fork-session','--session-id',target_id,'--resume-session-at',boundary],cwd=cwd,env=env,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=75,check=False,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0) if os.name=='nt' else 0) + receipt['cli_exit_code']=run.returncode + if run.returncode: raise OperationError('官方 CLI 克隆失败') + if source.read_bytes()!=data: raise OperationError('宿主更新了源历史;停止新分支提交') + if find(self.profile,target_id)!=target: raise OperationError('CLI 输出目录不匹配') + clone_data=target.read_bytes(); clone_rows=records(clone_data); clones={r['id']:r for r in clone_rows if r.get('id')} + for row in rows: + if not row.get('id') or row['type']=='session-meta': continue + clone=clones.get(row['id']) + if clone is None or any(clone.get(k)!=row.get(k) for k in ('type','role','content','callId','call_id','name','arguments','output','parentId','logicalParentId')): raise OperationError('CLI 克隆契约变化') + prefix=rows[:ends[boundary]+1]; ids={r.get('id') for r in prefix if r.get('id')} + final=[r for r in clone_rows if r['type']=='session-meta'] + for row in prefix: + if row['type']=='session-meta': continue + if any(row.get(k) and row[k] not in ids for k in ('parentId','logicalParentId')): raise OperationError('悬空父消息') + r=dict(clones[row['id']]) if row.get('id') else dict(row) + if 'sessionId' in r:r['sessionId']=target_id + final.append(r) + if title: final.append({'type':'custom-title','id':str(uuid.uuid4()),'customTitle':title,'sessionId':target_id}) + final_data=encode(final) + receipt.update(status='prepared',target_sha256=digest(final_data),clone_sha256=digest(clone_data)) + save(journal,receipt) + if source.read_bytes()!=data or target.read_bytes()!=clone_data: raise OperationError('提交前源或目标发生变化') + atomic(target,final_data) + receipt.update(status='completed',finished_at=time.time()); save(journal,receipt) + return receipt + except Exception as exc: + receipt['error_type']=type(exc).__name__; save(journal,receipt) + raise OperationError(f'操作未完成,保留诊断记录:{operation};{exc if isinstance(exc,OperationError) else type(exc).__name__}') from exc + + def recover(self, operation: str) -> dict: + uid(operation); journal=self.state/(operation+'.json') + no_links(journal); no_links(self.state/(operation+'.lock')) + with lock(self.state/(operation+'.lock')): + r=json.loads(journal.read_text(encoding='utf-8')); target=find(self.profile,r['target']) + # Recovery never rewrites a conversation; final atomic write may have succeeded before receipt save. + if r.get('status') in {'prepared','completed'} and digest(target.read_bytes())==r.get('target_sha256'): + r.update(status='completed',recovered_at=time.time()); save(journal,r); return r + raise OperationError('目标未达到已准备哈希;保留新分支待人工核查,不自动删除或重新克隆') diff --git a/plugins/workbuddy-tools/workbuddy_native/linux-sessions-columns.json b/plugins/workbuddy-tools/workbuddy_native/linux-sessions-columns.json new file mode 100644 index 0000000..5400404 --- /dev/null +++ b/plugins/workbuddy-tools/workbuddy_native/linux-sessions-columns.json @@ -0,0 +1,322 @@ +[ + { + "cid": 0, + "name": "id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "cid": 1, + "name": "cwd", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 2, + "name": "user_id", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 3, + "name": "title", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 4, + "name": "custom_title", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 5, + "name": "status", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'Pending'", + "pk": 0 + }, + { + "cid": 6, + "name": "created_at", + "type": "INTEGER", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 7, + "name": "updated_at", + "type": "INTEGER", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 8, + "name": "last_activity_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 9, + "name": "deleted_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 10, + "name": "is_playground", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "cid": 11, + "name": "source_mode", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 12, + "name": "is_background_automation", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 13, + "name": "mode", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 14, + "name": "model", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 15, + "name": "expert_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 16, + "name": "expert_locale", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 17, + "name": "expert_runtime_identity", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 18, + "name": "expert_marketplace", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 19, + "name": "permission_mode", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 20, + "name": "use_sandbox_cli", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 21, + "name": "project_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 22, + "name": "plugin_context_json", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 23, + "name": "addon_selection", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 24, + "name": "session_settings", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 25, + "name": "last_user_prompt_expert_selection", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 26, + "name": "context_window", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 27, + "name": "buddy_snapshot_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 28, + "name": "buddy_binding_json", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 29, + "name": "thought_level", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 30, + "name": "transport", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'local'", + "pk": 0 + }, + { + "cid": 31, + "name": "conversation_origin", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 32, + "name": "visibility", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 33, + "name": "group_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 34, + "name": "group_title", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 35, + "name": "agent_dirty", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 36, + "name": "agent_dirty_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 37, + "name": "agent_last_synced", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 38, + "name": "verified_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 39, + "name": "unread", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + } +] \ No newline at end of file diff --git a/plugins/workbuddy-tools/workbuddy_native/model.py b/plugins/workbuddy-tools/workbuddy_native/model.py new file mode 100644 index 0000000..df1d2b8 --- /dev/null +++ b/plugins/workbuddy-tools/workbuddy_native/model.py @@ -0,0 +1,88 @@ +"""Conservative adapter for WorkBuddy 5.6.2 / bundled CLI 2.147.0 JSONL.""" +from __future__ import annotations +import json, re, hashlib +from pathlib import Path +from typing import Any + +class OperationError(RuntimeError): pass +UUID = re.compile(r'^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$') +KINDS = {'message','reasoning','function_call','function_call_result','function_call_output','file-history-snapshot','session-meta','ai-title','custom-title','topic'} +def uid(value: Any) -> str: + if not isinstance(value,str) or not UUID.fullmatch(value): raise OperationError('需要小写 UUID') + return value + +def digest(data: bytes) -> str: return hashlib.sha256(data).hexdigest() +def records(data: bytes) -> list[dict[str,Any]]: + if len(data)>32*1024*1024: raise OperationError('历史大于 32 MiB,拒绝自动处理') + result=[]; ids=set() + try: + for line in data.decode('utf-8-sig').splitlines(): + if not line.strip(): continue + row=json.loads(line) + if not isinstance(row,dict) or row.get('type') not in KINDS: raise OperationError('未知历史结构,拒绝猜测适配') + if row.get('id'): + uid(row['id']) + if row['id'] in ids: raise OperationError('重复消息 ID') + ids.add(row['id']) + if row.get('sessionId'): uid(row['sessionId']) + if row.get('subagentInvocations') or (row.get('providerData') or {}).get('toolResult',{}).get('subAgent') is not None: raise OperationError('尚不支持子代理历史图') + result.append(row) + except (ValueError,UnicodeError,AttributeError,TypeError) as exc: raise OperationError('无效历史 JSONL') from exc + if not result: raise OperationError('历史为空') + return result + +def visible(row: dict) -> str: + c=row.get('content',[]) + if isinstance(c,str): return c.strip() + if not isinstance(c,list): raise OperationError('未知消息内容结构') + return '\n'.join(x['text'] for x in c if isinstance(x,dict) and x.get('type') in {'text','input_text','output_text'} and isinstance(x.get('text'),str)).strip() + +def boundaries(rows: list[dict]) -> list[tuple[int,dict]]: + pending=set(); seen=set(); candidates=[]; candidate=None; user_seen=False + for index,row in enumerate(rows): + kind=row['type']; content=row.get('content',[]) + if kind=='message' and row.get('role')=='user' and visible(row): + if candidate is not None and not pending: candidates.append(candidate) + candidate=None; user_seen=True + if kind=='reasoning': candidate=None + calls=[]; results=[] + if kind=='function_call': calls.append(row.get('callId') or row.get('call_id')) + if kind in {'function_call_result','function_call_output'}: results.append(row.get('callId') or row.get('call_id')) + for item in content if isinstance(content,list) else []: + if not isinstance(item,dict): raise OperationError('未知消息内容项') + if item.get('type')=='tool_use': calls.append(item.get('id')) + if item.get('type')=='tool_result': results.append(item.get('tool_use_id')) + for call in calls: + if not isinstance(call,str) or not call or call in seen: raise OperationError('工具 ID 缺失或重复') + seen.add(call); pending.add(call); candidate=None + for call in results: + if call not in pending: raise OperationError('未匹配的工具结果') + pending.remove(call) + # Hook/auth skipRun output is not a completed model turn. + if kind=='message' and row.get('role')=='assistant': + candidate=None + if user_seen and row.get('status')=='completed' and not pending and visible(row) and not (row.get('providerData') or {}).get('skipRun'): + uid(row.get('id')); candidate=(index,row) + if candidate is not None and not pending: candidates.append(candidate) + return candidates + +def no_links(path: Path) -> None: + if str(path).startswith('\\\\'): raise OperationError('不支持 UNC/网络共享路径,请使用本地磁盘') + for p in (path,*path.parents): + if p.is_symlink(): raise OperationError('路径含符号链接,拒绝写入') + try: + if getattr(p.lstat(),'st_file_attributes',0)&0x400: raise OperationError('路径含 Windows reparse point/junction,拒绝写入') + except FileNotFoundError: pass + +def inside(path: Path, root: Path) -> Path: + no_links(path) + if path.is_symlink() or not path.is_file(): raise OperationError('文件不存在或是符号链接') + resolved=path.resolve() + if root.resolve() not in resolved.parents: raise OperationError('路径不在配置目录内') + return resolved + +def find(profile: Path, session: str) -> Path: + no_links(profile/'projects') + matches=list((profile/'projects').glob(f'*/{uid(session)}.jsonl')) + if len(matches)!=1: raise OperationError('会话不存在或重复') + return inside(matches[0],profile/'projects') diff --git a/plugins/workbuddy-tools/workbuddy_native/platform.py b/plugins/workbuddy-tools/workbuddy_native/platform.py new file mode 100644 index 0000000..d91d5c0 --- /dev/null +++ b/plugins/workbuddy-tools/workbuddy_native/platform.py @@ -0,0 +1,69 @@ +"""Small stdlib-only OS boundary; no application or profile mutations.""" +from __future__ import annotations +from contextlib import contextmanager +import errno +import os +from pathlib import Path +from typing import Iterator, BinaryIO + +class LockBusy(BlockingIOError): + """The operation is already locked by this or another process.""" + +@contextmanager +def lock(path: Path) -> Iterator[BinaryIO]: + """Acquire one nonblocking exclusive lock; callers validate path containment. + + Lock files are persistent, not deleted on unlock (unlinking permits competing + locks on different inodes). Windows locks exactly byte zero on every path. + """ + path=Path(path) + if str(path).startswith('\\\\'): raise OSError('UNC/network lock paths are unsupported') + for candidate in (path,*path.parents): + if candidate.is_symlink(): raise OSError('Lock path contains a symbolic link') + try: + # FILE_ATTRIBUTE_REPARSE_POINT also covers junctions on Python 3.10/3.11. + if getattr(candidate.lstat(),'st_file_attributes',0)&0x400: + raise OSError('Lock path contains a Windows reparse point/junction') + except FileNotFoundError: pass + fd=os.open(path,os.O_RDWR|os.O_CREAT|getattr(os,'O_NOFOLLOW',0),0o600) + with os.fdopen(fd,'r+b',buffering=0) as stream: + acquired=False + try: + if os.name=='nt': + import msvcrt + if os.fstat(stream.fileno()).st_size==0: + stream.write(b'\0'); stream.flush() + stream.seek(0) + try: msvcrt.locking(stream.fileno(),msvcrt.LK_NBLCK,1) + except OSError as exc: + if exc.errno in {errno.EACCES,errno.EAGAIN,errno.EDEADLK} or getattr(exc,'winerror',None) in {33,36}: + raise LockBusy('Operation is already running') from exc + raise + else: + import fcntl + try: fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError as exc: raise LockBusy('Operation is already running') from exc + acquired=True + yield stream + finally: + if acquired: + if os.name=='nt': + import msvcrt + stream.seek(0); msvcrt.locking(stream.fileno(),msvcrt.LK_UNLCK,1) + else: + import fcntl + fcntl.flock(stream,fcntl.LOCK_UN) + +def fsync_directory(path: Path) -> None: + """Flush rename metadata on POSIX; directory handles are not portable on Win.""" + if os.name=='nt': return + fd=os.open(path,os.O_RDONLY|getattr(os,'O_DIRECTORY',0)) + try: os.fsync(fd) + finally: os.close(fd) + +def same_path(left: str | Path, right: str | Path) -> bool: + """Resolved path identity with OS-native case rules, not string casefold.""" + a=str(Path(left).resolve()); b=str(Path(right).resolve()) + if Path(a).exists() and Path(b).exists(): + return os.path.samefile(a,b) + return os.path.normcase(a)==os.path.normcase(b) if os.name=='nt' else a==b diff --git a/plugins/workbuddy-tools/workbuddy_native/registry.py b/plugins/workbuddy-tools/workbuddy_native/registry.py new file mode 100644 index 0000000..6ffb8c1 --- /dev/null +++ b/plugins/workbuddy-tools/workbuddy_native/registry.py @@ -0,0 +1,157 @@ +"""Insert-only desktop discovery adapter. No schema migrations or source updates.""" +from __future__ import annotations +import json, sqlite3, time +from contextlib import contextmanager +from .platform import lock, LockBusy, same_path +from pathlib import Path +from typing import TYPE_CHECKING +from .model import OperationError, uid, digest, find, records, no_links +from .engine import save +if TYPE_CHECKING: + from .engine import Engine + +_REQUIRED = {"id", "cwd", "user_id", "title", "custom_title", "status", "created_at", + "updated_at", "deleted_at", "transport", "is_playground", "unread"} +_COPY = ("mode", "model", "project_id", "source_mode") +_NEVER_COPY = {"permission_mode", "use_sandbox_cli", "plugin_context_json", "buddy_snapshot_id", "buddy_binding_json", + "expert_id", "expert_locale", "expert_runtime_identity", "expert_marketplace"} +_KNOWN_COLUMNS = _REQUIRED | set(_COPY) | {"last_activity_at", "is_background_automation", "expert_id", + "expert_locale", "expert_runtime_identity", "expert_marketplace", "permission_mode", "use_sandbox_cli", + "plugin_context_json", "last_user_prompt_expert_selection", "context_window", "addon_selection", + "session_settings", "thought_level", "buddy_snapshot_id", "buddy_binding_json", "conversation_origin", + "visibility", "group_id", "group_title", "agent_dirty", "agent_dirty_at", "agent_last_synced", "verified_at"} + + +class RegistryError(OperationError): pass + +def safe_path(path: Path) -> None: + try: no_links(path) + except OperationError as exc: raise RegistryError(str(exc)) from exc + +@contextmanager +def registry_lock(path: Path): + try: + with lock(path) as handle: yield handle + except LockBusy as exc: raise RegistryError('桌面登记正在执行') from exc + +def rowhash(row) -> str: + return digest(json.dumps(dict(row),ensure_ascii=False,sort_keys=True,separators=(",", ":")).encode()) + +def schema(db: sqlite3.Connection, fields: set[str]) -> set[str]: + extended=db.execute("PRAGMA table_xinfo(sessions)").fetchall() + if any(r[6] for r in extended): raise RegistryError("未知隐藏或生成字段;拒绝写入") + columns=[tuple(r[:6]) for r in extended] + names={r[1] for r in columns} + expected=json.loads(Path(__file__).with_name('linux-sessions-columns.json').read_text(encoding='utf-8')) + actual=[dict(zip(('cid','name','type','notnull','dflt_value','pk'),r)) for r in columns] + if actual!=expected: raise RegistryError('桌面 schema 不匹配已核对的 40 列适配器;拒绝写入') + if not _REQUIRED <= names or not names <= _KNOWN_COLUMNS: + raise RegistryError("未知桌面数据库结构;拒绝写入") + if [r[1] for r in columns if r[5]] != ['id']: + raise RegistryError("sessions.id 主键不匹配") + for r in columns: + if r[1] in _NEVER_COPY and r[4] is not None and str(r[4]).strip().upper()!='NULL': + raise RegistryError("安全字段具有未核对默认值") + if r[3] and r[4] is None and r[1] not in fields: + raise RegistryError("未处理的必填字段") + if db.execute("SELECT 1 FROM sqlite_master WHERE type='trigger' AND tbl_name='sessions'").fetchone() or db.execute("PRAGMA foreign_key_list(sessions)").fetchall(): + raise RegistryError("sessions 存在触发器或外键;拒绝写入") + return names + +def source_ok(row, cwd: str) -> None: + if row is None or not row['user_id'] or row['deleted_at'] is not None or row['transport']!='local' or row['is_playground']!=0: + raise RegistryError("源桌面会话不是有效本地普通会话") + if not row['cwd'] or not same_path(row['cwd'],cwd): + raise RegistryError("桌面源会话工作目录不一致") + +def register(engine: Engine, receipt: dict) -> dict: + """Insert metadata for one verified branch; absent DB is an explicit CLI-only result. + + Crash after COMMIT is recovered by matching the precommitted insertion digest. + An uncertain absent row is not reinserted automatically. + """ + operation=uid(receipt.get('operation')); target_id=uid(receipt.get('target')) + request=receipt.get('request',{}); source_id=uid(request.get('source')) + if source_id==target_id: raise RegistryError("源和目标不能相同") + journal=engine.state/(operation+'.json') + safe_path(journal) + if journal.is_symlink() or not journal.is_file(): raise RegistryError("缺少操作记录") + stored=json.loads(journal.read_text(encoding='utf-8')) + for key in ('operation','request','target','source_sha256','source_size','target_sha256','status'): + if stored.get(key)!=receipt.get(key): raise RegistryError("操作记录与结果不一致") + if stored.get('status')!='completed': raise RegistryError("分支尚未完成") + database=engine.profile/'workbuddy.db' + if not database.exists(): return {'status':'cli_only','reason':'desktop_database_absent','target':target_id} + safe_path(database) + for suffix in ('-wal','-shm','-journal'): safe_path(database.with_name(database.name+suffix)) + if database.is_symlink() or not database.is_file(): raise RegistryError("数据库不是普通本地文件") + source=find(engine.profile,source_id); target=find(engine.profile,target_id) + if not same_path(source.parent,target.parent): raise RegistryError("新分支目录不一致") + source_data=source.read_bytes(); source_hash=digest(source_data); target_hash=digest(target.read_bytes()) + size=stored.get('source_size',len(source_data)) + if type(size) is not int or not 0 dict: + uid(operation) + seed_arg=args.get('seed') + if not isinstance(seed_arg,str) or not Path(seed_arg).is_absolute(): raise OperationError('seed 必须是用户指定的本地绝对路径') + seed=Path(seed_arg); no_links(seed) + if seed.is_symlink() or not seed.is_file() or seed.stat().st_size>16384: raise OperationError('seed 必须是小于 16 KiB 的普通 JSON 文件') + data=seed.read_bytes(); spec=json.loads(data) + if not isinstance(spec,dict) or set(spec)!={'schema','messages'} or type(spec['schema']) is not int or spec['schema']!=1: raise OperationError('seed 结构应为 schema:1 和 messages') + messages=spec['messages'] + if not isinstance(messages,list) or len(messages) not in {2,4}: raise OperationError('seed 仅接受 1–2 组最小问答') + for i,m in enumerate(messages): + if not isinstance(m,dict) or set(m) not in ({'role','text'},{'role','text','reasoning'}) or m['role']!=('user' if i%2==0 else 'assistant') or not isinstance(m['text'],str) or not 1<=len(m['text'])<=2000 or '\0' in m['text']: raise OperationError('seed 消息格式或长度不支持') + if 'reasoning' in m and (m['role']!='assistant' or not isinstance(m['reasoning'],str) or not 1<=len(m['reasoning'])<=4000 or '\0' in m['reasoning']): raise OperationError('reasoning 仅允许 assistant 的 1–4000 字纯文本') + title=args.get('title','') + if not isinstance(title,str) or len(title)>120 or any(ord(c)<32 for c in title): raise OperationError('标题无效') + source,source_data,_=engine.source(session,cwd) + request={'source':session,'boundary':'style-seed','title_sha256':digest(title.encode()),'cwd':str(cwd.resolve()),'seed_sha256':digest(data)} + journal=engine.state/(operation+'.json') + no_links(journal); no_links(engine.state/(operation+'.lock')) + with lock(engine.state/(operation+'.lock')): + if journal.exists(): + old=json.loads(journal.read_text(encoding='utf-8')) + if old.get('request')!=request: raise OperationError('操作 ID 已用于另一请求') + if old.get('status')=='completed' and digest(find(engine.profile,old['target']).read_bytes())==old.get('target_sha256'): return old + raise OperationError('已有操作需 recover 核查') + sid=str(uuid.uuid4()); target=source.with_name(sid+'.jsonl'); rows=[]; parent=None + for i,m in enumerate(messages): + if m.get('reasoning'): + rid=str(uuid.uuid4()); reason={'type':'reasoning','id':rid,'parentId':parent,'sessionId':sid,'cwd':str(cwd.resolve()),'timestamp':int(time.time()*1000)+i,'content':[],'rawContent':[{'type':'text','text':m['reasoning']}]} + rows.append(reason); parent=rid + mid=str(uuid.uuid4()); row={'id':mid,'timestamp':int(time.time()*1000)+i,'type':'message','role':m['role'],'content':[{'type':'input_text' if i%2==0 else 'output_text','text':m['text']}],'sessionId':sid,'cwd':str(cwd.resolve())} + if parent: row['parentId']=parent + if i%2: row['status']='completed' + rows.append(row); parent=mid + if title:rows.append({'type':'custom-title','id':str(uuid.uuid4()),'sessionId':sid,'customTitle':title}) + wire=encode(rows) + receipt={'operation':operation,'request':request,'target':sid,'source_sha256':digest(source_data),'source_size':len(source_data),'target_sha256':digest(wire),'status':'prepared','kind':'style-new','style_default':'off','no_prompt_submitted':True} + save(journal,receipt) + if source.read_bytes()!=source_data or seed.read_bytes()!=data: raise OperationError('来源或 seed 已变化') + # Atomic no-clobber publication, never overwrite an existing UUID. + temp=target.with_name(target.name+'.'+operation+'.tmp'); atomic(temp,wire) + try: + os.link(temp,target) + fsync_directory(target.parent) + finally: temp.unlink(missing_ok=True) + receipt['status']='completed'; save(journal,receipt) + return receipt diff --git a/scripts/build_plugins.py b/scripts/build_plugins.py new file mode 100644 index 0000000..e06354e --- /dev/null +++ b/scripts/build_plugins.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Deterministic source-copy build; no network, dependencies or vendor binaries.""" +import json,shutil,sys +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +SOURCE=ROOT/'src/plugin' +sys.path.insert(0,str(SOURCE)) +from workbuddy_native.model import no_links +PLUGINS={'workbuddy-tools':{'branch','points','style-new','recover','status'}} +def build(): + for old_name in ('workbuddy-branch','workbuddy-style'): + old=ROOT/'plugins'/old_name + if old.exists(): + no_links(old) + manifest=old/'.workbuddy-plugin/plugin.json' + if not manifest.is_file() or json.loads(manifest.read_text(encoding='utf-8')).get('name')!=old_name:raise RuntimeError('Unowned old plugin directory') + shutil.rmtree(old) + for name,commands in PLUGINS.items(): + target=ROOT/'plugins'/name + no_links(target) + if target.exists(): + manifest_path=target/'.workbuddy-plugin/plugin.json' + if target.is_symlink() or not manifest_path.is_file() or json.loads(manifest_path.read_text(encoding='utf-8')).get('name')!=name: + raise RuntimeError('Refuse to replace a directory not owned by this plugin build: '+str(target)) + shutil.rmtree(target) + target.mkdir(parents=True,exist_ok=True) + shutil.copytree(SOURCE,target,dirs_exist_ok=True,ignore=shutil.ignore_patterns('__pycache__','*.pyc','tests','README.zh-CN.md')) + manifest=json.loads((target/'.workbuddy-plugin/plugin.json').read_text(encoding='utf-8'));manifest.update(name=name,version='0.2.0',description='Windows-first native conversation branching and opt-in reasoning seed tools') + (target/'.workbuddy-plugin/plugin.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8') + for command in (target/'commands').glob('*.md'): + if command.stem not in commands:command.unlink() + skill=target/'skills/conversation-tools/SKILL.md' + text=skill.read_text(encoding='utf-8').replace('/conversation-tools:',f'/{name}:') + lines=[line for line in text.splitlines() if not any(f'/{name}:{command}' in line for command in {'branch','points','style-new','recover','status'}-commands)] + skill.write_text('\n'.join(lines)+'\n',encoding='utf-8') + marketplace={'name':'workbuddy-plugins','owner':{'name':'WorkBuddy Conversation Tools'},'plugins':[{'name':name,'source':'./plugins/'+name,'version':'0.2.0'} for name in PLUGINS]} + (ROOT/'.workbuddy-plugin/marketplace.json').write_text(json.dumps(marketplace,ensure_ascii=False,indent=2),encoding='utf-8') +if __name__=='__main__':build() diff --git a/scripts/native_smoke.py b/scripts/native_smoke.py new file mode 100644 index 0000000..7687917 --- /dev/null +++ b/scripts/native_smoke.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Opt-in actual-host smoke using ONLY a new synthetic HOME/profile/workspace. +No installer download, real credentials, model prompt or existing profile reads. +""" +import argparse,json,os,re,sqlite3,subprocess,sys,uuid,importlib.util +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +def main(): + p=argparse.ArgumentParser();p.add_argument('--node',required=True);p.add_argument('--cli',required=True);p.add_argument('--output',required=True);a=p.parse_args() + node=Path(a.node).resolve(strict=True);cli=Path(a.cli).resolve(strict=True);out=Path(a.output).absolute() + out.mkdir(parents=True,exist_ok=False) + cwd=out/'workspace';home=out/'home';profile=home/'.workbuddy';logs=out/'logs' + for d in (cwd,profile,logs,out/'tmp'):d.mkdir(parents=True,exist_ok=True) + env={k:os.environ[k] for k in ('PATH','SystemRoot','SYSTEMROOT','WINDIR','COMSPEC','PATHEXT') if k in os.environ} + env.update(HOME=str(home),USERPROFILE=str(home),APPDATA=str(home/'AppData/Roaming'),LOCALAPPDATA=str(home/'AppData/Local'),TEMP=str(out/'tmp'),TMP=str(out/'tmp'),CODEBUDDY_CONFIG_DIR=str(profile),WORKBUDDY_CONFIG_DIR=str(profile),CODEBUDDY_FORCE_HEADLESS_BUNDLE='1',DISABLE_TELEMETRY='1',DISABLE_GALILEO='1',PYTHONUTF8='1') + if os.name=='nt': + env.pop('CODEBUDDY_FORCE_HEADLESS_BUNDLE',None);env['CODEBUDDY_FORCE_LITE_WB_BUNDLE']='1' + def run(label,args,stdin=None): + try: + r=subprocess.run([str(node),str(cli),*args],cwd=cwd,env=env,input=stdin,capture_output=True,text=True,encoding='utf-8',timeout=120) + except subprocess.TimeoutExpired as exc: + as_text=lambda value:value.decode('utf-8','replace') if isinstance(value,bytes) else (value or '') + (logs/(label+'.txt')).write_text(as_text(exc.stdout)+'\nSTDERR\n'+as_text(exc.stderr)+'\nTIMEOUT: 120 seconds',encoding='utf-8') + raise RuntimeError(label+' timed out; partial synthetic diagnostics retained') from exc + (logs/(label+'.txt')).write_text(r.stdout+'\nSTDERR\n'+r.stderr,encoding='utf-8') + if r.returncode:raise RuntimeError(label+' failed; inspect synthetic logs') + return r.stdout + for name in ('workbuddy-tools',):run('validate-'+name,['plugin','validate',str(ROOT/'plugins'/name)]) + run('marketplace',['plugin','marketplace','add',str(ROOT)]) + for name in ('workbuddy-tools',): + run('install-'+name,['plugin','install',name+'@workbuddy-plugins']) + r=subprocess.run([sys.executable,'-X','utf8',str(ROOT/'plugins'/name/'scripts/manage.py'),'install','--project',str(cwd),'--cli',str(cli),'--node',str(node)],env=env,capture_output=True,text=True,encoding='utf-8',timeout=20) + if r.returncode:raise RuntimeError('Project hook installation failed: '+r.stderr) + listing=run('list',['plugin','list','--json']) + assert all(name+'@workbuddy-plugins' in listing for name in ('workbuddy-tools',)) + sid=str(uuid.uuid4());key=re.sub('-+','-',re.sub(r'[/\\:]','-',str(cwd.resolve())).strip('-'));directory=profile/'projects'/key;directory.mkdir(parents=True) + ids=[str(uuid.uuid4()) for _ in range(4)];rows=[] + for i,(role,text) in enumerate([('user','Synthetic Q1'),('assistant','Synthetic A1'),('user','EXCLUDED Q2'),('assistant','EXCLUDED A2')]): + row={'type':'message','id':ids[i],'role':role,'content':[{'type':'input_text' if role=='user' else 'output_text','text':text}],'status':'completed','cwd':str(cwd),'sessionId':sid,'timestamp':1793520000000+i} + if i:row['parentId']=ids[i-1] + rows.append(row) + source=directory/(sid+'.jsonl');source.write_text(''.join(json.dumps(row)+'\n' for row in rows),encoding='utf-8') + db=sqlite3.connect(profile/'workbuddy.db');db.executescript((ROOT/'src/plugin/tests/linux-sessions-schema.sql').read_text(encoding='utf-8'));db.execute('INSERT INTO sessions(id,cwd,user_id,title,created_at,updated_at) VALUES(?,?,?,?,?,?)',(sid,str(cwd),'synthetic-user','Synthetic source',1793520000000,1793520000000));db.commit();source_row=db.execute('SELECT * FROM sessions WHERE id=?',(sid,)).fetchone() + calls={} + def command(namespace,name,args=None): + text='/'+namespace+':'+name+(' '+json.dumps(args,ensure_ascii=True) if args else '') + label=namespace+'-'+name;calls[label]=calls.get(label,0)+1 + result=run(label+'-'+str(calls[label]),['--resume',sid,'-p',text]) + assert 'Authentication required' not in result + line=next((line for line in result.splitlines() if line.startswith('{"conversation_tools"')),None) + if not line:raise RuntimeError('Native hook did not return operation JSON; inspect '+namespace+'-'+name) + return json.loads(line)['conversation_tools'] + points=command('workbuddy-tools','points');assert points[0]['message_id']==ids[1] + command('workbuddy-tools','status') + op=str(uuid.uuid4());branch=command('workbuddy-tools','branch',{'at':ids[1],'title':'Synthetic branch','operation_id':op});assert 'EXCLUDED' not in (directory/(branch['target']+'.jsonl')).read_text(encoding='utf-8');command('workbuddy-tools','recover',{'operation_id':op}) + seed=cwd/'seed.json';seed.write_text(json.dumps({'schema':1,'messages':[{'role':'user','text':'Synthetic request'},{'role':'assistant','text':'Synthetic answer','reasoning':'We need to verify the facts. Synthetic test only.'}]}),encoding='utf-8') + style=command('workbuddy-tools','style-new',{'seed':str(seed),'operation_id':str(uuid.uuid4())});styled=directory/(style['target']+'.jsonl');assert 'We need to verify' in styled.read_text(encoding='utf-8') + fork=str(uuid.uuid4());result=run('style-eof',['--print','--input-format','stream-json','--output-format','stream-json','--resume',style['target'],'--fork-session','--session-id',fork],stdin='');assert '"duration_api_ms":0' in result;assert 'We need to verify' in (directory/(fork+'.jsonl')).read_text(encoding='utf-8') + assert db.execute('SELECT * FROM sessions WHERE id=?',(sid,)).fetchone()==source_row + assert db.execute('SELECT count(*) FROM sessions').fetchone()[0]==3 + for _ in range(5):command('workbuddy-tools','style-new',{'seed':str(seed),'operation_id':str(uuid.uuid4())}) + assert db.execute('SELECT count(*) FROM sessions').fetchone()[0]==8 + # Deliberate stream loss and missing interpreter must STILL block in the real host. + settings=cwd/'.codebuddy/settings.local.json';saved=settings.read_bytes();cfg=json.loads(saved) + entry=cfg['hooks']['UserPromptSubmit'][0]['hooks'][0];original=entry['command'];shell=entry.get('shell','posix') + spec=importlib.util.spec_from_file_location('native_smoke_manage',ROOT/'plugins/workbuddy-tools/scripts/manage.py');manage=importlib.util.module_from_spec(spec);spec.loader.exec_module(manage) + try: + entry['command']=('& { '+original+' } *> $null') if shell=='powershell' else '('+original+') >/dev/null 2>&1' + settings.write_text(json.dumps(cfg),encoding='utf-8') + lost=run('both-hook-streams-discarded',['--resume',sid,'-p','/workbuddy-tools:status']) + assert 'Authentication required' not in lost and 'blocked' in lost.lower(),lost + entry['command']=manage.guarded_hook_command([str(out/'missing-python.exe'),str(cwd/'.codebuddy/conversation-tools-router.py')],shell) + settings.write_text(json.dumps(cfg),encoding='utf-8') + missing=run('missing-interpreter-failclosed',['--resume',sid,'-p','/workbuddy-tools:status']) + assert 'Authentication required' not in missing and 'blocked' in missing.lower(),missing + finally:settings.write_bytes(saved) + subprocess.run([sys.executable,'-X','utf8',str(ROOT/'plugins/workbuddy-tools/scripts/manage.py'),'uninstall','--project',str(cwd)],env=env,check=True,capture_output=True) + owners=json.loads((cwd/'.codebuddy/conversation-tools-installed.json').read_text(encoding='utf-8'));assert owners['plugins']=={} + db.close() + report={'status':'passed','platform':sys.platform,'native_combined_plugin':True,'source_database_unchanged':True,'reasoning_eof_api_ms':0,'owned_uninstall':True,'repeated_style_creates':5,'both_hook_streams_discarded_blocks':True,'missing_interpreter_blocks':True,'gui':'NOT TESTED','live_model_effect':'NOT TESTED'} + (out/'result.json').write_text(json.dumps(report,indent=2),encoding='utf-8');print(json.dumps(report)) +if __name__=='__main__':main() diff --git a/scripts/prepare_windows_runtime.ps1 b/scripts/prepare_windows_runtime.ps1 new file mode 100644 index 0000000..36aa9de --- /dev/null +++ b/scripts/prepare_windows_runtime.ps1 @@ -0,0 +1,39 @@ +# Static extraction of a SHA256-pinned official archive. Never executes installer. +param([Parameter(Mandatory=$true)][string]$Output) +$ErrorActionPreference='Stop' +$Repo=Split-Path $PSScriptRoot -Parent +$Pin=Get-Content -LiteralPath (Join-Path $Repo 'ci/workbuddy-windows-pin.json') -Raw | ConvertFrom-Json +if (Test-Path -LiteralPath $Output) { throw 'Runtime output must be a new directory.' } +$SevenZip=(Get-Command 7z -ErrorAction SilentlyContinue).Source +if (-not $SevenZip) { $SevenZip=Join-Path $env:ProgramFiles '7-Zip/7z.exe' } +if (-not (Test-Path -LiteralPath $SevenZip)) { throw 'Trusted preinstalled 7-Zip required; no automatic dependency installation.' } +New-Item -ItemType Directory -Path $Output | Out-Null +$Installer=Join-Path $Output 'WorkBuddy-pinned.exe' +Invoke-WebRequest -Uri $Pin.url -OutFile $Installer +$Actual=(Get-FileHash -LiteralPath $Installer -Algorithm SHA256).Hash.ToLowerInvariant() +if ($Actual -ne $Pin.sha256) { throw 'Official artifact hash mismatch; stop without executing or extracting it.' } +$Outer=Join-Path $Output 'outer';$Payload=Join-Path $Output 'payload';$NodeDir=Join-Path $Output 'node' +& $SevenZip x '-y' "-o$Outer" $Installer | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'NSIS static extraction failed' } +$Inner=Join-Path $Outer '$PLUGINSDIR/app-64.7z' +if (-not (Test-Path -LiteralPath $Inner)) { throw 'Pinned NSIS layout changed' } +& $SevenZip x '-y' "-o$Payload" $Inner | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'Application payload extraction failed' } +$NodeZip=Join-Path $Payload 'resources/vendor/node.zip' +if (-not (Test-Path -LiteralPath $NodeZip)) { throw 'Pinned bundled Node archive absent' } +& $SevenZip x '-y' "-o$NodeDir" $NodeZip | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'Bundled Node extraction failed' } +$Node=Join-Path $NodeDir 'node-v22.22.2-win-x64/node.exe' +$Cli=Join-Path $Payload 'resources/app.asar.unpacked/cli/bin/codebuddy' +if (-not (Test-Path -LiteralPath $Node) -or -not (Test-Path -LiteralPath $Cli)) { throw 'Pinned runtime paths unavailable' } +$CliPackage=Get-Content -LiteralPath (Join-Path $Payload 'resources/app.asar.unpacked/cli/package.json') -Raw | ConvertFrom-Json +if ($CliPackage.version -ne $Pin.cli_version) { throw 'Bundled CLI package version mismatch' } +$NodeVersion=& $Node --version +if ($LASTEXITCODE -ne 0 -or $NodeVersion.Trim() -ne 'v22.22.2') { throw 'Bundled Node version mismatch' } +$Report=@{node=$Node;cli=$Cli;version=$Pin.version;sha256=$Actual;installer_executed=$false} +$Report | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $Output 'runtime.json') -Encoding utf8 +if ($env:GITHUB_ENV) { + "WORKBUDDY_TEST_NODE=$Node" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + "WORKBUDDY_TEST_CLI=$Cli" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append +} +$Report | ConvertTo-Json diff --git a/src/plugin/.workbuddy-plugin/plugin.json b/src/plugin/.workbuddy-plugin/plugin.json new file mode 100644 index 0000000..d4507b3 --- /dev/null +++ b/src/plugin/.workbuddy-plugin/plugin.json @@ -0,0 +1,8 @@ +{ + "name": "conversation-tools", + "version": "0.1.0", + "description": "本地会话分支与显式最小风格 seed;不发送模型请求、不修改源历史", + "author": { + "name": "Local Conversation Tools" + } +} \ No newline at end of file diff --git a/src/plugin/commands/branch.md b/src/plugin/commands/branch.md new file mode 100644 index 0000000..64ad1ec --- /dev/null +++ b/src/plugin/commands/branch.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 branch(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/src/plugin/commands/points.md b/src/plugin/commands/points.md new file mode 100644 index 0000000..6a827d3 --- /dev/null +++ b/src/plugin/commands/points.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 points(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/src/plugin/commands/recover.md b/src/plugin/commands/recover.md new file mode 100644 index 0000000..8e4a3e5 --- /dev/null +++ b/src/plugin/commands/recover.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 recover(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/src/plugin/commands/status.md b/src/plugin/commands/status.md new file mode 100644 index 0000000..23eb95f --- /dev/null +++ b/src/plugin/commands/status.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 status(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/src/plugin/commands/style-new.md b/src/plugin/commands/style-new.md new file mode 100644 index 0000000..be0c2b5 --- /dev/null +++ b/src/plugin/commands/style-new.md @@ -0,0 +1,8 @@ +--- +description: 本地会话工具 style-new(由确定性原生 hook 执行) +disable-model-invocation: true +allowed-tools: [] +--- +此命令只能由 conversation-tools 原生 UserPromptSubmit hook 处理。 +如果看到本段,说明安装的项目 hook 未生效:停止,不执行 shell,不重试,不创建或修改会话。 +请运行插件 scripts/manage.py check 检查安装。 diff --git a/src/plugin/examples/minimal-seed.json b/src/plugin/examples/minimal-seed.json new file mode 100644 index 0000000..924ab23 --- /dev/null +++ b/src/plugin/examples/minimal-seed.json @@ -0,0 +1 @@ +{"schema":1,"messages":[{"role":"user","text":"请先说明结论,再列出你确实核验过的依据;不确定之处直接指出。"},{"role":"assistant","text":"我会将结论、已核验依据和不确定项分开表达。具体回答仍取决于后续任务与模型能力。"}]} diff --git a/src/plugin/examples/we-need-demo.json b/src/plugin/examples/we-need-demo.json new file mode 100644 index 0000000..e73cd66 --- /dev/null +++ b/src/plugin/examples/we-need-demo.json @@ -0,0 +1 @@ +{"schema":1,"messages":[{"role":"user","text":"请直接回答问题,并区分已核实的事实和不确定项。"},{"role":"assistant","text":"我会先给出结论,再说明核验依据和仍不确定的部分。","reasoning":"We need to answer the question directly and verify the facts before making claims."}]} diff --git a/src/plugin/hooks/dispatch.py b/src/plugin/hooks/dispatch.py new file mode 100644 index 0000000..7d9de0b --- /dev/null +++ b/src/plugin/hooks/dispatch.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Native UserPromptSubmit dispatcher: only exact namespaced slash commands.""" +from __future__ import annotations +import json, os, sys, uuid +if sys.version_info < (3,10): + print('{"decision":"block","reason":"conversation-tools requires Python 3.10+; install using a compatible interpreter"}') + raise SystemExit(2) +if hasattr(sys.stdout,'reconfigure'):sys.stdout.reconfigure(encoding='utf-8') +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from workbuddy_native.model import OperationError, uid +from workbuddy_native.engine import Engine +MANIFEST=json.loads((Path(__file__).resolve().parents[1]/'.workbuddy-plugin/plugin.json').read_text(encoding='utf-8')) +PREFIX='/'+MANIFEST['name']+':' +SUPPORTED={'workbuddy-branch':{'branch','points','recover','status'},'workbuddy-style':{'style-new','recover','status'}}.get(MANIFEST['name'],{'branch','points','style-new','recover','status'}) + +def dispatch(event: dict) -> dict | None: + prompt=event.get('prompt') + if not isinstance(prompt,str) or not prompt.startswith(PREFIX): return None + command,_,raw=prompt.partition(' ') + try: + if event.get('hook_event_name')!='UserPromptSubmit': raise OperationError('不支持的事件') + expected='2.165.0' if sys.platform=='win32' else '2.147.0' + if event.get('version')!=expected: raise OperationError('CLI 版本不匹配当前平台适配器,停止写入;需要 '+expected) + if command not in {PREFIX+n for n in SUPPORTED}: raise OperationError('未知命令') + args=json.loads(raw) if raw.strip() else {} + if not isinstance(args,dict): raise OperationError('参数必须是 JSON 对象') + cwd=Path(event['cwd']) + if not cwd.is_absolute() or not cwd.is_dir(): raise OperationError('当前项目目录无效') + session=uid(event['session_id']) + transcript=Path(event['transcript_path']) + if not transcript.is_absolute() or transcript.name!=session+'.jsonl' or transcript.parent.parent.name!='projects' or transcript.is_symlink(): raise OperationError('宿主历史路径无效') + profile=transcript.parent.parent.parent.resolve() + config_path=cwd/'.conversation-tools.json' + if config_path.is_symlink(): raise OperationError('配置文件不能是符号链接') + config=json.loads(config_path.read_text(encoding='utf-8')) + if set(config)!={'schema','cli_argv'} or config['schema']!=1: raise OperationError('配置结构不支持') + engine=Engine(profile,config['cli_argv'],profile/'conversation-tools-operations') + name=command[len(PREFIX):] + allowed={'branch':{'at','title','operation_id'},'points':set(),'style-new':{'seed','title','operation_id'},'recover':{'operation_id'},'status':set()}[name] + if set(args)-allowed: raise OperationError('存在未知参数') + if name=='points': result=engine.points(session,cwd) + elif name=='branch': + op=args.get('operation_id') or str(uuid.uuid5(uuid.NAMESPACE_URL,session+':'+str(event.get('generation_id',prompt)))) + result=engine.branch(session,args.get('at','latest'),args.get('title',''),op,cwd) + from workbuddy_native.registry import register + if (profile/'workbuddy.db').exists(): result=dict(result,desktop_registration=register(engine,result)) + elif name=='recover': + result=engine.recover(uid(args.get('operation_id'))) + if (profile/'workbuddy.db').exists(): + from workbuddy_native.registry import register + registration=register(engine,result); result=dict(result,desktop_registration=registration) + elif name=='style-new': + from workbuddy_native.style import create_style + op=args.get('operation_id') or str(uuid.uuid5(uuid.NAMESPACE_URL,session+':'+str(event.get('generation_id',prompt)))) + result=create_style(engine,session,cwd,args,op) + if (profile/'workbuddy.db').exists(): + from workbuddy_native.registry import register + result=dict(result,desktop_registration=register(engine,result)) + else: result={'profile':str(profile),'adapter':('Windows WorkBuddy 5.9.3 / CLI 2.165.0' if sys.platform=='win32' else 'Linux WorkBuddy 5.6.2 / CLI 2.147.0'),'style_default':'off','database_present':(profile/'workbuddy.db').exists()} + if isinstance(result,dict) and result.get('target'): + result=dict(result,open_uri='workbuddy://chat/'+uid(result['target']),gui_open_verified=False) + return {'decision':'block','reason':json.dumps({'conversation_tools':result},ensure_ascii=False)} + except Exception as exc: + return {'decision':'block','reason':'conversation-tools:'+(str(exc) if isinstance(exc,OperationError) else type(exc).__name__)+';没有向模型提交此命令。'} + +if __name__=='__main__': + try: + raw=sys.stdin.buffer.read(1024*1024+1) + if len(raw)>1024*1024: raise ValueError('hook input too large') + output=dispatch(json.loads(raw)) + if output is not None: + print(json.dumps(output,ensure_ascii=False),flush=True) + print(output['reason'],file=sys.stderr,flush=True) + raise SystemExit(2) # Native unconditional stop, even if host loses stdout on exit. + except Exception: + output={'decision':'block','reason':'conversation-tools:无效的宿主事件,已拒绝处理。'} + print(json.dumps(output,ensure_ascii=False),flush=True) + print(output['reason'],file=sys.stderr,flush=True) + raise SystemExit(2) diff --git a/src/plugin/hooks/hooks.json b/src/plugin/hooks/hooks.json new file mode 100644 index 0000000..bd0b542 --- /dev/null +++ b/src/plugin/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{}} diff --git a/src/plugin/hooks/router.py b/src/plugin/hooks/router.py new file mode 100644 index 0000000..a777b51 --- /dev/null +++ b/src/plugin/hooks/router.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Installed project router: exactly one host hook, argv-only namespace dispatch.""" +import json,subprocess,sys +from pathlib import Path +if hasattr(sys.stdout,'reconfigure'):sys.stdout.reconfigure(encoding='utf-8') +def block(reason): + message='WorkBuddy conversation tools: '+reason + print(json.dumps({'decision':'block','reason':message},ensure_ascii=False),flush=True) + print(message,file=sys.stderr,flush=True) +def main(): + raw=sys.stdin.buffer.read(1024*1024+1) + if len(raw)>1024*1024:raise ValueError('event too large') + event=json.loads(raw);prompt=event.get('prompt','') + if not isinstance(prompt,str) or not prompt.startswith('/'):return + namespace=prompt.split(':',1)[0][1:] + if namespace not in {'workbuddy-tools','workbuddy-branch','workbuddy-style','conversation-tools'}:return False + path=Path(__file__).with_name('conversation-tools-installed.json') + if path.is_symlink():raise ValueError('ownership is a symlink') + owners=json.loads(path.read_text(encoding='utf-8')) + if owners.get('schema')!=2:raise ValueError('unsupported router ownership') + owner=owners.get('plugins',{}).get(namespace) + if owner is None:raise ValueError('requested plugin is not installed in this project') + if not isinstance(owner,dict) or set(owner)!={'python','handler','shell'}:raise ValueError('invalid plugin owner') + for key in ('python','handler'): + p=Path(owner[key]) + if not p.is_absolute() or not p.is_file() or p.is_symlink():raise ValueError('missing or linked '+key) + result=subprocess.run([owner['python'],'-X','utf8',owner['handler']],input=raw,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,timeout=100,check=False) + if result.returncode not in {0,2}:raise ValueError('operation handler failed') + output=json.loads(result.stdout) + if not isinstance(output,dict) or output.get('decision')!='block' or not isinstance(output.get('reason'),str):raise ValueError('handler did not safely stop the prompt') + print(json.dumps(output,ensure_ascii=False),flush=True) + print(output['reason'],file=sys.stderr,flush=True) + return True +if __name__=='__main__': + try: + handled=main() + raise SystemExit(2 if handled else 0) + except Exception as exc: + block('refused; '+type(exc).__name__+'; prompt processing stopped') + raise SystemExit(2) diff --git a/src/plugin/scripts/discover.py b/src/plugin/scripts/discover.py new file mode 100644 index 0000000..57a5af7 --- /dev/null +++ b/src/plugin/scripts/discover.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Read-only local runtime discovery; never executes a candidate or scans profiles.""" +import json,os,sys +from pathlib import Path +roots=[] +if os.environ.get('WORKBUDDY_INSTALL_DIR'):roots.append(Path(os.environ['WORKBUDDY_INSTALL_DIR'])) +if os.name=='nt': + for env in ('LOCALAPPDATA','ProgramFiles','ProgramFiles(x86)'): + if os.environ.get(env): + root=Path(os.environ[env]);roots.extend([root/'WorkBuddy',root/'Programs'/'WorkBuddy',root/'Tencent'/'WorkBuddy']) +else:roots.extend([Path('/opt/WorkBuddy'),Path('/opt/workbuddy')]) +results=[] +for root in dict.fromkeys(roots): + if not root.is_dir():continue + resources=root/'resources' + nodes=[resources/'runtime/node/node.exe',resources/'runtime/node/bin/node.exe',resources/'runtime/node/bin/node'] + clis=[resources/'app.asar.unpacked/cli/bin/codebuddy',resources/'app.asar.unpacked/cli/bin/codebuddy.js'] + vendor=resources/'vendor/node.zip' + if vendor.is_file():results.append({'install_root':str(root),'bundled_node_archive':str(vendor),'note':'Archive is not executed or extracted; provide a trusted node.exe explicitly.'}) + for node in nodes: + for cli in clis: + if node.is_file() and cli.is_file():results.append({'install_root':str(root),'node':str(node.resolve()),'cli':str(cli.resolve())}) +print(json.dumps({'python':sys.executable,'python_version':sys.version.split()[0],'python_supported':sys.version_info>=(3,10),'platform':sys.platform,'candidates':results,'next':'Verify the intended official installation; pass --cli and --node explicitly. Set WORKBUDDY_INSTALL_DIR if not found.'},ensure_ascii=True,indent=2)) diff --git a/src/plugin/scripts/install.ps1 b/src/plugin/scripts/install.ps1 new file mode 100644 index 0000000..2fd28b6 --- /dev/null +++ b/src/plugin/scripts/install.ps1 @@ -0,0 +1,29 @@ +# No execution-policy changes or downloads. Invoke from a trusted PowerShell session. +param( + [Parameter(Mandatory=$true)][ValidateSet('install','uninstall','check')][string]$Action, + [Parameter(Mandatory=$true)][string]$Project, + [string]$Cli, + [string]$Node, + [string]$Python, + [ValidateSet('powershell','posix')][string]$HookShell='powershell' +) +$ErrorActionPreference='Stop' +$candidates=@() +if ($Python) { $candidates+=,@($Python) } +else { + if (Get-Command py -ErrorAction SilentlyContinue) { $candidates+=,@('py','-3') } + if (Get-Command python -ErrorAction SilentlyContinue) { $candidates+=,@('python') } +} +$chosen=$null +foreach ($candidate in $candidates) { + $exe=$candidate[0];$prefix=@($candidate | Select-Object -Skip 1) + & $exe @prefix -c 'import sys; sys.exit(0 if sys.version_info >= (3,10) else 1)' + if ($LASTEXITCODE -eq 0) { $chosen=$candidate;break } +} +if (-not $chosen) { throw 'Python 3.10+ not found. Provide -Python path to a trusted compatible python.exe. Nothing installed.' } +$exe=$chosen[0];$prefix=@($chosen | Select-Object -Skip 1) +$params=@('-X','utf8',(Join-Path $PSScriptRoot 'manage.py'),$Action,'--project',$Project,'--hook-shell',$HookShell) +if ($Cli) { $params+=@('--cli',$Cli) } +if ($Node) { $params+=@('--node',$Node) } +& $exe @prefix @params +if ($LASTEXITCODE -ne 0) { throw "Native project hook $Action failed; inspect the preceding diagnostic." } diff --git a/src/plugin/scripts/manage.py b/src/plugin/scripts/manage.py new file mode 100644 index 0000000..90398d5 --- /dev/null +++ b/src/plugin/scripts/manage.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Merge only owned native hook. No trust, permissions, credentials or history edits.""" +import argparse,json,os,shlex,sys,shutil +if sys.version_info < (3,10): + raise SystemExit('conversation-tools requires Python 3.10+; no settings changed') +if hasattr(sys.stdout,'reconfigure'):sys.stdout.reconfigure(encoding='utf-8') +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from workbuddy_native.engine import atomic +from workbuddy_native.model import no_links +from workbuddy_native.platform import lock +ROOT=Path(__file__).resolve().parents[1] +PLUGIN=json.loads((ROOT/'.workbuddy-plugin/plugin.json').read_text(encoding='utf-8'))['name'] + +def hook_command(argv, shell): + if shell=='posix':return shlex.join(argv) + if shell=='powershell': + if any(any(c in a for c in '\r\n\0') for a in argv):raise ValueError('unsupported control characters in hook path') + return '& '+ ' '.join("'"+a.replace("'","''")+"'" for a in argv) + raise ValueError('unsupported native hook shell') + +def guarded_hook_command(argv,shell): + command=hook_command(argv,shell) + if shell=='powershell': + return "$ErrorActionPreference='Stop'; try { "+command+"; if ($LASTEXITCODE -eq 0) { exit 0 } else { exit 2 } } catch { exit 2 }" + if shell=='posix': + return 'if '+command+'; then exit 0; else exit 2; fi' + raise ValueError('unsupported hook shell') + +def configure(a,project,folder,settings,config): + snapshot=settings.read_bytes() if settings.exists() else None + current=json.loads(snapshot) if snapshot is not None else {} + if not isinstance(current,dict):raise ValueError('invalid project settings') + entries=current.get('hooks',{}).get('UserPromptSubmit',[]) + if not isinstance(entries,list):raise ValueError('invalid hooks array') + ownership=folder/'conversation-tools-installed.json';router=folder/'conversation-tools-router.py' + no_links(ownership);no_links(router) + owners=json.loads(ownership.read_text(encoding='utf-8')) if ownership.exists() else {'schema':2,'plugins':{},'hook':None} + if not isinstance(owners,dict):raise ValueError('invalid ownership') + if owners.get('schema')!=2: + # Uninstall the old exact owned entry, without executing/parsing its shell. + if a.action!='uninstall':raise ValueError('legacy hook layout: uninstall each old plugin first') + previous=owners.pop(PLUGIN,None) + entries=[e for e in entries if e!=previous] + if entries:current.setdefault('hooks',{})['UserPromptSubmit']=entries + elif 'hooks' in current:current['hooks'].pop('UserPromptSubmit',None) + if current.get('hooks')=={}:current.pop('hooks') + atomic(settings,json.dumps(current,ensure_ascii=False,indent=2).encode()) + if owners:atomic(ownership,json.dumps(owners,ensure_ascii=False,indent=2).encode()) + else:atomic(ownership,b'{"schema":2,"plugins":{},"hook":null}') + return + if not {'schema','plugins','hook'}<=set(owners) or set(owners)-{'schema','plugins','hook','stale_hooks'} or not isinstance(owners['plugins'],dict):raise ValueError('invalid ownership schema') + previous=owners['hook'];plugins=owners['plugins'] + stale=owners.get('stale_hooks',[]) + if not isinstance(stale,list):raise ValueError('invalid ownership recovery list') + old_hooks=stale+([previous] if previous else []) + if a.action=='check': + print(json.dumps({'project':str(project),'plugin':PLUGIN,'hook_installed':PLUGIN in plugins and previous in entries,'router_exists':router.is_file(),'engine_config_present':config.is_file(),'python':sys.version.split()[0],'python_executable':sys.executable,'platform':sys.platform,'hook_shell':a.hook_shell,'hook_shell_available':a.hook_shell!='powershell' or bool(shutil.which('pwsh'))},ensure_ascii=False));return + if a.action=='install': + if a.hook_shell=='powershell' and not shutil.which('pwsh'):raise ValueError('PowerShell 7 pwsh not found on PATH; no installation changes') + if not a.cli or not Path(a.cli).is_absolute() or not Path(a.cli).is_file():raise ValueError('--cli must be the official bundled CLI absolute path') + argv=[str(Path(a.cli).resolve())] + if a.node: + if not Path(a.node).is_absolute() or not Path(a.node).is_file():raise ValueError('invalid --node') + argv.insert(0,str(Path(a.node).resolve())) + if os.name=='nt' and Path(argv[0]).suffix.lower() not in {'.exe','.com'}:raise ValueError('Windows needs --node pointing to trusted node.exe, not a batch launcher') + planned={'schema':1,'cli_argv':argv} + if config.exists() and json.loads(config.read_text(encoding='utf-8'))!=planned:raise ValueError('existing CLI configuration differs; refusing overwrite') + atomic(config,json.dumps(planned,ensure_ascii=False,indent=2).encode()) + plugins[PLUGIN]={'python':str(Path(sys.executable).resolve(strict=True)),'handler':str(ROOT/'hooks/dispatch.py'),'shell':a.hook_shell} + atomic(router,(ROOT/'hooks/router.py').read_bytes()) + else:plugins.pop(PLUGIN,None) + # One shared project router avoids the actual host's multi-hook result bug. + entries=[e for e in entries if e not in old_hooks] + owned=None + if plugins: + chosen=plugins[sorted(plugins)[0]] + command=guarded_hook_command([chosen['python'],'-X','utf8',str(router)],chosen['shell']) + hook={'type':'command','command':command,'timeout':110} + if chosen['shell']=='powershell':hook['shell']='powershell' + owned={'hooks':[hook]};entries.append(owned) + owners['hook']=owned + if entries:current.setdefault('hooks',{})['UserPromptSubmit']=entries + elif 'hooks' in current:current['hooks'].pop('UserPromptSubmit',None) + if current.get('hooks')=={}:current.pop('hooks') + if settings.exists(): + backup=settings.with_name('settings.local.json.conversation-tools.backup') + if not backup.exists():atomic(backup,settings.read_bytes()) + if (settings.read_bytes() if settings.exists() else None)!=snapshot:raise ValueError('settings changed concurrently; refusing overwrite') + # Durable intent remembers old and new exact hooks until settings commit. + owners['stale_hooks']=old_hooks+([owned] if owned else []) + atomic(ownership,json.dumps(owners,ensure_ascii=False,indent=2).encode()) + atomic(settings,json.dumps(current,ensure_ascii=False,indent=2).encode()) + owners['stale_hooks']=[] + atomic(ownership,json.dumps(owners,ensure_ascii=False,indent=2).encode()) + print(json.dumps({'status':a.action+'ed','plugin':PLUGIN,'project':str(project),'history_deleted':False},ensure_ascii=False)) + +def main(): + p=argparse.ArgumentParser();p.add_argument('action',choices=['install','uninstall','check']);p.add_argument('--project',required=True);p.add_argument('--cli');p.add_argument('--node');p.add_argument('--hook-shell',choices=['powershell','posix'],default='powershell' if os.name=='nt' else 'posix');a=p.parse_args() + project=Path(a.project).resolve(strict=True) + if not project.is_dir():raise ValueError('project is not directory') + folder=project/'.codebuddy';settings=folder/'settings.local.json';config=project/'.conversation-tools.json' + for path in (folder,settings,config):no_links(path) + if a.action=='check':configure(a,project,folder,settings,config);return + folder.mkdir(exist_ok=True) + with lock(folder/'conversation-tools-install.lock'):configure(a,project,folder,settings,config) +if __name__=='__main__': + try:main() + except Exception as e:print('Refused: '+str(e),file=sys.stderr);sys.exit(1) diff --git a/src/plugin/skills/conversation-tools/SKILL.md b/src/plugin/skills/conversation-tools/SKILL.md new file mode 100644 index 0000000..3488a3a --- /dev/null +++ b/src/plugin/skills/conversation-tools/SKILL.md @@ -0,0 +1,16 @@ +--- +name: conversation-tools +description: 本地会话分支和用户显式选择的最小风格 seed 的使用说明。 +disable-model-invocation: true +user-invocable: true +allowed-tools: [] +--- +这是说明技能,不授权模型写入会话文件或数据库。 +执行操作必须使用项目原生 UserPromptSubmit hook 的固定命令: +- `/conversation-tools:points` 查看当前会话可用完整回复 ID。 +- `/conversation-tools:branch {"at":"latest","title":"分支名称"}` 或将 at 设为完整回复 UUID。 +- `/conversation-tools:style-new {"seed":"/绝对路径/minimal-seed.json","title":"新会话"}` +- `/conversation-tools:recover {"operation_id":"操作 UUID"}` +- `/conversation-tools:status` +参数是 JSON,不是 shell。不要把参数插入 shell,也不要替代 hook 调用任何写入工具。 +如果 hook 未生效,停止并提示运行 `scripts/manage.py check`;不要自动模仿此操作。 diff --git a/src/plugin/tests/linux-sessions-schema.sql b/src/plugin/tests/linux-sessions-schema.sql new file mode 100644 index 0000000..379c5b6 --- /dev/null +++ b/src/plugin/tests/linux-sessions-schema.sql @@ -0,0 +1,42 @@ +CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + cwd TEXT NOT NULL, + user_id TEXT NOT NULL, + title TEXT, + custom_title TEXT, + status TEXT NOT NULL DEFAULT 'Pending', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + last_activity_at INTEGER, + deleted_at INTEGER, + is_playground INTEGER NOT NULL DEFAULT 0, + source_mode TEXT, + is_background_automation INTEGER, + mode TEXT, + model TEXT, + expert_id TEXT, + expert_locale TEXT, + expert_runtime_identity TEXT, + expert_marketplace TEXT, + permission_mode TEXT, + use_sandbox_cli INTEGER, + project_id TEXT +); +ALTER TABLE sessions ADD COLUMN plugin_context_json TEXT; +ALTER TABLE sessions ADD COLUMN addon_selection TEXT; +ALTER TABLE sessions ADD COLUMN session_settings TEXT; +ALTER TABLE sessions ADD COLUMN last_user_prompt_expert_selection TEXT; +ALTER TABLE sessions ADD COLUMN context_window INTEGER; +ALTER TABLE sessions ADD COLUMN buddy_snapshot_id TEXT; +ALTER TABLE sessions ADD COLUMN buddy_binding_json TEXT; +ALTER TABLE sessions ADD COLUMN thought_level TEXT; +ALTER TABLE sessions ADD COLUMN transport TEXT NOT NULL DEFAULT 'local'; +ALTER TABLE sessions ADD COLUMN conversation_origin TEXT; +ALTER TABLE sessions ADD COLUMN visibility TEXT; +ALTER TABLE sessions ADD COLUMN group_id TEXT; +ALTER TABLE sessions ADD COLUMN group_title TEXT; +ALTER TABLE sessions ADD COLUMN agent_dirty INTEGER; +ALTER TABLE sessions ADD COLUMN agent_dirty_at INTEGER; +ALTER TABLE sessions ADD COLUMN agent_last_synced INTEGER; +ALTER TABLE sessions ADD COLUMN verified_at INTEGER; +ALTER TABLE sessions ADD COLUMN unread INTEGER NOT NULL DEFAULT 0; diff --git a/src/plugin/tests/test_engine.py b/src/plugin/tests/test_engine.py new file mode 100644 index 0000000..d383c66 --- /dev/null +++ b/src/plugin/tests/test_engine.py @@ -0,0 +1,70 @@ +import tempfile,unittest,json,uuid,sys,os +from pathlib import Path +from unittest.mock import patch +from workbuddy_native.model import * +from workbuddy_native.engine import Engine,encode +from workbuddy_native.style import create_style +U=lambda:str(uuid.uuid4()) +class TestEngine(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name);self.cwd=self.root/'project';self.cwd.mkdir();self.profile=self.root/'profile';self.folder=self.profile/'projects'/'project';self.folder.mkdir(parents=True);self.sid=U();self.op=U();self.rows=[];parent=None + for role in ['user','assistant','user','assistant']: + row={'type':'message','id':U(),'sessionId':self.sid,'cwd':str(self.cwd),'role':role,'content':[{'type':'text','text':role}],'status':'completed'} + if parent:row['parentId']=parent + parent=row['id'];self.rows.append(row) + self.source=self.folder/(self.sid+'.jsonl');self.source.write_bytes(encode(self.rows));self.engine=Engine(self.profile,['/fake'],self.root/'state') + def tearDown(self):self.tmp.cleanup() + def fake(self,args,**kw): + self.assertIs(kw['stdin'],__import__('subprocess').DEVNULL);self.assertNotIn('shell',kw) + selected='CODEBUDDY_FORCE_LITE_WB_BUNDLE' if os.name=='nt' else 'CODEBUDDY_FORCE_HEADLESS_BUNDLE' + other='CODEBUDDY_FORCE_HEADLESS_BUNDLE' if os.name=='nt' else 'CODEBUDDY_FORCE_LITE_WB_BUNDLE' + self.assertEqual(kw['env'][selected],'1');self.assertNotIn(other,kw['env']) + target=args[args.index('--session-id')+1];(self.folder/(target+'.jsonl')).write_bytes(self.source.read_bytes());return type('Run',(),{'returncode':0})() + def test_branch_idempotent_and_immutable(self): + before=self.source.read_bytes() + with patch('subprocess.run',self.fake):r=self.engine.branch(self.sid,self.rows[1]['id'],'$(touch BAD)',self.op,self.cwd);r2=self.engine.branch(self.sid,self.rows[1]['id'],'$(touch BAD)',self.op,self.cwd) + self.assertEqual(r,r2);self.assertEqual(self.source.read_bytes(),before);self.assertEqual(len(records(find(self.profile,r['target']).read_bytes())),3) + def test_pending_and_incomplete(self): + rows=self.rows[:2]+[{'type':'function_call','id':U(),'callId':'c'}] + self.assertEqual(boundaries(rows),[]) + rows=self.rows[:2]+[dict(self.rows[1],id=U(),status='incomplete')];self.assertEqual(boundaries(rows),[]) + def test_unfinished_reasoning_invalidates(self): + self.assertEqual(boundaries(self.rows[:2]+[{'type':'reasoning','id':U(),'content':[]}]),[]) + def test_embedded_tool_invalidates(self): + rows=self.rows[:2]+[{'type':'message','role':'assistant','content':[{'type':'tool_use','id':'c'}]}];self.assertEqual(boundaries(rows),[]) + def test_skip_run_not_boundary(self): + self.rows[3]['providerData']={'skipRun':True};self.assertEqual(len(boundaries(self.rows)),1) + def test_unknown_uuid_symlink(self): + with self.assertRaises(OperationError):uid('../escape') + with self.assertRaises(OperationError):records(b'{"type":"unknown"}\n') + outside=self.root/(U()+'.jsonl');outside.write_bytes(encode(self.rows));self.source.unlink() + try:self.source.symlink_to(outside) + except OSError as exc: + if os.name=='nt':self.skipTest('Windows symlink privilege unavailable: '+str(exc)) + raise + with self.assertRaises(OperationError):find(self.profile,self.sid) + def test_failed_no_retry(self): + with patch('subprocess.run',side_effect=TimeoutError): + with self.assertRaises(OperationError):self.engine.branch(self.sid,'latest','',self.op,self.cwd) + with patch('subprocess.run') as run: + with self.assertRaises(OperationError):self.engine.branch(self.sid,'latest','',self.op,self.cwd) + run.assert_not_called() + def test_recover_prepared(self): + with patch('subprocess.run',self.fake):r=self.engine.branch(self.sid,'latest','',self.op,self.cwd) + r['status']='prepared';(self.engine.state/(self.op+'.json')).write_text(json.dumps(r));self.assertEqual(self.engine.recover(self.op)['status'],'completed') + def test_style_no_model(self): + seed=self.root/'seed.json';seed.write_text(json.dumps({'schema':1,'messages':[{'role':'user','text':'example'},{'role':'assistant','text':'answer'}]}));before=self.source.read_bytes() + with patch('subprocess.run') as run:r=create_style(self.engine,self.sid,self.cwd,{'seed':str(seed)},self.op);run.assert_not_called() + self.assertEqual(self.source.read_bytes(),before);self.assertEqual(len(records(find(self.profile,r['target']).read_bytes())),2) + def test_reasoning_seed_preserves_plain_text_and_chain(self): + seed=self.root/'reason.json';seed.write_text(json.dumps({'schema':1,'messages':[{'role':'user','text':'q'},{'role':'assistant','text':'a','reasoning':'synthetic reasoning'}]})) + r=create_style(self.engine,self.sid,self.cwd,{'seed':str(seed)},self.op);rows=records(find(self.profile,r['target']).read_bytes()) + self.assertEqual(rows[1]['type'],'reasoning');self.assertEqual(rows[1]['rawContent'][0]['text'],'synthetic reasoning');self.assertEqual(rows[2]['parentId'],rows[1]['id']);self.assertNotIn('providerData',rows[1]) + def test_shipped_synthetic_we_need_demo(self): + seed=Path(__file__).resolve().parents[1]/'examples/we-need-demo.json' + r=create_style(self.engine,self.sid,self.cwd,{'seed':str(seed)},self.op);rows=records(find(self.profile,r['target']).read_bytes()) + self.assertTrue(rows[1]['rawContent'][0]['text'].startswith('We need')) + def test_seed_rejects_private_opaque_fields(self): + seed=self.root/'bad.json';seed.write_text(json.dumps({'schema':1,'messages':[{'role':'user','text':'q'},{'role':'assistant','text':'a','providerData':{'token':'x'}}]})) + with self.assertRaises(OperationError):create_style(self.engine,self.sid,self.cwd,{'seed':str(seed)},self.op) +if __name__=='__main__':unittest.main() diff --git a/src/plugin/tests/test_hook_install.py b/src/plugin/tests/test_hook_install.py new file mode 100644 index 0000000..8d6f107 --- /dev/null +++ b/src/plugin/tests/test_hook_install.py @@ -0,0 +1,59 @@ +import importlib.util,json,subprocess,sys,tempfile,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +spec=importlib.util.spec_from_file_location('dispatch',ROOT/'hooks/dispatch.py');d=importlib.util.module_from_spec(spec);spec.loader.exec_module(d) +mspec=importlib.util.spec_from_file_location('manage',ROOT/'scripts/manage.py');manage=importlib.util.module_from_spec(mspec);mspec.loader.exec_module(manage) +class HookTests(unittest.TestCase): + def test_powershell_fixed_argv_escaping(self): + self.assertEqual(manage.hook_command(["C:\\A B\\O'Brien;$x&`test.py"],'powershell'),"& 'C:\\A B\\O''Brien;$x&`test.py'") + with self.assertRaises(ValueError):manage.hook_command(['bad\npath'],'powershell') + def test_uninstall_recorded_powershell_hook_without_pwsh(self): + with tempfile.TemporaryDirectory() as td: + project=Path(td);folder=project/'.codebuddy';folder.mkdir();old={'hooks':[{'type':'command','shell':'powershell','command':"& 'old-python.exe' 'old-dispatch.py'",'timeout':90}]} + (folder/'settings.local.json').write_text(json.dumps({'hooks':{'UserPromptSubmit':[old]}}),encoding='utf-8') + (folder/'conversation-tools-installed.json').write_text(json.dumps({'conversation-tools':old}),encoding='utf-8') + subprocess.run([sys.executable,str(ROOT/'scripts/manage.py'),'uninstall','--project',td,'--hook-shell','powershell'],check=True,stdout=subprocess.DEVNULL) + self.assertEqual(json.loads((folder/'settings.local.json').read_text(encoding='utf-8')), {}) + def test_normal_prompts_unaffected(self): + for prompt in ['hello',' /conversation-tools:branch','/other:branch','please /conversation-tools:branch']:self.assertIsNone(d.dispatch({'prompt':prompt})) + def test_unknown_and_wrong_version_blocked(self): + for e in [{'prompt':'/conversation-tools:nope','hook_event_name':'UserPromptSubmit','version':'2.147.0'},{'prompt':'/conversation-tools:branch','hook_event_name':'UserPromptSubmit','version':'future'}]:self.assertEqual(d.dispatch(e)['decision'],'block') + def test_malicious_arguments_not_shell(self): + out=d.dispatch({'prompt':'/conversation-tools:branch $(touch /tmp/never-create)','hook_event_name':'UserPromptSubmit','version':'2.147.0'}) + self.assertEqual(out['decision'],'block') + def test_install_uninstall_preserves_other_settings(self): + with tempfile.TemporaryDirectory() as td: + p=Path(td);(p/'.codebuddy').mkdir();s=p/'.codebuddy/settings.local.json';old={'permissions':{'deny':['x']},'hooks':{'Stop':[{'hooks':[]}],'UserPromptSubmit':[{'hooks':[{'type':'command','command':'echo other'}]}]}};s.write_text(json.dumps(old)) + args=[sys.executable,str(ROOT/'scripts/manage.py')] + subprocess.run(args+['install','--project',td,'--cli',sys.executable],check=True,stdout=subprocess.DEVNULL) + subprocess.run(args+['install','--project',td,'--cli',sys.executable],check=True,stdout=subprocess.DEVNULL) + self.assertEqual(len(json.loads(s.read_text())['hooks']['UserPromptSubmit']),2) + subprocess.run(args+['uninstall','--project',td],check=True,stdout=subprocess.DEVNULL) + self.assertEqual(json.loads(s.read_text()),old) +if __name__=='__main__':unittest.main() + +class InstallerRecoveryTests(unittest.TestCase): + def test_interrupted_change_and_last_uninstall_recover_owned_hooks(self): + from types import SimpleNamespace + from unittest.mock import patch + import contextlib,io + with tempfile.TemporaryDirectory() as td: + root=Path(td);folder=root/'.codebuddy';folder.mkdir();settings=folder/'settings.local.json';config=root/'.conversation-tools.json' + args=SimpleNamespace(action='install',hook_shell='posix',cli=sys.executable,node=None) + real_atomic=manage.atomic + with contextlib.redirect_stdout(io.StringIO()):manage.configure(args,root,folder,settings,config) + def interrupted(path,data): + if path==settings:raise OSError('synthetic settings publication failure') + real_atomic(path,data) + with patch.object(manage.sys,'executable',str(ROOT/'hooks/dispatch.py')): + with patch.object(manage,'atomic',side_effect=interrupted): + with self.assertRaises(OSError):manage.configure(args,root,folder,settings,config) + with contextlib.redirect_stdout(io.StringIO()):manage.configure(args,root,folder,settings,config) + self.assertEqual(len(json.loads(settings.read_text(encoding='utf-8'))['hooks']['UserPromptSubmit']),1) + owners=folder/'conversation-tools-installed.json';self.assertEqual(json.loads(owners.read_text(encoding='utf-8'))['stale_hooks'],[]) + args.action='uninstall' + with patch.object(manage,'atomic',side_effect=interrupted): + with self.assertRaises(OSError):manage.configure(args,root,folder,settings,config) + with contextlib.redirect_stdout(io.StringIO()):manage.configure(args,root,folder,settings,config) + self.assertEqual(json.loads(settings.read_text(encoding='utf-8')), {}) + self.assertEqual(json.loads(owners.read_text(encoding='utf-8'))['plugins'],{}) diff --git a/src/plugin/tests/test_platform.py b/src/plugin/tests/test_platform.py new file mode 100644 index 0000000..d27bd4d --- /dev/null +++ b/src/plugin/tests/test_platform.py @@ -0,0 +1,78 @@ +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch +from types import SimpleNamespace +from workbuddy_native.platform import lock, LockBusy, fsync_directory, same_path + +class PlatformTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup) + self.root=Path(self.tmp.name); self.path=self.root/'operation.lock' + def test_lock_excludes_same_process_and_releases(self): + with lock(self.path): + with self.assertRaises(LockBusy): + with lock(self.path): pass + with lock(self.path): pass + self.assertTrue(self.path.exists()) + def test_lock_released_after_exception(self): + with self.assertRaises(ValueError): + with lock(self.path): raise ValueError('synthetic') + with lock(self.path): pass + def test_reparse_attribute_rejected_without_is_junction_api(self): + with patch.object(Path,'is_symlink',return_value=False), patch.object(Path,'lstat',return_value=SimpleNamespace(st_file_attributes=0x400)): + with self.assertRaisesRegex(OSError,'reparse point'): + with lock(self.path): pass + self.assertFalse(self.path.exists()) + def test_unc_lock_rejected(self): + with self.assertRaisesRegex(OSError,'UNC'): + with lock(Path(r'\\server\share\operation.lock')): pass + def test_cross_process_lock(self): + script='''import sys +from pathlib import Path +from workbuddy_native.platform import lock, LockBusy +try: + with lock(Path(sys.argv[1])): pass +except LockBusy: + sys.exit(17) +''' + env=dict(os.environ); env['PYTHONPATH']=str(Path(__file__).resolve().parents[1]) + with lock(self.path): + result=subprocess.run([sys.executable,'-c',script,str(self.path)],env=env,capture_output=True,timeout=10) + self.assertEqual(result.returncode,17,result.stderr.decode()) + result=subprocess.run([sys.executable,'-c',script,str(self.path)],env=env,capture_output=True,timeout=10) + self.assertEqual(result.returncode,0,result.stderr.decode()) + def test_existing_paths_use_filesystem_identity(self): + with patch('os.path.samefile',return_value=False) as same: + self.assertFalse(same_path(self.root,self.root));same.assert_called_once() + def test_same_path_normalization(self): + self.assertTrue(same_path(self.root/'a'/'..'/'b',self.root/'b')) + self.assertFalse(same_path(self.root/'a',self.root/'b')) + def test_fsync_directory(self): fsync_directory(self.root) + @unittest.skipUnless(os.name=='nt','Requires actual Windows filesystem') + def test_windows_case_insensitive_path(self): + self.assertTrue(same_path(str(self.root).upper(),str(self.root).lower())) + @unittest.skipUnless(os.name=='nt','Requires actual Windows msvcrt') + def test_windows_lock_byte_zero(self): + with lock(self.path) as stream: + self.assertGreaterEqual(os.fstat(stream.fileno()).st_size,1) + stream.seek(10) + # Other participants still lock byte zero, not the caller cursor. + with self.assertRaises(LockBusy): + with lock(self.path): pass + with lock(self.path): pass + @unittest.skipUnless(os.name=='posix','Requires case-sensitive POSIX semantics') + def test_posix_case_sensitive_path(self): + self.assertFalse(same_path(self.root/'A',self.root/'a')) + @unittest.skipIf(os.name=='nt','Windows symlink creation requires optional privilege') + def test_symlink_lock_rejected(self): + target=self.root/'other'; target.write_text('unchanged') + self.path.symlink_to(target) + with self.assertRaises(OSError): + with lock(self.path): pass + self.assertEqual(target.read_text(),'unchanged') + +if __name__=='__main__': unittest.main() diff --git a/src/plugin/tests/test_registry.py b/src/plugin/tests/test_registry.py new file mode 100644 index 0000000..bdcb41c --- /dev/null +++ b/src/plugin/tests/test_registry.py @@ -0,0 +1,129 @@ +import os, json, sqlite3, tempfile, unittest, uuid +from workbuddy_native.platform import lock +from contextlib import closing +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch +from workbuddy_native.engine import encode, save +from workbuddy_native.model import digest +from workbuddy_native.registry import register, RegistryError + +class RegistryTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup) + self.root=Path(self.tmp.name); self.cwd=self.root/'project'; self.cwd.mkdir() + self.profile=self.root/'profile'; self.hist=self.profile/'projects'/'project'; self.hist.mkdir(parents=True) + self.state=self.root/'state'; self.state.mkdir() + self.engine=SimpleNamespace(profile=self.profile,state=self.state) + self.source=str(uuid.uuid4()); self.target=str(uuid.uuid4()); self.op=str(uuid.uuid4()) + self.original=encode([{'type':'message','id':str(uuid.uuid4()),'role':'assistant','content':[{'type':'output_text','text':'fixture'}],'cwd':str(self.cwd)}]) + self.target_data=encode([{'type':'message','id':str(uuid.uuid4()),'role':'assistant','content':[{'type':'output_text','text':'fixture'}],'cwd':str(self.cwd)}, {'type':'custom-title','id':str(uuid.uuid4()),'customTitle':'测试 $(touch /tmp/never)','sessionId':self.target}]) + (self.hist/(self.source+'.jsonl')).write_bytes(self.original); (self.hist/(self.target+'.jsonl')).write_bytes(self.target_data) + self.receipt={'operation':self.op,'target':self.target,'request':{'source':self.source,'cwd':str(self.cwd),'title_sha256':digest('测试 $(touch /tmp/never)'.encode())},'source_sha256':digest(self.original),'target_sha256':digest(self.target_data),'status':'completed'} + self.journal=self.state/(self.op+'.json'); save(self.journal,self.receipt) + self.dbpath=self.profile/'workbuddy.db' + with closing(sqlite3.connect(self.dbpath)) as db, db: + db.executescript(Path(__file__).with_name('linux-sessions-schema.sql').read_text(encoding='utf-8')) + db.execute('INSERT INTO sessions (id,cwd,user_id,title,status,created_at,updated_at,transport,is_playground,unread,permission_mode,plugin_context_json) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',(self.source,str(self.cwd),'synthetic-user','source','pending',1,1,'local',0,0,'bypass','private-not-copy')) + self.source_row=self.row(self.source) + def row(self,id): + with closing(sqlite3.connect(self.dbpath)) as db, db: return db.execute('SELECT * FROM sessions WHERE id=?',(id,)).fetchone() + def test_insert_and_idempotent(self): + self.assertEqual(register(self.engine,self.receipt)['status'],'registered') + self.assertEqual(register(self.engine,self.receipt)['status'],'already_registered') + self.assertEqual(self.row(self.source),self.source_row) + + with closing(sqlite3.connect(self.dbpath)) as db, db: + self.assertEqual(db.execute('SELECT permission_mode,plugin_context_json,status FROM sessions WHERE id=?',(self.target,)).fetchone(),(None,None,'Pending')) + self.assertEqual((self.hist/(self.source+'.jsonl')).read_bytes(),self.original) + def test_absent_db_does_not_create(self): + self.dbpath.unlink(); self.assertEqual(register(self.engine,self.receipt)['status'],'cli_only'); self.assertFalse(self.dbpath.exists()) + def test_unknown_schema(self): + with closing(sqlite3.connect(self.dbpath)) as db, db: db.execute('ALTER TABLE sessions ADD COLUMN unknown_future TEXT') + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertIsNone(self.row(self.target)) + def test_unrecognized_default_rejected(self): + with closing(sqlite3.connect(self.dbpath)) as db, db: + db.execute('PRAGMA writable_schema=ON') + db.execute("UPDATE sqlite_master SET sql=replace(sql, ?, ?) WHERE name='sessions'", ("DEFAULT 'Pending'", "DEFAULT 'Other'")) + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertIsNone(self.row(self.target)) + def test_missing_title_uses_fallback(self): + self.receipt['request']['title_sha256']=digest(b'') + save(self.journal,self.receipt) + register(self.engine,self.receipt) + with closing(sqlite3.connect(self.dbpath)) as db, db: + self.assertEqual(db.execute('SELECT custom_title FROM sessions WHERE id=?',(self.target,)).fetchone()[0],'分支 '+self.target[:8]) + def test_generated_column_rejected(self): + with closing(sqlite3.connect(self.dbpath)) as db, db: + db.execute('ALTER TABLE sessions ADD COLUMN unsafe_generated TEXT GENERATED ALWAYS AS (user_id) VIRTUAL') + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertIsNone(self.row(self.target)) + def test_host_append_after_snapshot_allowed(self): + self.receipt['source_size']=len(self.original); save(self.journal,self.receipt) + path=self.hist/(self.source+'.jsonl'); path.write_bytes(self.original+b'{}\n') + self.assertEqual(register(self.engine,self.receipt)['status'],'registered') + self.assertEqual(path.read_bytes(),self.original+b'{}\n') + def test_changed_prefix_rejected(self): + self.receipt['source_size']=len(self.original); save(self.journal,self.receipt) + path=self.hist/(self.source+'.jsonl'); path.write_bytes(self.original.replace(b'fixture',b'changed')+b'{}\n') + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + def test_shared_operation_lock(self): + with lock(self.state/(self.op+'.lock')): + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertIsNone(self.row(self.target)) + @unittest.skipIf(os.name=='nt','Windows symbolic link creation requires optional privilege') + def test_symlink_lock_rejected(self): + target=self.root/'lock-target'; target.write_text('unchanged') + (self.state/(self.op+'.lock')).symlink_to(target) + from workbuddy_native.model import OperationError + with self.assertRaises(OperationError): register(self.engine,self.receipt) + self.assertEqual(target.read_text(),'unchanged') + def test_busy(self): + db=sqlite3.connect(self.dbpath); db.execute('BEGIN IMMEDIATE') + try: + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + finally: db.rollback(); db.close() + self.assertIsNone(self.row(self.target)) + def test_corrupt(self): + self.dbpath.write_bytes(b'not sqlite') + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + def test_commit_then_receipt_failure_recovery(self): + real_save=save; count=0 + def fail(path, data): + nonlocal count + count+=1 + if count>=2: raise OSError('synthetic crash after commit') + real_save(path,data) + with patch('workbuddy_native.registry.save',side_effect=fail): + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertIsNotNone(self.row(self.target)) + self.assertEqual(register(self.engine,self.receipt)['status'],'already_registered') + def test_foreign_uuid_collision(self): + with closing(sqlite3.connect(self.dbpath)) as db, db: db.execute('INSERT INTO sessions (id,user_id,cwd,created_at,updated_at) VALUES (?,?,?,1,1)',(self.target,'foreign',str(self.cwd))) + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertEqual(self.row(self.target)[2],'foreign') + def test_source_history_changed(self): + (self.hist/(self.source+'.jsonl')).write_bytes(self.original+b'\n') + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertIsNone(self.row(self.target)) + def test_trigger_rejected(self): + with closing(sqlite3.connect(self.dbpath)) as db, db: db.execute('CREATE TRIGGER evil AFTER INSERT ON sessions BEGIN UPDATE sessions SET title="changed"; END') + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertEqual(self.row(self.source),self.source_row) + @unittest.skipIf(os.name=='nt','Windows symbolic link creation requires optional privilege') + def test_symlink_database_rejected(self): + moved=self.dbpath.with_suffix('.saved'); self.dbpath.rename(moved); self.dbpath.symlink_to(moved) + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + @unittest.skipIf(os.name=='nt','Windows symbolic link creation requires optional privilege') + def test_symlink_sqlite_sidecar_rejected(self): + target=self.root/'sidecar-target'; target.write_text('unchanged') + self.dbpath.with_name(self.dbpath.name+'-wal').symlink_to(target) + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + self.assertEqual(target.read_text(),'unchanged') + def test_target_edited_after_register(self): + register(self.engine,self.receipt) + with closing(sqlite3.connect(self.dbpath)) as db, db: db.execute('UPDATE sessions SET status="running" WHERE id=?',(self.target,)) + with self.assertRaises(RegistryError): register(self.engine,self.receipt) + +if __name__=='__main__': unittest.main() diff --git a/src/plugin/tests/test_router.py b/src/plugin/tests/test_router.py new file mode 100644 index 0000000..f151604 --- /dev/null +++ b/src/plugin/tests/test_router.py @@ -0,0 +1,41 @@ +import json,os,shutil,subprocess,sys,tempfile,unittest,importlib.util +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +spec=importlib.util.spec_from_file_location('router_manage',ROOT/'scripts/manage.py');manage=importlib.util.module_from_spec(spec);spec.loader.exec_module(manage) +class RouterTests(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name);self.router=self.root/'conversation-tools-router.py';shutil.copy2(ROOT/'hooks/router.py',self.router) + self.handler=self.root/'handler.py';self.handler.write_text("import json,sys\nprint(json.dumps({'decision':'block','reason':'SYNTHETIC RECEIPT'}),flush=True)\nsys.exit(2)\n",encoding='utf-8') + self.owners=self.root/'conversation-tools-installed.json';self.owners.write_text(json.dumps({'schema':2,'hook':None,'plugins':{'workbuddy-style':{'python':str(Path(sys.executable).resolve()),'handler':str(self.handler),'shell':'powershell' if os.name=='nt' else 'posix'}}}),encoding='utf-8') + def invoke(self,prompt,stdout=subprocess.PIPE):return subprocess.run([sys.executable,str(self.router)],input=json.dumps({'prompt':prompt}).encode(),stdout=stdout,stderr=subprocess.PIPE) + def test_handled_exit2_even_when_stdout_discarded(self): + self.assertEqual(self.invoke('/workbuddy-style:style-new').returncode,2) + self.assertEqual(self.invoke('/workbuddy-style:style-new',subprocess.DEVNULL).returncode,2) + def test_handler_crash_or_missing_still_exit2(self): + self.handler.write_text('raise RuntimeError("synthetic")',encoding='utf-8');self.assertEqual(self.invoke('/workbuddy-style:style-new').returncode,2) + self.handler.unlink();self.assertEqual(self.invoke('/workbuddy-style:style-new').returncode,2) + def test_handler_allow_is_rejected(self): + self.handler.write_text('print("{}")',encoding='utf-8');self.assertEqual(self.invoke('/workbuddy-style:style-new').returncode,2) + def test_reserved_missing_owner_still_blocks(self): + self.assertEqual(self.invoke('/workbuddy-branch:points').returncode,2) + def test_normal_and_other_prompts_noop(self): + for text in ['ordinary hello','/unrelated:command']: + r=self.invoke(text);self.assertEqual((r.returncode,r.stdout,r.stderr),(0,b'',b'')) + @unittest.skipUnless(os.name=='posix','POSIX shell integration') + def test_posix_guard_maps_missing_interpreter_to2(self): + command=manage.guarded_hook_command([str(self.root/'missing-python'),str(self.router)],'posix') + r=subprocess.run(['/bin/sh','-c',command],capture_output=True);self.assertEqual(r.returncode,2) + r=subprocess.run(['/bin/sh','-e','-c',command],capture_output=True);self.assertEqual(r.returncode,2) + @unittest.skipUnless(os.name=='nt' or shutil.which('pwsh'),'Requires actual PowerShell 7 parser') + def test_powershell_real_parser_and_error_guard(self): + self.assertIsNotNone(shutil.which('pwsh'),'Windows validation requires PowerShell 7; do not silently skip') + script=self.root/"space ' & ; $ ` (中文).py";script.write_text('import json,sys;print(json.dumps(sys.argv[1:]))',encoding='utf-8') + argv=[sys.executable,'-X','utf8',str(script),"quote ' space & ; $ ` (中文)"] + command=manage.guarded_hook_command(argv,'powershell') + r=subprocess.run(['pwsh','-NoProfile','-NonInteractive','-Command',command],capture_output=True,text=True,encoding='utf-8');self.assertEqual(r.returncode,0,r.stderr);self.assertEqual(json.loads(r.stdout),argv[4:]) + r=subprocess.run(['pwsh','-NoProfile','-NonInteractive','-Command',manage.guarded_hook_command([str(self.root/'missing.exe')],'powershell')],capture_output=True);self.assertEqual(r.returncode,2) + for code in (1,2): + command=manage.guarded_hook_command([sys.executable,'-c','import sys;sys.exit('+str(code)+')'],'powershell') + r=subprocess.run(['pwsh','-NoProfile','-NonInteractive','-Command',command],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + self.assertEqual(r.returncode,2) +if __name__=='__main__':unittest.main() diff --git a/src/plugin/workbuddy_native/__init__.py b/src/plugin/workbuddy_native/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/plugin/workbuddy_native/engine.py b/src/plugin/workbuddy_native/engine.py new file mode 100644 index 0000000..f828fbd --- /dev/null +++ b/src/plugin/workbuddy_native/engine.py @@ -0,0 +1,113 @@ +"""No model requests, no source writes, argv-only official CLI cloning.""" +from __future__ import annotations +import json, os, subprocess, time, uuid +from pathlib import Path +from typing import Any +from .model import OperationError, uid, digest, records, boundaries, find, no_links +from .platform import lock, fsync_directory, same_path + +def atomic(path: Path, data: bytes) -> None: + no_links(path) + tmp=path.with_name(path.name+'.tmp-'+str(uuid.uuid4())) + fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) + try: + with os.fdopen(fd,'wb') as f: f.write(data); f.flush(); os.fsync(f.fileno()) + os.replace(tmp,path) + fsync_directory(path.parent) + finally: + if tmp.exists(): tmp.unlink() + +def encode(rows: list[dict]) -> bytes: return ''.join(json.dumps(r,ensure_ascii=False,separators=(',',':'))+'\n' for r in rows).encode() +def save(path: Path, data: dict) -> None: atomic(path,json.dumps(data,ensure_ascii=False,indent=2).encode()) + +class Engine: + def __init__(self, profile: Path, cli: list[str], state: Path): + no_links(profile); no_links(state) + self.profile=profile.resolve(); self.cli=cli; self.state=state + if not cli or any(not isinstance(s,str) or '\0' in s for s in cli): raise OperationError('CLI argv 配置无效') + state.mkdir(parents=True,exist_ok=True,mode=0o700) + if state.is_symlink(): raise OperationError('状态目录不能是符号链接') + + def points(self, session: str, cwd: Path) -> list[dict]: + _,_,rows=self.source(session,cwd) + return [{'message_id':r['id'],'turn':n,'preview':__import__('workbuddy_native.model',fromlist=['visible']).visible(r)[:180]} for n,(_,r) in enumerate(boundaries(rows),1)] + + def source(self, session: str, cwd: Path): + path=find(self.profile,session); data=path.read_bytes(); rows=records(data) + dirs=[r['cwd'] for r in rows if r.get('cwd')] + if not dirs or not all(same_path(d,cwd) for d in dirs) or not cwd.is_dir(): raise OperationError('源会话与当前项目目录不一致') + return path,data,rows + + def branch(self, session: str, boundary: str, title: str, operation: str, cwd: Path) -> dict: + uid(session); uid(operation) + if not isinstance(title,str) or len(title)>120 or any(ord(c)<32 for c in title): raise OperationError('标题应为 0–120 个普通字符') + source,data,rows=self.source(session,cwd) + points=boundaries(rows) + if not points: raise OperationError('没有已完成且工具闭合的回复') + if boundary=='latest': boundary=points[-1][1]['id'] + uid(boundary) + ends={r['id']:i for i,r in points} + if boundary not in ends: raise OperationError('请选择已完成且工具闭合的回复 ID') + request={'source':session,'boundary':boundary,'title_sha256':digest(title.encode()),'cwd':str(cwd.resolve())} + lock_path=self.state/(operation+'.lock') + no_links(lock_path); no_links(self.state/(operation+'.json')) + with lock(lock_path): + journal=self.state/(operation+'.json') + if journal.exists(): + old=json.loads(journal.read_text(encoding='utf-8')) + if old.get('request')!=request: raise OperationError('操作 ID 已用于不同请求') + if old.get('status')=='completed': + target=find(self.profile,old['target']) + if digest(target.read_bytes())!=old['target_sha256']: raise OperationError('目标已变化;禁止重复执行') + return old + raise OperationError('操作未确定;用 recover 命令核查,禁止再次克隆') + target_id=str(uuid.uuid4()); target=source.with_name(target_id+'.jsonl') + if target.exists(): raise OperationError('新目标冲突') + receipt={'operation':operation,'request':request,'target':target_id,'source_sha256':digest(data),'source_size':len(data),'status':'started','started_at':time.time()} + save(journal,receipt) + try: + env=dict(os.environ); env.update(CODEBUDDY_CONFIG_DIR=str(self.profile),WORKBUDDY_CONFIG_DIR=str(self.profile),DISABLE_TELEMETRY='1') + # The verified Windows distribution ships only the lite-WB bundle. + selected='CODEBUDDY_FORCE_LITE_WB_BUNDLE' if os.name=='nt' else 'CODEBUDDY_FORCE_HEADLESS_BUNDLE' + other='CODEBUDDY_FORCE_HEADLESS_BUNDLE' if os.name=='nt' else 'CODEBUDDY_FORCE_LITE_WB_BUNDLE' + env[selected]='1'; env.pop(other,None) + for k in ('CODEBUDDY_PROJECT_CONFIG_DIR','OTEL_LOG_RAW_API_BODIES'): env.pop(k,None) + run=subprocess.run(self.cli+['--print','--input-format','stream-json','--output-format','stream-json','--resume',session,'--fork-session','--session-id',target_id,'--resume-session-at',boundary],cwd=cwd,env=env,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=75,check=False,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0) if os.name=='nt' else 0) + receipt['cli_exit_code']=run.returncode + if run.returncode: raise OperationError('官方 CLI 克隆失败') + if source.read_bytes()!=data: raise OperationError('宿主更新了源历史;停止新分支提交') + if find(self.profile,target_id)!=target: raise OperationError('CLI 输出目录不匹配') + clone_data=target.read_bytes(); clone_rows=records(clone_data); clones={r['id']:r for r in clone_rows if r.get('id')} + for row in rows: + if not row.get('id') or row['type']=='session-meta': continue + clone=clones.get(row['id']) + if clone is None or any(clone.get(k)!=row.get(k) for k in ('type','role','content','callId','call_id','name','arguments','output','parentId','logicalParentId')): raise OperationError('CLI 克隆契约变化') + prefix=rows[:ends[boundary]+1]; ids={r.get('id') for r in prefix if r.get('id')} + final=[r for r in clone_rows if r['type']=='session-meta'] + for row in prefix: + if row['type']=='session-meta': continue + if any(row.get(k) and row[k] not in ids for k in ('parentId','logicalParentId')): raise OperationError('悬空父消息') + r=dict(clones[row['id']]) if row.get('id') else dict(row) + if 'sessionId' in r:r['sessionId']=target_id + final.append(r) + if title: final.append({'type':'custom-title','id':str(uuid.uuid4()),'customTitle':title,'sessionId':target_id}) + final_data=encode(final) + receipt.update(status='prepared',target_sha256=digest(final_data),clone_sha256=digest(clone_data)) + save(journal,receipt) + if source.read_bytes()!=data or target.read_bytes()!=clone_data: raise OperationError('提交前源或目标发生变化') + atomic(target,final_data) + receipt.update(status='completed',finished_at=time.time()); save(journal,receipt) + return receipt + except Exception as exc: + receipt['error_type']=type(exc).__name__; save(journal,receipt) + raise OperationError(f'操作未完成,保留诊断记录:{operation};{exc if isinstance(exc,OperationError) else type(exc).__name__}') from exc + + def recover(self, operation: str) -> dict: + uid(operation); journal=self.state/(operation+'.json') + no_links(journal); no_links(self.state/(operation+'.lock')) + with lock(self.state/(operation+'.lock')): + r=json.loads(journal.read_text(encoding='utf-8')); target=find(self.profile,r['target']) + # Recovery never rewrites a conversation; final atomic write may have succeeded before receipt save. + if r.get('status') in {'prepared','completed'} and digest(target.read_bytes())==r.get('target_sha256'): + r.update(status='completed',recovered_at=time.time()); save(journal,r); return r + raise OperationError('目标未达到已准备哈希;保留新分支待人工核查,不自动删除或重新克隆') diff --git a/src/plugin/workbuddy_native/linux-sessions-columns.json b/src/plugin/workbuddy_native/linux-sessions-columns.json new file mode 100644 index 0000000..5400404 --- /dev/null +++ b/src/plugin/workbuddy_native/linux-sessions-columns.json @@ -0,0 +1,322 @@ +[ + { + "cid": 0, + "name": "id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 1 + }, + { + "cid": 1, + "name": "cwd", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 2, + "name": "user_id", + "type": "TEXT", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 3, + "name": "title", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 4, + "name": "custom_title", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 5, + "name": "status", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'Pending'", + "pk": 0 + }, + { + "cid": 6, + "name": "created_at", + "type": "INTEGER", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 7, + "name": "updated_at", + "type": "INTEGER", + "notnull": 1, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 8, + "name": "last_activity_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 9, + "name": "deleted_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 10, + "name": "is_playground", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + }, + { + "cid": 11, + "name": "source_mode", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 12, + "name": "is_background_automation", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 13, + "name": "mode", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 14, + "name": "model", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 15, + "name": "expert_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 16, + "name": "expert_locale", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 17, + "name": "expert_runtime_identity", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 18, + "name": "expert_marketplace", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 19, + "name": "permission_mode", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 20, + "name": "use_sandbox_cli", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 21, + "name": "project_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 22, + "name": "plugin_context_json", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 23, + "name": "addon_selection", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 24, + "name": "session_settings", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 25, + "name": "last_user_prompt_expert_selection", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 26, + "name": "context_window", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 27, + "name": "buddy_snapshot_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 28, + "name": "buddy_binding_json", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 29, + "name": "thought_level", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 30, + "name": "transport", + "type": "TEXT", + "notnull": 1, + "dflt_value": "'local'", + "pk": 0 + }, + { + "cid": 31, + "name": "conversation_origin", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 32, + "name": "visibility", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 33, + "name": "group_id", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 34, + "name": "group_title", + "type": "TEXT", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 35, + "name": "agent_dirty", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 36, + "name": "agent_dirty_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 37, + "name": "agent_last_synced", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 38, + "name": "verified_at", + "type": "INTEGER", + "notnull": 0, + "dflt_value": null, + "pk": 0 + }, + { + "cid": 39, + "name": "unread", + "type": "INTEGER", + "notnull": 1, + "dflt_value": "0", + "pk": 0 + } +] \ No newline at end of file diff --git a/src/plugin/workbuddy_native/model.py b/src/plugin/workbuddy_native/model.py new file mode 100644 index 0000000..df1d2b8 --- /dev/null +++ b/src/plugin/workbuddy_native/model.py @@ -0,0 +1,88 @@ +"""Conservative adapter for WorkBuddy 5.6.2 / bundled CLI 2.147.0 JSONL.""" +from __future__ import annotations +import json, re, hashlib +from pathlib import Path +from typing import Any + +class OperationError(RuntimeError): pass +UUID = re.compile(r'^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$') +KINDS = {'message','reasoning','function_call','function_call_result','function_call_output','file-history-snapshot','session-meta','ai-title','custom-title','topic'} +def uid(value: Any) -> str: + if not isinstance(value,str) or not UUID.fullmatch(value): raise OperationError('需要小写 UUID') + return value + +def digest(data: bytes) -> str: return hashlib.sha256(data).hexdigest() +def records(data: bytes) -> list[dict[str,Any]]: + if len(data)>32*1024*1024: raise OperationError('历史大于 32 MiB,拒绝自动处理') + result=[]; ids=set() + try: + for line in data.decode('utf-8-sig').splitlines(): + if not line.strip(): continue + row=json.loads(line) + if not isinstance(row,dict) or row.get('type') not in KINDS: raise OperationError('未知历史结构,拒绝猜测适配') + if row.get('id'): + uid(row['id']) + if row['id'] in ids: raise OperationError('重复消息 ID') + ids.add(row['id']) + if row.get('sessionId'): uid(row['sessionId']) + if row.get('subagentInvocations') or (row.get('providerData') or {}).get('toolResult',{}).get('subAgent') is not None: raise OperationError('尚不支持子代理历史图') + result.append(row) + except (ValueError,UnicodeError,AttributeError,TypeError) as exc: raise OperationError('无效历史 JSONL') from exc + if not result: raise OperationError('历史为空') + return result + +def visible(row: dict) -> str: + c=row.get('content',[]) + if isinstance(c,str): return c.strip() + if not isinstance(c,list): raise OperationError('未知消息内容结构') + return '\n'.join(x['text'] for x in c if isinstance(x,dict) and x.get('type') in {'text','input_text','output_text'} and isinstance(x.get('text'),str)).strip() + +def boundaries(rows: list[dict]) -> list[tuple[int,dict]]: + pending=set(); seen=set(); candidates=[]; candidate=None; user_seen=False + for index,row in enumerate(rows): + kind=row['type']; content=row.get('content',[]) + if kind=='message' and row.get('role')=='user' and visible(row): + if candidate is not None and not pending: candidates.append(candidate) + candidate=None; user_seen=True + if kind=='reasoning': candidate=None + calls=[]; results=[] + if kind=='function_call': calls.append(row.get('callId') or row.get('call_id')) + if kind in {'function_call_result','function_call_output'}: results.append(row.get('callId') or row.get('call_id')) + for item in content if isinstance(content,list) else []: + if not isinstance(item,dict): raise OperationError('未知消息内容项') + if item.get('type')=='tool_use': calls.append(item.get('id')) + if item.get('type')=='tool_result': results.append(item.get('tool_use_id')) + for call in calls: + if not isinstance(call,str) or not call or call in seen: raise OperationError('工具 ID 缺失或重复') + seen.add(call); pending.add(call); candidate=None + for call in results: + if call not in pending: raise OperationError('未匹配的工具结果') + pending.remove(call) + # Hook/auth skipRun output is not a completed model turn. + if kind=='message' and row.get('role')=='assistant': + candidate=None + if user_seen and row.get('status')=='completed' and not pending and visible(row) and not (row.get('providerData') or {}).get('skipRun'): + uid(row.get('id')); candidate=(index,row) + if candidate is not None and not pending: candidates.append(candidate) + return candidates + +def no_links(path: Path) -> None: + if str(path).startswith('\\\\'): raise OperationError('不支持 UNC/网络共享路径,请使用本地磁盘') + for p in (path,*path.parents): + if p.is_symlink(): raise OperationError('路径含符号链接,拒绝写入') + try: + if getattr(p.lstat(),'st_file_attributes',0)&0x400: raise OperationError('路径含 Windows reparse point/junction,拒绝写入') + except FileNotFoundError: pass + +def inside(path: Path, root: Path) -> Path: + no_links(path) + if path.is_symlink() or not path.is_file(): raise OperationError('文件不存在或是符号链接') + resolved=path.resolve() + if root.resolve() not in resolved.parents: raise OperationError('路径不在配置目录内') + return resolved + +def find(profile: Path, session: str) -> Path: + no_links(profile/'projects') + matches=list((profile/'projects').glob(f'*/{uid(session)}.jsonl')) + if len(matches)!=1: raise OperationError('会话不存在或重复') + return inside(matches[0],profile/'projects') diff --git a/src/plugin/workbuddy_native/platform.py b/src/plugin/workbuddy_native/platform.py new file mode 100644 index 0000000..d91d5c0 --- /dev/null +++ b/src/plugin/workbuddy_native/platform.py @@ -0,0 +1,69 @@ +"""Small stdlib-only OS boundary; no application or profile mutations.""" +from __future__ import annotations +from contextlib import contextmanager +import errno +import os +from pathlib import Path +from typing import Iterator, BinaryIO + +class LockBusy(BlockingIOError): + """The operation is already locked by this or another process.""" + +@contextmanager +def lock(path: Path) -> Iterator[BinaryIO]: + """Acquire one nonblocking exclusive lock; callers validate path containment. + + Lock files are persistent, not deleted on unlock (unlinking permits competing + locks on different inodes). Windows locks exactly byte zero on every path. + """ + path=Path(path) + if str(path).startswith('\\\\'): raise OSError('UNC/network lock paths are unsupported') + for candidate in (path,*path.parents): + if candidate.is_symlink(): raise OSError('Lock path contains a symbolic link') + try: + # FILE_ATTRIBUTE_REPARSE_POINT also covers junctions on Python 3.10/3.11. + if getattr(candidate.lstat(),'st_file_attributes',0)&0x400: + raise OSError('Lock path contains a Windows reparse point/junction') + except FileNotFoundError: pass + fd=os.open(path,os.O_RDWR|os.O_CREAT|getattr(os,'O_NOFOLLOW',0),0o600) + with os.fdopen(fd,'r+b',buffering=0) as stream: + acquired=False + try: + if os.name=='nt': + import msvcrt + if os.fstat(stream.fileno()).st_size==0: + stream.write(b'\0'); stream.flush() + stream.seek(0) + try: msvcrt.locking(stream.fileno(),msvcrt.LK_NBLCK,1) + except OSError as exc: + if exc.errno in {errno.EACCES,errno.EAGAIN,errno.EDEADLK} or getattr(exc,'winerror',None) in {33,36}: + raise LockBusy('Operation is already running') from exc + raise + else: + import fcntl + try: fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError as exc: raise LockBusy('Operation is already running') from exc + acquired=True + yield stream + finally: + if acquired: + if os.name=='nt': + import msvcrt + stream.seek(0); msvcrt.locking(stream.fileno(),msvcrt.LK_UNLCK,1) + else: + import fcntl + fcntl.flock(stream,fcntl.LOCK_UN) + +def fsync_directory(path: Path) -> None: + """Flush rename metadata on POSIX; directory handles are not portable on Win.""" + if os.name=='nt': return + fd=os.open(path,os.O_RDONLY|getattr(os,'O_DIRECTORY',0)) + try: os.fsync(fd) + finally: os.close(fd) + +def same_path(left: str | Path, right: str | Path) -> bool: + """Resolved path identity with OS-native case rules, not string casefold.""" + a=str(Path(left).resolve()); b=str(Path(right).resolve()) + if Path(a).exists() and Path(b).exists(): + return os.path.samefile(a,b) + return os.path.normcase(a)==os.path.normcase(b) if os.name=='nt' else a==b diff --git a/src/plugin/workbuddy_native/registry.py b/src/plugin/workbuddy_native/registry.py new file mode 100644 index 0000000..6ffb8c1 --- /dev/null +++ b/src/plugin/workbuddy_native/registry.py @@ -0,0 +1,157 @@ +"""Insert-only desktop discovery adapter. No schema migrations or source updates.""" +from __future__ import annotations +import json, sqlite3, time +from contextlib import contextmanager +from .platform import lock, LockBusy, same_path +from pathlib import Path +from typing import TYPE_CHECKING +from .model import OperationError, uid, digest, find, records, no_links +from .engine import save +if TYPE_CHECKING: + from .engine import Engine + +_REQUIRED = {"id", "cwd", "user_id", "title", "custom_title", "status", "created_at", + "updated_at", "deleted_at", "transport", "is_playground", "unread"} +_COPY = ("mode", "model", "project_id", "source_mode") +_NEVER_COPY = {"permission_mode", "use_sandbox_cli", "plugin_context_json", "buddy_snapshot_id", "buddy_binding_json", + "expert_id", "expert_locale", "expert_runtime_identity", "expert_marketplace"} +_KNOWN_COLUMNS = _REQUIRED | set(_COPY) | {"last_activity_at", "is_background_automation", "expert_id", + "expert_locale", "expert_runtime_identity", "expert_marketplace", "permission_mode", "use_sandbox_cli", + "plugin_context_json", "last_user_prompt_expert_selection", "context_window", "addon_selection", + "session_settings", "thought_level", "buddy_snapshot_id", "buddy_binding_json", "conversation_origin", + "visibility", "group_id", "group_title", "agent_dirty", "agent_dirty_at", "agent_last_synced", "verified_at"} + + +class RegistryError(OperationError): pass + +def safe_path(path: Path) -> None: + try: no_links(path) + except OperationError as exc: raise RegistryError(str(exc)) from exc + +@contextmanager +def registry_lock(path: Path): + try: + with lock(path) as handle: yield handle + except LockBusy as exc: raise RegistryError('桌面登记正在执行') from exc + +def rowhash(row) -> str: + return digest(json.dumps(dict(row),ensure_ascii=False,sort_keys=True,separators=(",", ":")).encode()) + +def schema(db: sqlite3.Connection, fields: set[str]) -> set[str]: + extended=db.execute("PRAGMA table_xinfo(sessions)").fetchall() + if any(r[6] for r in extended): raise RegistryError("未知隐藏或生成字段;拒绝写入") + columns=[tuple(r[:6]) for r in extended] + names={r[1] for r in columns} + expected=json.loads(Path(__file__).with_name('linux-sessions-columns.json').read_text(encoding='utf-8')) + actual=[dict(zip(('cid','name','type','notnull','dflt_value','pk'),r)) for r in columns] + if actual!=expected: raise RegistryError('桌面 schema 不匹配已核对的 40 列适配器;拒绝写入') + if not _REQUIRED <= names or not names <= _KNOWN_COLUMNS: + raise RegistryError("未知桌面数据库结构;拒绝写入") + if [r[1] for r in columns if r[5]] != ['id']: + raise RegistryError("sessions.id 主键不匹配") + for r in columns: + if r[1] in _NEVER_COPY and r[4] is not None and str(r[4]).strip().upper()!='NULL': + raise RegistryError("安全字段具有未核对默认值") + if r[3] and r[4] is None and r[1] not in fields: + raise RegistryError("未处理的必填字段") + if db.execute("SELECT 1 FROM sqlite_master WHERE type='trigger' AND tbl_name='sessions'").fetchone() or db.execute("PRAGMA foreign_key_list(sessions)").fetchall(): + raise RegistryError("sessions 存在触发器或外键;拒绝写入") + return names + +def source_ok(row, cwd: str) -> None: + if row is None or not row['user_id'] or row['deleted_at'] is not None or row['transport']!='local' or row['is_playground']!=0: + raise RegistryError("源桌面会话不是有效本地普通会话") + if not row['cwd'] or not same_path(row['cwd'],cwd): + raise RegistryError("桌面源会话工作目录不一致") + +def register(engine: Engine, receipt: dict) -> dict: + """Insert metadata for one verified branch; absent DB is an explicit CLI-only result. + + Crash after COMMIT is recovered by matching the precommitted insertion digest. + An uncertain absent row is not reinserted automatically. + """ + operation=uid(receipt.get('operation')); target_id=uid(receipt.get('target')) + request=receipt.get('request',{}); source_id=uid(request.get('source')) + if source_id==target_id: raise RegistryError("源和目标不能相同") + journal=engine.state/(operation+'.json') + safe_path(journal) + if journal.is_symlink() or not journal.is_file(): raise RegistryError("缺少操作记录") + stored=json.loads(journal.read_text(encoding='utf-8')) + for key in ('operation','request','target','source_sha256','source_size','target_sha256','status'): + if stored.get(key)!=receipt.get(key): raise RegistryError("操作记录与结果不一致") + if stored.get('status')!='completed': raise RegistryError("分支尚未完成") + database=engine.profile/'workbuddy.db' + if not database.exists(): return {'status':'cli_only','reason':'desktop_database_absent','target':target_id} + safe_path(database) + for suffix in ('-wal','-shm','-journal'): safe_path(database.with_name(database.name+suffix)) + if database.is_symlink() or not database.is_file(): raise RegistryError("数据库不是普通本地文件") + source=find(engine.profile,source_id); target=find(engine.profile,target_id) + if not same_path(source.parent,target.parent): raise RegistryError("新分支目录不一致") + source_data=source.read_bytes(); source_hash=digest(source_data); target_hash=digest(target.read_bytes()) + size=stored.get('source_size',len(source_data)) + if type(size) is not int or not 0 dict: + uid(operation) + seed_arg=args.get('seed') + if not isinstance(seed_arg,str) or not Path(seed_arg).is_absolute(): raise OperationError('seed 必须是用户指定的本地绝对路径') + seed=Path(seed_arg); no_links(seed) + if seed.is_symlink() or not seed.is_file() or seed.stat().st_size>16384: raise OperationError('seed 必须是小于 16 KiB 的普通 JSON 文件') + data=seed.read_bytes(); spec=json.loads(data) + if not isinstance(spec,dict) or set(spec)!={'schema','messages'} or type(spec['schema']) is not int or spec['schema']!=1: raise OperationError('seed 结构应为 schema:1 和 messages') + messages=spec['messages'] + if not isinstance(messages,list) or len(messages) not in {2,4}: raise OperationError('seed 仅接受 1–2 组最小问答') + for i,m in enumerate(messages): + if not isinstance(m,dict) or set(m) not in ({'role','text'},{'role','text','reasoning'}) or m['role']!=('user' if i%2==0 else 'assistant') or not isinstance(m['text'],str) or not 1<=len(m['text'])<=2000 or '\0' in m['text']: raise OperationError('seed 消息格式或长度不支持') + if 'reasoning' in m and (m['role']!='assistant' or not isinstance(m['reasoning'],str) or not 1<=len(m['reasoning'])<=4000 or '\0' in m['reasoning']): raise OperationError('reasoning 仅允许 assistant 的 1–4000 字纯文本') + title=args.get('title','') + if not isinstance(title,str) or len(title)>120 or any(ord(c)<32 for c in title): raise OperationError('标题无效') + source,source_data,_=engine.source(session,cwd) + request={'source':session,'boundary':'style-seed','title_sha256':digest(title.encode()),'cwd':str(cwd.resolve()),'seed_sha256':digest(data)} + journal=engine.state/(operation+'.json') + no_links(journal); no_links(engine.state/(operation+'.lock')) + with lock(engine.state/(operation+'.lock')): + if journal.exists(): + old=json.loads(journal.read_text(encoding='utf-8')) + if old.get('request')!=request: raise OperationError('操作 ID 已用于另一请求') + if old.get('status')=='completed' and digest(find(engine.profile,old['target']).read_bytes())==old.get('target_sha256'): return old + raise OperationError('已有操作需 recover 核查') + sid=str(uuid.uuid4()); target=source.with_name(sid+'.jsonl'); rows=[]; parent=None + for i,m in enumerate(messages): + if m.get('reasoning'): + rid=str(uuid.uuid4()); reason={'type':'reasoning','id':rid,'parentId':parent,'sessionId':sid,'cwd':str(cwd.resolve()),'timestamp':int(time.time()*1000)+i,'content':[],'rawContent':[{'type':'text','text':m['reasoning']}]} + rows.append(reason); parent=rid + mid=str(uuid.uuid4()); row={'id':mid,'timestamp':int(time.time()*1000)+i,'type':'message','role':m['role'],'content':[{'type':'input_text' if i%2==0 else 'output_text','text':m['text']}],'sessionId':sid,'cwd':str(cwd.resolve())} + if parent: row['parentId']=parent + if i%2: row['status']='completed' + rows.append(row); parent=mid + if title:rows.append({'type':'custom-title','id':str(uuid.uuid4()),'sessionId':sid,'customTitle':title}) + wire=encode(rows) + receipt={'operation':operation,'request':request,'target':sid,'source_sha256':digest(source_data),'source_size':len(source_data),'target_sha256':digest(wire),'status':'prepared','kind':'style-new','style_default':'off','no_prompt_submitted':True} + save(journal,receipt) + if source.read_bytes()!=source_data or seed.read_bytes()!=data: raise OperationError('来源或 seed 已变化') + # Atomic no-clobber publication, never overwrite an existing UUID. + temp=target.with_name(target.name+'.'+operation+'.tmp'); atomic(temp,wire) + try: + os.link(temp,target) + fsync_directory(target.parent) + finally: temp.unlink(missing_ok=True) + receipt['status']='completed'; save(journal,receipt) + return receipt diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 0000000..148b19d --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,19 @@ +import json,subprocess,sys,tempfile,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +class PackagingTests(unittest.TestCase): + def test_install_idempotence_uninstall_preserves_unrelated_hooks(self): + with tempfile.TemporaryDirectory() as td: + project=Path(td);folder=project/'.codebuddy';folder.mkdir();settings=folder/'settings.local.json' + unrelated={'hooks':[{'type':'command','command':'echo unrelated'}]};settings.write_text(json.dumps({'hooks':{'UserPromptSubmit':[unrelated]}}),encoding='utf-8') + script=ROOT/'plugins/workbuddy-tools/scripts/manage.py' + for _ in range(2):subprocess.run([sys.executable,str(script),'install','--project',td,'--cli',sys.executable],check=True,stdout=subprocess.DEVNULL) + self.assertEqual(len(json.loads(settings.read_text(encoding='utf-8'))['hooks']['UserPromptSubmit']),2) + subprocess.run([sys.executable,str(script),'uninstall','--project',td],check=True,stdout=subprocess.DEVNULL) + self.assertEqual(json.loads(settings.read_text(encoding='utf-8'))['hooks']['UserPromptSubmit'],[unrelated]) + def test_single_plugin_all_commands(self): + root=ROOT/'plugins/workbuddy-tools' + self.assertEqual(json.loads((root/'.workbuddy-plugin/plugin.json').read_text(encoding='utf-8'))['name'],'workbuddy-tools') + self.assertEqual({p.stem for p in (root/'commands').glob('*.md')},{'branch','points','style-new','recover','status'}) + self.assertEqual([p.name for p in (ROOT/'plugins').iterdir() if p.is_dir()],['workbuddy-tools']) +if __name__=='__main__':unittest.main()