From 3e84c3722312e77494f64afa14318f4f45a39f40 Mon Sep 17 00:00:00 2001 From: mindcarver Date: Mon, 23 Nov 2026 14:55:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(antigravity):=20=E5=B0=86=20Antigravity=20?= =?UTF-8?q?2.0=20=E6=AD=A3=E5=BC=8F=E7=BA=B3=E5=85=A5=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=B9=B6=E9=80=82=E9=85=8D=20Stop=20Hook=20?= =?UTF-8?q?=E5=8D=8F=E8=AE=AE=20(Refs=20#142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/platform-capabilities.json | 34 ++ docs/installation.md | 76 +++- hooks/check-state.mjs | 81 +++- scripts/refresh-install.mjs | 227 +++++++++- scripts/verify-install.mjs | 648 ++++++++++++++++++++++++++- tests/check-state.test.mjs | 180 ++++++++ tests/platform-capabilities.test.mjs | 433 +++++++++++++++++- tests/refresh-install.test.mjs | 193 +++++++- 8 files changed, 1845 insertions(+), 27 deletions(-) diff --git a/config/platform-capabilities.json b/config/platform-capabilities.json index 16981b3..812373c 100644 --- a/config/platform-capabilities.json +++ b/config/platform-capabilities.json @@ -260,6 +260,40 @@ "summary": "`zcode plugins list --json` 提供 enabled、version、rootPath、skillCount 与 hookDetails;检查完整 Skill/Hook 载荷和两个可运行 Hook", "manualFallback": "ZCode CLI 不可用时保持 UNVERIFIED,不自动安装宿主" } + }, + { + "id": "antigravity", + "displayName": "Antigravity", + "installation": { + "mode": "plugin-dir", + "configRoot": ".gemini/config", + "configRootOverride": { + "environment": "ANTIGRAVITY_CONFIG_DIR" + }, + "pluginDir": "plugins/thinloop", + "skillRoot": ".gemini/config/plugins/thinloop/skills", + "skillRootOverride": { + "environment": "ANTIGRAVITY_CONFIG_DIR", + "suffix": "plugins/thinloop/skills" + }, + "summary": "在 `~/.gemini/config/plugins/thinloop` 装配全局插件(`plugin.json`、`hooks.json`、`rules/AGENTS.md` 与 `skills`/`hooks` 源码软链)", + "takesEffect": "自动发现,下一轮生效" + }, + "capabilities": { + "hookHandler": "hooks/check-state.mjs", + "hooks": [ + { + "event": "Stop", + "kind": "antigravity-plugin-hook", + "source": "hooks.json", + "name": "thinloop-continuity" + } + ] + }, + "verification": { + "mode": "plugin-dir", + "summary": "核对 `~/.gemini/config/plugins/thinloop` 的白名单 `plugin.json`、根级扁平 `hooks.json`(`Stop`)、纯路由内核 `rules/AGENTS.md`、十五个源码 Skill 与无 `skills.json`/`skills/scd-*` 重复暴露" + } } ] } diff --git a/docs/installation.md b/docs/installation.md index 401dbb9..54e606f 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -15,12 +15,14 @@ | Claude Code | 安装完整插件 | 更新后重启或重新加载插件 | | WorkBuddy | 安装完整插件 | 更新后重启 WorkBuddy | | ZCode | 安装完整插件 | 更新后新建会话 | +| Antigravity | 在 `~/.gemini/config/plugins/thinloop` 装配全局插件(`plugin.json`、`hooks.json`、`rules/AGENTS.md` 与 `skills`/`hooks` 源码软链) | 自动发现,下一轮生效 | -Skill 链接随源码仓库更新,但默认不启用连续性 Hook;Claude Code、WorkBuddy -和 ZCode 的完整插件会额外启用各自支持的 Hook,DeepSeek Harness 则通过把 -`.dsh-plugin/continuity.mjs` 挂载到 DSH 的 home 级用户 patch 层启用 -`agent/turn-stopping` 连续性闸门。不要在同一个 Agent 中同时安装完整插件和 -个人 Skill 链接,以免重复暴露同名能力。 +Skill 链接随源码仓库更新,但默认不启用连续性 Hook;Claude Code、WorkBuddy、 +ZCode 与 Antigravity 的完整/全局插件会额外启用各自支持的 Hook,DeepSeek +Harness 则通过把 `.dsh-plugin/continuity.mjs` 挂载到 DSH 的 home 级用户 patch +层启用 `agent/turn-stopping` 连续性闸门。不要在同一个 Agent 中同时安装完整插件 +和个人 Skill 链接(或在 Antigravity 中同时在 `~/.gemini/config/skills.json` / +`~/.gemini/config/skills/` 暴露 Thinloop Skill),以免重复暴露同名能力。 ## Codex、OpenCode、Pi、CodeWhale、Reasonix 与 DeepSeek Harness @@ -231,6 +233,53 @@ WorkBuddy 5.3.5 内置的 CodeBuddy 运行时读取 上下文注入。ZCode 不支持 Codex 专用的 `PreCompact` 事件,因此当前运行时会 记录一条 warning 并只跳过该事件,不影响上述两个 ZCode Hook。 +## Antigravity 2.0 全局插件 + +Antigravity 2.0 自动发现 `~/.gemini/config/plugins/thinloop`(支持以 +`ANTIGRAVITY_CONFIG_DIR` 环境变量覆盖为 `$ANTIGRAVITY_CONFIG_DIR/plugins/thinloop`)。 +先审查仓库中的 Skill 与 `hooks/check-state.mjs`,再使用一键装配命令创建插件载荷: + +```bash +# 首次装配全局插件(严禁手改 ~/.gemini/config/config.json) +node scripts/refresh-install.mjs --platform antigravity --install + +# 刷新已安装的全局插件载荷(未安装时拒绝隐式安装) +node scripts/refresh-install.mjs --platform antigravity + +# 只读校验插件载荷与防重复暴露冲突 +node scripts/verify-install.mjs --platform antigravity +``` + +插件载荷包含四部分: + +1. `plugin.json`:仅保留 Antigravity 白名单顶层字段(`name`、`displayName`、 + 与 `.codex-plugin/plugin.json` 同步的 `version`、`description`、`author`、 + `homepage`、`repository` 与三条中文 `suggestedPrompts`),不写入未知顶层字段。 +2. `hooks.json`(位于插件根目录)与 `hooks` 源码软链:使用 Antigravity 扁平 + `Stop` 格式调用 `node "./hooks/check-state.mjs" --platform antigravity`。 + 当 `.scd/tasks/current.md` 不可恢复且正常结束(`NO_TOOL_CALL`)时返回 + `{"decision":"continue","reason":...}`;遇到 `USER_CANCELED`、`ERROR`、 + `MAX_INVOCATIONS` 或 `continuationActive: true` 时返回 `{}` 直接放行,避免 + 与用户取消冲突或死循环。 +3. `rules/AGENTS.md`:仅包含由 `config/routing-kernel.json` 渲染出的十条 + Thinloop Routing Kernel(无 YAML frontmatter,绝不包含 Thinloop 仓库自用的 + `Thinloop Delivery Default`)。 +4. `skills` 源码软链:指向源码仓库 `skills/`,自动暴露全部十五个 Skill。 + +**严禁手工修改 `~/.gemini/config/config.json`**;插件启用或禁用应通过 +Antigravity Customizations 界面切换,改动自动发现、下一轮生效。 + +### 防与 `skills.json` / 全局 `skills/` 重复暴露 + +全局插件已经通过 `~/.gemini/config/plugins/thinloop/skills` 暴露全部十五个 +Thinloop Skill。若此前在 `~/.gemini/config/skills.json` 的 `entries` 中指向了 +Thinloop `skills/`,或在 `~/.gemini/config/skills/` 放置了同名 `scd-*` 链接, +安装全局插件后请移除对应条目,避免 Antigravity 重复暴露同名 Skill。 + +`node scripts/verify-install.mjs --platform antigravity` 为纯只读检查: +核对 `~/.gemini/config/plugins/thinloop` 的白名单 `plugin.json`、根级扁平 `hooks.json`(`Stop`)、纯路由内核 `rules/AGENTS.md`、十五个源码 Skill 与无 `skills.json`/`skills/scd-*` 重复暴露。插件目录不存在时返回 +`NOT_INSTALLED`;检测到上述任一重复暴露冲突时返回 `FAIL` 并指出移除位置。 + ## 每次交付核对三端 每次 Thinloop 交付后都核对已安装的 ZCode、Claude Code 和 Codex;只改 README、 @@ -291,11 +340,15 @@ claude plugin update thinloop@thinloop --scope user # WorkBuddy 完整插件(安装了 CodeBuddy CLI 时) codebuddy plugin update thinloop@thinloop --scope user + +# Antigravity 2.0 全局插件(仅刷新已安装目录) +node scripts/refresh-install.mjs --platform antigravity ``` - Claude Code:命令成功后重启客户端,或在交互会话重新加载插件。 - WorkBuddy:也可以在插件页刷新市场后更新 Thinloop;完成后重启 WorkBuddy。 - ZCode:Settings → Plugins → Refresh → `thinloop` → Update;更新后新建会话。 +- Antigravity:运行 `node scripts/refresh-install.mjs --platform antigravity` 原子刷新 `plugin.json`、`hooks.json`、`rules/AGENTS.md` 与 `skills`/`hooks` 软链;自动发现,下一轮生效。 - 升级到 v0.13.1:确认当前列表中存在 `scd-knowledge`、`scd-next`、`scd-execute`、`scd-reengineering`、`scd-project` 与 `scd-quickdev`, 并且插件版本与当前源码仓库一致。Knowledge 仍只在用户显式调用时工作,写入前仍需确认具体草稿和目标。 - 升级到 v0.13.3:确认当前列表中存在十二个 Skill,包括新增的 `scd-interview`;个人面试题默认存到 @@ -346,11 +399,11 @@ node scripts/verify-install.mjs 检查器从 [`config/platform-capabilities.json`](../config/platform-capabilities.json) -读取九个平台的能力契约,遵循 `CODEX_HOME`、`XDG_CONFIG_HOME`、 -`PI_CODING_AGENT_DIR/skills`、`CODEWHALE_SKILLS_DIR`、`~/.reasonix/skills` -与 `DSH_HOME`,只读取 Skill -链接、CodeWhale 的无网络 `doctor --json` 报告、Claude Code 插件清单及本地 -插件内容; +读取十个平台的能力契约,遵循 `CODEX_HOME`、`XDG_CONFIG_HOME`、 +`PI_CODING_AGENT_DIR/skills`、`CODEWHALE_SKILLS_DIR`、`~/.reasonix/skills`、 +`DSH_HOME` 与 `ANTIGRAVITY_CONFIG_DIR`,只读取 Skill +链接、CodeWhale 的无网络 `doctor --json` 报告、Claude Code / ZCode 插件清单及 +Antigravity 全局插件目录(含 `skills.json` 与全局 `skills/` 防重复暴露检查); 不安装、修复、覆盖、重启或重新加载任何 Agent。状态和退出码见 [验证指南](./verification.md)。 @@ -398,6 +451,9 @@ ZCode:使用 $scd-execute 继续这个已批准的 Initiative,执行当前 ZCode:使用 $scd-next 只读检查当前项目进度和下一步。 ZCode:使用 $scd-reengineering 重新实现这个项目并保留选定兼容契约。 ZCode:使用 $scd-evolve 诊断本次使用过的 Thinloop Skill。 +Antigravity:检查当前项目状态并告诉我唯一建议下一步(触发 scd-next)。 +Antigravity:按 Thinloop QuickDev 修复这个单交付问题并完成独立验收。 +Antigravity:把已批准的 PRD 拆分为多 Issue 依赖图但不直接开工(触发 scd-project)。 ``` 方案与开工前提:按[计划确认契约](../skills/scd-quickdev/references/planning-contract.md)先确认具体技术选择、精确Git计划版本和开工范围,再连续完成普通交付;新选择或实质变更重新确认。纯状态查询不创建开发计划。 diff --git a/hooks/check-state.mjs b/hooks/check-state.mjs index 8793cd6..68ed083 100644 --- a/hooks/check-state.mjs +++ b/hooks/check-state.mjs @@ -3,6 +3,19 @@ import path from "node:path"; import { RELATIVE_STATE_PATH, validateState } from "./validate-state.mjs"; +function parsePlatformArg(argv = process.argv.slice(2)) { + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === "--platform") { + return argv[index + 1] || null; + } + if (arg.startsWith("--platform=")) { + return arg.slice("--platform=".length) || null; + } + } + return null; +} + async function readStdin() { let input = ""; process.stdin.setEncoding("utf8"); @@ -16,12 +29,26 @@ function emit(payload) { process.stdout.write(`${JSON.stringify(payload)}\n`); } -function block(eventName, managedBy, issues) { +function allow(isAntigravity) { + if (isAntigravity) { + emit({}); + } +} + +function block(eventName, managedBy, issues, { isAntigravity = false } = {}) { const issueList = issues.map((issue) => `- ${issue}`).join("\n"); const message = `${managedBy} paused ${eventName} because .scd/tasks/current.md is not resumable:\n` + `${issueList}\nUpdate the note, then retry the lifecycle event.`; + if (isAntigravity) { + emit({ + decision: "continue", + reason: message, + }); + return; + } + if ( process.env.ZCODE_PLUGIN_ROOT && eventName === "SessionStart" @@ -59,12 +86,36 @@ function block(eventName, managedBy, issues) { } async function main() { + const platformArg = parsePlatformArg(); + let isAntigravity = platformArg === "antigravity"; + try { const hookInput = await readStdin(); + const hasKnownPluginEnv = Boolean( + process.env.CLAUDE_PLUGIN_ROOT || + process.env.ZCODE_PLUGIN_ROOT || + process.env.CODEBUDDY_PLUGIN_ROOT, + ); + if ( + !platformArg && + !hasKnownPluginEnv && + typeof hookInput.hookEventName === "string" && + hookInput.hookEventName.trim().length > 0 + ) { + isAntigravity = true; + } + + const workspaceFallback = + isAntigravity && + Array.isArray(hookInput.workspacePaths) && + typeof hookInput.workspacePaths[0] === "string" && + hookInput.workspacePaths[0].trim() + ? hookInput.workspacePaths[0] + : ""; const cwd = typeof hookInput.cwd === "string" && hookInput.cwd.trim() ? hookInput.cwd - : process.cwd(); + : workspaceFallback || process.cwd(); const statePath = path.resolve(cwd, RELATIVE_STATE_PATH); let markdown; @@ -72,6 +123,7 @@ async function main() { markdown = await fs.readFile(statePath, "utf8"); } catch (error) { if (error?.code === "ENOENT") { + allow(isAntigravity); return; } throw error; @@ -79,11 +131,28 @@ async function main() { const result = validateState(markdown); if (!result.managed || result.issues.length === 0) { + allow(isAntigravity); return; } - const eventName = hookInput.hook_event_name || "lifecycle event"; + const eventName = + hookInput.hookEventName || hookInput.hook_event_name || "lifecycle event"; + if (isAntigravity && (eventName === "Stop" || eventName === "lifecycle event")) { + const hasTerminationReason = + hookInput.terminationReason !== undefined && + hookInput.terminationReason !== null && + hookInput.terminationReason !== ""; + if ( + (hasTerminationReason && hookInput.terminationReason !== "NO_TOOL_CALL") || + hookInput.continuationActive === true + ) { + allow(true); + return; + } + } + if ( + !isAntigravity && process.env.CLAUDE_PLUGIN_ROOT && !process.env.CODEBUDDY_PLUGIN_ROOT && !process.env.ZCODE_PLUGIN_ROOT && @@ -101,8 +170,12 @@ async function main() { }); return; } - block(eventName, result.managedBy, result.issues); + block(eventName, result.managedBy, result.issues, { isAntigravity }); } catch (error) { + if (isAntigravity) { + emit({}); + return; + } emit({ continue: true, systemMessage: diff --git a/scripts/refresh-install.mjs b/scripts/refresh-install.mjs index aa4f3bd..70d1e31 100644 --- a/scripts/refresh-install.mjs +++ b/scripts/refresh-install.mjs @@ -5,12 +5,210 @@ import os from "node:os"; import path from "node:path"; import { spawn, spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; -import { inspectInstallations } from "./verify-install.mjs"; +import { + expectedAntigravityHooks, + expectedAntigravityManifest, + expectedAntigravityRules, + inspectInstallations, + resolveAntigravityPaths, +} from "./verify-install.mjs"; import { pluginList } from "./plugin-list.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const pluginId = "thinloop@thinloop"; +function atomicWriteFile(destination, content) { + const temporary = `${destination}.thinloop-${process.pid}`; + fs.writeFileSync(temporary, content, "utf8"); + try { + fs.renameSync(temporary, destination); + } finally { + if (fs.existsSync(temporary)) fs.unlinkSync(temporary); + } +} + +function atomicSymlink(target, destination) { + const temporary = `${destination}.thinloop-${process.pid}`; + const linkType = process.platform === "win32" ? "junction" : "dir"; + fs.symlinkSync(target, temporary, linkType); + try { + if (process.platform === "win32") { + try { + if (fs.lstatSync(destination).isSymbolicLink()) fs.unlinkSync(destination); + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + } + fs.renameSync(temporary, destination); + } finally { + try { + fs.lstatSync(temporary); + fs.unlinkSync(temporary); + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + } +} + +function validateAntigravityPluginDir(pluginDir, { allowCreate }) { + let exists = false; + let legacySkillsDir = false; + + try { + const dirLstat = fs.lstatSync(pluginDir); + exists = true; + if (dirLstat.isSymbolicLink() || !dirLstat.isDirectory()) { + const stat = fs.statSync(pluginDir); + if (!stat.isDirectory()) { + throw new Error(`Refusing to modify non-directory: ${pluginDir}`); + } + } + } catch (error) { + if (error?.code === "ENOENT") { + if (!allowCreate) { + throw new Error( + "No installed Antigravity Thinloop plugin; do not install a missing client implicitly", + ); + } + return { exists: false, legacySkillsDir: false }; + } + throw error; + } + + const manifestPath = path.join(pluginDir, "plugin.json"); + let existingManifest; + try { + existingManifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + } catch { + throw new Error( + `Not an owned Antigravity Thinloop plugin (missing or unreadable plugin.json): ${pluginDir}`, + ); + } + if (existingManifest?.name !== "thinloop") { + throw new Error(`Not an owned Antigravity Thinloop plugin: ${pluginDir}`); + } + + for (const filePath of [ + manifestPath, + path.join(pluginDir, "hooks.json"), + path.join(pluginDir, "rules", "AGENTS.md"), + ]) { + try { + if (fs.lstatSync(filePath).isDirectory()) { + throw new Error(`Refusing to replace directory with file: ${filePath}`); + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + } + + const rulesDir = path.join(pluginDir, "rules"); + try { + if (!fs.statSync(rulesDir).isDirectory()) { + throw new Error(`Refusing to replace non-directory: ${rulesDir}`); + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + + const hooksLink = path.join(pluginDir, "hooks"); + try { + if (!fs.lstatSync(hooksLink).isSymbolicLink()) { + throw new Error(`Refusing to replace non-link: ${hooksLink}`); + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + + const skillsLink = path.join(pluginDir, "skills"); + try { + const skillsStat = fs.lstatSync(skillsLink); + if (!skillsStat.isSymbolicLink()) { + if (!skillsStat.isDirectory()) { + throw new Error(`Refusing to replace non-link: ${skillsLink}`); + } + for (const entry of fs.readdirSync(skillsLink, { withFileTypes: true })) { + const entryPath = path.join(skillsLink, entry.name); + if (!entry.name.startsWith("scd-") || !fs.lstatSync(entryPath).isSymbolicLink()) { + throw new Error(`Refusing to replace non-link: ${entryPath}`); + } + } + legacySkillsDir = true; + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + + return { exists, legacySkillsDir }; +} + +function assembleAntigravityPlugin({ + sourceRoot, + homeDir, + environment, + platform, + allowCreate, +}) { + const { pluginDir } = resolveAntigravityPaths(platform, homeDir, environment); + const state = validateAntigravityPluginDir(pluginDir, { allowCreate }); + const manifestText = `${JSON.stringify(expectedAntigravityManifest(sourceRoot), null, 2)}\n`; + const hooksText = `${JSON.stringify(expectedAntigravityHooks(), null, 2)}\n`; + const rulesText = expectedAntigravityRules(sourceRoot); + const skillsTarget = path.join(sourceRoot, "skills"); + const hooksTarget = path.join(sourceRoot, "hooks"); + + if (!state.exists) { + fs.mkdirSync(pluginDir, { recursive: true }); + } + fs.mkdirSync(path.join(pluginDir, "rules"), { recursive: true }); + + atomicWriteFile(path.join(pluginDir, "plugin.json"), manifestText); + atomicWriteFile(path.join(pluginDir, "hooks.json"), hooksText); + atomicWriteFile(path.join(pluginDir, "rules", "AGENTS.md"), rulesText); + + const skillsPath = path.join(pluginDir, "skills"); + if (state.legacySkillsDir) { + for (const entry of fs.readdirSync(skillsPath)) { + fs.unlinkSync(path.join(skillsPath, entry)); + } + fs.rmdirSync(skillsPath); + } + atomicSymlink(skillsTarget, skillsPath); + atomicSymlink(hooksTarget, path.join(pluginDir, "hooks")); +} + +export function installAntigravityPlugin({ + sourceRoot = root, + homeDir = os.homedir(), + environment = process.env, +} = {}) { + const resolvedSource = path.resolve(sourceRoot); + const registryPath = path.join(resolvedSource, "config/platform-capabilities.json"); + const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")); + const platform = registry.platforms.find((entry) => entry.id === "antigravity"); + if (!platform) { + throw new Error("Antigravity platform is missing from config/platform-capabilities.json"); + } + assembleAntigravityPlugin({ + sourceRoot: resolvedSource, + homeDir, + environment, + platform, + allowCreate: true, + }); + const report = inspectInstallations({ + sourceRoot: resolvedSource, + homeDir, + environment, + platformId: "antigravity", + registryPath, + }); + if (report.results[0].status !== "PASS") { + throw new Error("Install did not verify PASS; run verify-install.mjs --platform antigravity"); + } + return report; +} + function run(command, context) { const result = spawnSync(command[0], command.slice(1), { cwd: context.sourceRoot, env: context.environment, encoding: "utf8", @@ -66,13 +264,21 @@ export async function refreshInstallation({ platformId, sourceRoot = root, homeDir = os.homedir(), environment = process.env, runCommand = run, request = zcodeRequest, } = {}) { - if (!["codex", "claude-code", "zcode"].includes(platformId)) { - throw new Error("--platform must be codex, claude-code or zcode"); + if (!["codex", "claude-code", "zcode", "antigravity"].includes(platformId)) { + throw new Error("--platform must be codex, claude-code, zcode or antigravity"); } const context = { sourceRoot: path.resolve(sourceRoot), environment: { ...environment, HOME: homeDir } }; const registry = JSON.parse(fs.readFileSync(path.join(sourceRoot, "config/platform-capabilities.json"), "utf8")); const platform = registry.platforms.find(entry => entry.id === platformId); - if (platformId === "codex") { + if (platformId === "antigravity") { + assembleAntigravityPlugin({ + sourceRoot: context.sourceRoot, + homeDir, + environment, + platform, + allowCreate: false, + }); + } else if (platformId === "codex") { const skillsRoot = path.join(environment.CODEX_HOME || path.join(homeDir, ".codex"), "skills"); const names = fs.readdirSync(path.join(sourceRoot, "skills")) .filter(name => fs.existsSync(path.join(sourceRoot, "skills", name, "SKILL.md"))); @@ -159,8 +365,17 @@ export async function refreshInstallation({ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); try { - if (args.length !== 2 || args[0] !== "--platform") throw new Error("Usage: node scripts/refresh-install.mjs --platform codex|claude-code|zcode"); - const report = await refreshInstallation({ platformId: args[1] }); + const isAntigravityInstall = + args.length === 3 && + args[0] === "--platform" && + args[1] === "antigravity" && + args[2] === "--install"; + if (!isAntigravityInstall && (args.length !== 2 || args[0] !== "--platform")) { + throw new Error("Usage: node scripts/refresh-install.mjs --platform codex|claude-code|zcode|antigravity [--install]"); + } + const report = isAntigravityInstall + ? installAntigravityPlugin() + : await refreshInstallation({ platformId: args[1] }); process.stdout.write(`PASS ${args[1]} Thinloop ${report.expectedVersion}; new task/session required for loaded instructions\n`); } catch (error) { process.stderr.write(`${error.message}\n`); diff --git a/scripts/verify-install.mjs b/scripts/verify-install.mjs index a038df3..d5bfcb2 100644 --- a/scripts/verify-install.mjs +++ b/scripts/verify-install.mjs @@ -8,6 +8,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { isDeepStrictEqual } from "node:util"; import { pluginList } from "./plugin-list.mjs"; import { readDshPatch, hasDshInsertion } from "./dsh-patch.mjs"; +import { loadRoutingKernel, renderMarkdownKernel } from "./sync-routing-kernel.mjs"; const SCRIPT_ROOT = path.resolve( path.dirname(fileURLToPath(import.meta.url)), @@ -18,7 +19,26 @@ const DEFAULT_REGISTRY = path.join( "config", "platform-capabilities.json", ); -const RESULT_ORDER = ["PASS", "FAIL", "UNVERIFIED", "MANUAL", "SKIP"]; +const RESULT_ORDER = ["PASS", "FAIL", "NOT_INSTALLED", "UNVERIFIED", "MANUAL", "SKIP"]; +export const ANTIGRAVITY_MANIFEST_ALLOWED_KEYS = new Set([ + "name", + "displayName", + "version", + "description", + "author", + "homepage", + "repository", + "suggestedPrompts", + "logo", + "disabled", +]); +const ANTIGRAVITY_DEFAULT_REPO_URL = "https://github.com/mindcarver/thinloop"; +const ANTIGRAVITY_SUGGESTED_PROMPTS = [ + "检查当前项目的 Issue、PR 和推进状态,并给出唯一建议下一步", + "把一个明确的单交付改动按计划确认、测试设计与独立验收完整交付", + "把模糊的产品想法先做澄清并沉淀为可测试的产品契约与多 Issue 依赖图", +]; +const ANTIGRAVITY_HOOK_NAME = "thinloop-continuity"; const READ_ONLY_PROBES = new Map([ ["claude-code", ["claude", "plugin", "list", "--json"]], ["zcode", ["zcode", "plugins", "list", "--json"]], @@ -152,6 +172,11 @@ function validateRegistry(registry) { } else if (platform.verification.command !== undefined) { throw new Error(`Platform ${platform.id} must not declare a command`); } + if (platform.verification.mode === "plugin-dir") { + if (!platform.installation.configRoot || !platform.installation.pluginDir) { + throw new Error(`Platform ${platform.id} plugin-dir installation paths are required`); + } + } const manualRuntime = platform.verification.manualRuntime; if (manualRuntime) { const allowed = MANUAL_PROBES.get(platform.id); @@ -207,6 +232,9 @@ function resultStatus(checks) { if (checks.some((check) => check.status === "FAIL")) { return "FAIL"; } + if (checks.some((check) => check.status === "NOT_INSTALLED")) { + return "NOT_INSTALLED"; + } if (checks.some((check) => check.status === "UNVERIFIED")) { return "UNVERIFIED"; } @@ -874,6 +902,616 @@ function inspectSkip(platform) { ]); } +export function resolveAntigravityPaths(platform, homeDir, environment = {}) { + const override = platform.installation.configRootOverride; + const overrideRoot = override && environment[override.environment]; + const configRoot = + typeof overrideRoot === "string" && overrideRoot.length > 0 + ? path.resolve(overrideRoot) + : resolveFrom(homeDir, platform.installation.configRoot); + const pluginDir = resolveFrom(configRoot, platform.installation.pluginDir); + return { configRoot, pluginDir }; +} + +export function expectedAntigravityManifest(sourceRoot) { + const codexManifest = readJson( + resolveFrom(sourceRoot, ".codex-plugin/plugin.json"), + ); + let repoUrls = {}; + const claudeManifestPath = resolveFrom(sourceRoot, ".claude-plugin/plugin.json"); + if (fs.existsSync(claudeManifestPath)) { + try { + repoUrls = readJson(claudeManifestPath); + } catch { + repoUrls = {}; + } + } + return { + name: codexManifest.name, + displayName: codexManifest.interface?.displayName || "Thinloop", + version: codexManifest.version, + description: codexManifest.description, + author: codexManifest.author || { name: "mindcarver" }, + homepage: repoUrls.homepage || ANTIGRAVITY_DEFAULT_REPO_URL, + repository: repoUrls.repository || ANTIGRAVITY_DEFAULT_REPO_URL, + suggestedPrompts: [...ANTIGRAVITY_SUGGESTED_PROMPTS], + }; +} + +export function expectedAntigravityHooks() { + return { + [ANTIGRAVITY_HOOK_NAME]: { + Stop: [ + { + type: "command", + command: 'node "./hooks/check-state.mjs" --platform antigravity', + timeout: 5, + }, + ], + }, + }; +} + +export function expectedAntigravityRules(sourceRoot) { + const kernel = loadRoutingKernel(sourceRoot); + return [ + "# Thinloop Routing Kernel", + "", + "Generated from `config/routing-kernel.json` for Antigravity global plugin installation.", + "", + renderMarkdownKernel(kernel), + "", + ].join("\n"); +} + +function extractAntigravityHookTarget(command, pluginDir) { + if (typeof command !== "string" || !command.trim()) { + return { error: "hook command is empty" }; + } + const hasPlatformFlag = /(?:^|\s)--platform(?:=|\s+)antigravity(?:\s|$)/.test( + command, + ); + if (!hasPlatformFlag) { + return { error: "hook command must pass --platform antigravity" }; + } + const match = + command.match(/"([^"]*check-state\.mjs)"/) || + command.match(/'([^']*check-state\.mjs)'/) || + command.match(/(?:^|\s)(\S*check-state\.mjs)(?:\s|$)/); + if (!match) { + return { error: "hook command does not target hooks/check-state.mjs" }; + } + const rawTarget = match[1]; + const resolved = path.isAbsolute(rawTarget) + ? rawTarget + : path.resolve(pluginDir, rawTarget); + return { rawTarget, resolved }; +} + +function inspectAntigravityManifest(pluginDir, expected) { + const manifestPath = path.join(pluginDir, "plugin.json"); + const expectedManifest = expectedAntigravityManifest(expected.sourceRoot); + try { + const manifest = readJson(manifestPath); + if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) { + return [ + makeCheck("manifest", "FAIL", "plugin.json must be a JSON object"), + makeCheck("version", "UNVERIFIED", "plugin.json is not a JSON object"), + ]; + } + const problems = []; + const unknownKeys = Object.keys(manifest).filter( + (key) => !ANTIGRAVITY_MANIFEST_ALLOWED_KEYS.has(key), + ); + if (unknownKeys.length > 0) { + problems.push(`unknown top-level fields: ${unknownKeys.join(", ")}`); + } + if (manifest.name !== expectedManifest.name) { + problems.push( + `name ${manifest.name ?? "missing"}; ${expectedManifest.name} expected`, + ); + } + if (manifest.displayName !== expectedManifest.displayName) { + problems.push( + `displayName ${manifest.displayName ?? "missing"}; ${expectedManifest.displayName} expected`, + ); + } + if (typeof manifest.description !== "string" || !manifest.description.trim()) { + problems.push("description must be a non-empty string"); + } + const validAuthor = + (typeof manifest.author === "string" && manifest.author.trim().length > 0) || + (manifest.author && + typeof manifest.author === "object" && + !Array.isArray(manifest.author) && + typeof manifest.author.name === "string" && + manifest.author.name.trim().length > 0); + if (!validAuthor) { + problems.push("author must be a non-empty string or object with name"); + } + if ( + typeof manifest.homepage !== "string" || + !manifest.homepage.startsWith("https://") + ) { + problems.push("homepage must be an https:// URL"); + } + const validRepository = + (typeof manifest.repository === "string" && + manifest.repository.startsWith("https://")) || + (manifest.repository && + typeof manifest.repository === "object" && + !Array.isArray(manifest.repository) && + typeof manifest.repository.url === "string" && + manifest.repository.url.startsWith("https://")); + if (!validRepository) { + problems.push("repository must be an https:// URL or { type, url } object"); + } + const validPrompts = + Array.isArray(manifest.suggestedPrompts) && + manifest.suggestedPrompts.length === 3 && + manifest.suggestedPrompts.every( + (item) => typeof item === "string" && item.trim().length > 0, + ); + if (!validPrompts) { + problems.push("suggestedPrompts must contain exactly 3 non-empty strings"); + } + if (manifest.disabled === true) { + problems.push("plugin.json must not declare disabled: true"); + } + + return [ + makeCheck( + "manifest", + problems.length > 0 ? "FAIL" : "PASS", + problems.length > 0 + ? problems.join("; ") + : `${manifest.name} plugin.json satisfies Antigravity whitelist`, + ), + makeCheck( + "version", + typeof manifest.version !== "string" || !manifest.version + ? "FAIL" + : manifest.version === expected.version + ? "PASS" + : "FAIL", + typeof manifest.version === "string" && manifest.version + ? `${manifest.version} installed; ${expected.version} expected` + : `version missing in plugin.json; ${expected.version} expected`, + ), + ]; + } catch (error) { + return [ + makeCheck("manifest", "FAIL", `plugin.json: ${error.message}`), + makeCheck( + "version", + "UNVERIFIED", + "version cannot be verified without a readable plugin.json", + ), + ]; + } +} + +function inspectAntigravityHooks(pluginDir, platform, expected) { + const hooksJsonPath = path.join(pluginDir, "hooks.json"); + const expectedHandlerPath = resolveFrom( + expected.sourceRoot, + platform.capabilities.hookHandler, + ); + const expectedHandlerReal = fs.realpathSync(expectedHandlerPath); + let hooksConfig; + try { + hooksConfig = readJson(hooksJsonPath); + } catch (error) { + return makeCheck("hooks", "FAIL", `hooks.json: ${error.message}`); + } + if (!hooksConfig || typeof hooksConfig !== "object" || Array.isArray(hooksConfig)) { + return makeCheck("hooks", "FAIL", "hooks.json must be a JSON object"); + } + const entry = hooksConfig[ANTIGRAVITY_HOOK_NAME]; + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { + return makeCheck( + "hooks", + "FAIL", + `hooks.json missing root flat hook "${ANTIGRAVITY_HOOK_NAME}"`, + ); + } + if (entry.enabled === false) { + return makeCheck( + "hooks", + "FAIL", + `hooks.json hook "${ANTIGRAVITY_HOOK_NAME}" is disabled`, + ); + } + if (!Array.isArray(entry.Stop) || entry.Stop.length === 0) { + return makeCheck( + "hooks", + "FAIL", + `hooks.json "${ANTIGRAVITY_HOOK_NAME}.Stop" must be a non-empty flat handler array`, + ); + } + + const problems = []; + let matchedValidHandler = false; + for (const [index, handler] of entry.Stop.entries()) { + if (!handler || typeof handler !== "object" || Array.isArray(handler)) { + problems.push(`Stop[${index}] must be a handler object`); + continue; + } + if ("hooks" in handler || "matcher" in handler) { + problems.push( + `Stop[${index}] must use Antigravity flat handler format (not grouped matcher/hooks)`, + ); + continue; + } + if (handler.type !== undefined && handler.type !== "command") { + problems.push(`Stop[${index}] unsupported type ${JSON.stringify(handler.type)}`); + continue; + } + const extracted = extractAntigravityHookTarget(handler.command, pluginDir); + if (extracted.error) { + problems.push(`Stop[${index}] ${extracted.error}`); + continue; + } + try { + fs.accessSync(extracted.resolved, fs.constants.R_OK); + const actualReal = fs.realpathSync(extracted.resolved); + if (actualReal !== expectedHandlerReal) { + problems.push( + `Stop[${index}] resolves to ${actualReal}; ${expectedHandlerReal} expected`, + ); + continue; + } + matchedValidHandler = true; + } catch (error) { + problems.push( + `Stop[${index}] unreadable handler ${extracted.resolved}: ${error.message}`, + ); + } + } + + if (problems.length > 0 || !matchedValidHandler) { + return makeCheck( + "hooks", + "FAIL", + problems.length > 0 + ? problems.join("; ") + : `hooks.json "${ANTIGRAVITY_HOOK_NAME}.Stop" has no valid check-state.mjs handler`, + ); + } + return makeCheck( + "hooks", + "PASS", + `1/1 flat Stop hook (${ANTIGRAVITY_HOOK_NAME}) in hooks.json resolves to ${expectedHandlerPath}`, + ); +} + +function inspectAntigravityRules(pluginDir, expected) { + const rulesPath = path.join(pluginDir, "rules", "AGENTS.md"); + let content; + try { + content = fs.readFileSync(rulesPath, "utf8"); + } catch (error) { + return makeCheck("rules", "FAIL", `rules/AGENTS.md: ${error.message}`); + } + const normalized = content.replace(/\r\n/g, "\n"); + const problems = []; + if (/^---\s*\n/.test(normalized)) { + problems.push("rules/AGENTS.md must not include YAML frontmatter"); + } + if (normalized.includes("Thinloop Delivery Default")) { + problems.push( + "rules/AGENTS.md must not include repository-only Thinloop Delivery Default", + ); + } + const expectedBlock = renderMarkdownKernel(loadRoutingKernel(expected.sourceRoot)); + const blockIndex = normalized.indexOf(expectedBlock); + if (blockIndex < 0) { + problems.push("rules/AGENTS.md has drifted from config/routing-kernel.json"); + } else { + const trailing = normalized.slice(blockIndex + expectedBlock.length).trim(); + if (trailing.length > 0) { + problems.push( + "rules/AGENTS.md contains unexpected content after routing kernel", + ); + } + } + return makeCheck( + "rules", + problems.length > 0 ? "FAIL" : "PASS", + problems.length > 0 + ? problems.join("; ") + : "rules/AGENTS.md matches config/routing-kernel.json without repository-only delivery rules", + ); +} + +function inspectAntigravitySkills(pluginDir, expected) { + const skillRoot = path.join(pluginDir, "skills"); + let rootLstat; + try { + rootLstat = fs.lstatSync(skillRoot); + } catch (error) { + return makeCheck("skills", "FAIL", `skills: ${error.message}`); + } + let rootStat; + try { + rootStat = fs.statSync(skillRoot); + } catch (error) { + return makeCheck("skills", "FAIL", `skills: ${error.message}`); + } + if (!rootStat.isDirectory()) { + return makeCheck( + "skills", + "FAIL", + "skills must be a directory or symbolic link to source skills", + ); + } + + const rootIsLink = rootLstat.isSymbolicLink(); + const missing = []; + const nonLinks = []; + const wrongTargets = []; + const inspectionErrors = []; + + for (const skillName of expected.skillNames) { + const installedDir = path.join(skillRoot, skillName); + const installedSkillMd = path.join(installedDir, "SKILL.md"); + let entryLstat; + try { + entryLstat = fs.lstatSync(installedDir); + } catch (error) { + if (error?.code === "ENOENT") { + missing.push(skillName); + continue; + } + inspectionErrors.push(`${skillName}: ${error.message}`); + continue; + } + if (!rootIsLink && !entryLstat.isSymbolicLink()) { + nonLinks.push(skillName); + continue; + } + if (!fs.existsSync(installedSkillMd)) { + missing.push(`${skillName}/SKILL.md`); + continue; + } + try { + const actualSkillMd = fs.realpathSync(installedSkillMd); + const expectedSkillMd = fs.realpathSync( + path.join(expected.skillsRoot, skillName, "SKILL.md"), + ); + if (actualSkillMd !== expectedSkillMd) { + wrongTargets.push(`${skillName} -> ${actualSkillMd}`); + } + } catch (error) { + wrongTargets.push(`${skillName} -> ${error.message}`); + } + } + + let unexpected = []; + try { + unexpected = unexpectedSkillNames(skillRoot, expected); + } catch (error) { + inspectionErrors.push(error.message); + } + + const problems = [ + ...(missing.length > 0 ? [`missing: ${missing.join(", ")}`] : []), + ...(nonLinks.length > 0 ? [`not source links: ${nonLinks.join(", ")}`] : []), + ...(wrongTargets.length > 0 ? [`wrong targets: ${wrongTargets.join(", ")}`] : []), + ...(unexpected.length > 0 + ? [`unexpected scd skills: ${unexpected.join(", ")}`] + : []), + ]; + return makeCheck( + "skills", + problems.length > 0 + ? "FAIL" + : inspectionErrors.length > 0 + ? "UNVERIFIED" + : "PASS", + problems.length > 0 + ? problems.join("; ") + : inspectionErrors.length > 0 + ? inspectionErrors.join("; ") + : `${expected.skillNames.length}/${expected.skillNames.length} plugin skills in ${skillRoot} resolve to ${expected.skillsRoot}`, + ); +} + +function matchesSkillPattern(name, pattern) { + if (typeof pattern !== "string" || !pattern) { + return false; + } + if (name === pattern) { + return true; + } + try { + return new RegExp(`^(?:${pattern})$`).test(name); + } catch { + return false; + } +} + +function resolveSkillsJsonEntryPath(rawPath, homeDir, configRoot) { + if (rawPath === "~") { + return path.resolve(homeDir); + } + if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) { + return path.resolve(homeDir, rawPath.slice(2)); + } + if (path.isAbsolute(rawPath)) { + return path.resolve(rawPath); + } + return path.resolve(configRoot, rawPath); +} + +function inspectAntigravityDuplication(configRoot, pluginDir, expected, homeDir) { + const conflicts = []; + const skillsJsonPath = path.join(configRoot, "skills.json"); + const globalSkillsDir = path.join(configRoot, "skills"); + const expectedSkillsReal = fs.realpathSync(expected.skillsRoot); + const expectedSet = new Set(expected.skillNames); + let pluginSkillsReal = null; + try { + pluginSkillsReal = fs.realpathSync(path.join(pluginDir, "skills")); + } catch { + pluginSkillsReal = null; + } + + if (fs.existsSync(skillsJsonPath)) { + let skillsConfig; + try { + skillsConfig = readJson(skillsJsonPath); + } catch (error) { + conflicts.push( + `skills.json could not be parsed (${error.message}); inspect ${skillsJsonPath}`, + ); + } + if (Array.isArray(skillsConfig?.entries)) { + for (const entry of skillsConfig.entries) { + if (typeof entry?.path !== "string" || !entry.path.trim()) { + continue; + } + const resolvedPath = resolveSkillsJsonEntryPath( + entry.path.trim(), + homeDir, + configRoot, + ); + let entryReal = null; + try { + entryReal = fs.realpathSync(resolvedPath); + } catch { + entryReal = null; + } + const pointsToThinloopRoot = + entryReal === expectedSkillsReal || + (pluginSkillsReal !== null && entryReal === pluginSkillsReal) || + resolvedPath === path.resolve(expected.skillsRoot) || + resolvedPath === path.resolve(pluginDir, "skills"); + + let exposedCandidates = []; + if (pointsToThinloopRoot) { + exposedCandidates = [...expected.skillNames]; + } else if (entryReal) { + try { + if (fs.statSync(entryReal).isDirectory()) { + exposedCandidates = fs + .readdirSync(entryReal, { withFileTypes: true }) + .map((item) => item.name) + .filter( + (name) => + (expectedSet.has(name) || name.startsWith("scd-")) && + fs.existsSync(path.join(entryReal, name, "SKILL.md")), + ); + } + } catch { + exposedCandidates = []; + } + } + + if (Array.isArray(entry.include_only) && entry.include_only.length > 0) { + exposedCandidates = exposedCandidates.filter((name) => + entry.include_only.some((pattern) => matchesSkillPattern(name, pattern)), + ); + } + if (Array.isArray(entry.exclude) && entry.exclude.length > 0) { + exposedCandidates = exposedCandidates.filter( + (name) => + !entry.exclude.some((pattern) => matchesSkillPattern(name, pattern)), + ); + } + + if (exposedCandidates.length > 0) { + conflicts.push( + `duplicate exposure: ${skillsJsonPath} entry "${entry.path}" also exposes ${exposedCandidates.length} Thinloop skill(s) alongside global plugin; remove this entry from ${skillsJsonPath}`, + ); + } + } + } + } + + try { + const globalEntries = fs + .readdirSync(globalSkillsDir, { withFileTypes: true }) + .map((entry) => entry.name) + .filter((name) => expectedSet.has(name) || name.startsWith("scd-")) + .sort(); + if (globalEntries.length > 0) { + conflicts.push( + `duplicate exposure: ${globalSkillsDir} contains ${globalEntries.join(", ")} alongside global plugin; remove these entries from ${globalSkillsDir}`, + ); + } + } catch (error) { + if (error?.code !== "ENOENT") { + conflicts.push(`could not inspect ${globalSkillsDir}: ${error.message}`); + } + } + + return makeCheck( + "duplication", + conflicts.length > 0 ? "FAIL" : "PASS", + conflicts.length > 0 + ? conflicts.join("; ") + : `no duplicate Thinloop skill exposure in ${skillsJsonPath} or ${globalSkillsDir}`, + ); +} + +function inspectAntigravityPlugin(platform, expected, homeDir, environment) { + const { configRoot, pluginDir } = resolveAntigravityPaths( + platform, + homeDir, + environment, + ); + let pluginDirStat; + try { + pluginDirStat = fs.statSync(pluginDir); + } catch (error) { + if (error?.code === "ENOENT") { + try { + fs.lstatSync(pluginDir); + return singleCheckResult( + platform, + "plugin", + "FAIL", + `${pluginDir} is a broken symbolic link`, + ); + } catch (lstatError) { + if (lstatError?.code === "ENOENT") { + return singleCheckResult( + platform, + "plugin", + "NOT_INSTALLED", + `${pluginDir} is not installed`, + ); + } + return singleCheckResult(platform, "plugin", "UNVERIFIED", lstatError.message); + } + } + return singleCheckResult(platform, "plugin", "UNVERIFIED", error.message); + } + if (!pluginDirStat.isDirectory()) { + return singleCheckResult( + platform, + "plugin", + "FAIL", + `${pluginDir} is not a directory`, + ); + } + + const [manifestCheck, versionCheck] = inspectAntigravityManifest( + pluginDir, + expected, + ); + const checks = [ + manifestCheck, + versionCheck, + inspectAntigravityHooks(pluginDir, platform, expected), + inspectAntigravityRules(pluginDir, expected), + inspectAntigravitySkills(pluginDir, expected), + inspectAntigravityDuplication(configRoot, pluginDir, expected, homeDir), + ]; + return platformResult(platform, checks); +} + export function inspectInstallations({ registryPath = DEFAULT_REGISTRY, sourceRoot = SCRIPT_ROOT, @@ -924,6 +1562,14 @@ export function inspectInstallations({ if (platform.verification.mode === "plugin-cli") { return inspectPlugin(platform, expected, runCommand, context); } + if (platform.verification.mode === "plugin-dir") { + return inspectAntigravityPlugin( + platform, + expected, + context.homeDir, + environment, + ); + } if (platform.verification.mode === "manual") { return inspectManual(platform); } diff --git a/tests/check-state.test.mjs b/tests/check-state.test.mjs index fc32de6..bb9679a 100644 --- a/tests/check-state.test.mjs +++ b/tests/check-state.test.mjs @@ -389,3 +389,183 @@ test("repeat guard does not change PreCompact or other platform protocols", () = assert.equal(generic.continue, false); } finally { fs.rmSync(cwd, { recursive: true, force: true }); } }); + +function runAntigravityHook( + cwd, + input = {}, + { args = [], env = {}, rawInput } = {}, +) { + return spawnSync(process.execPath, [hookPath, ...args], { + cwd, + input: + rawInput !== undefined + ? rawInput + : JSON.stringify({ + cwd, + hookEventName: "Stop", + ...input, + }), + encoding: "utf8", + env: { + ...process.env, + CLAUDE_PLUGIN_ROOT: "", + CODEBUDDY_PLUGIN_ROOT: "", + ZCODE_PLUGIN_ROOT: "", + ...env, + }, + }); +} + +test("Antigravity Stop continues with reason when state is invalid under NO_TOOL_CALL or omitted terminationReason", () => { + const cwd = makeWorkspace(); + try { + writeState(cwd, validState({ evidence: "" })); + for (const payload of [ + { terminationReason: "NO_TOOL_CALL", continuationActive: false }, + {}, + ]) { + const output = parseOutput(runAntigravityHook(cwd, payload)); + assert.equal(output.decision, "continue"); + assert.match(output.reason, /^scd-quickdev paused Stop/); + assert.match(output.reason, /empty section: Evidence/); + assert.equal("continue" in output, false); + assert.equal("systemMessage" in output, false); + } + } finally { + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); + +test("Antigravity Stop allows USER_CANCELED, ERROR, and MAX_INVOCATIONS without forcing continuation", () => { + const cwd = makeWorkspace(); + try { + writeState(cwd, validState({ evidence: "" })); + for (const terminationReason of [ + "USER_CANCELED", + "ERROR", + "MAX_INVOCATIONS", + ]) { + const output = parseOutput( + runAntigravityHook(cwd, { terminationReason, continuationActive: false }), + ); + assert.deepEqual(output, {}); + } + } finally { + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); + +test("Antigravity Stop allows when continuationActive is true to prevent infinite loops", () => { + const cwd = makeWorkspace(); + try { + writeState(cwd, validState({ evidence: "" })); + const output = parseOutput( + runAntigravityHook(cwd, { + terminationReason: "NO_TOOL_CALL", + continuationActive: true, + }), + ); + assert.deepEqual(output, {}); + } finally { + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); + +test("Antigravity Stop returns empty JSON object when state is absent, unmanaged, or valid", () => { + const cwd = makeWorkspace(); + try { + assert.deepEqual( + parseOutput( + runAntigravityHook(cwd, { terminationReason: "NO_TOOL_CALL" }), + ), + {}, + ); + writeState(cwd, validState({ managedBy: "another-tool" })); + assert.deepEqual( + parseOutput( + runAntigravityHook(cwd, { terminationReason: "NO_TOOL_CALL" }), + ), + {}, + ); + writeState(cwd, validState()); + assert.deepEqual( + parseOutput( + runAntigravityHook(cwd, { terminationReason: "NO_TOOL_CALL" }), + ), + {}, + ); + } finally { + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); + +test("Antigravity CLI --platform flag forces Antigravity protocol and fail-open JSON output", () => { + const cwd = makeWorkspace(); + try { + writeState(cwd, validState({ status: "complete" })); + for (const args of [ + ["--platform", "antigravity"], + ["--platform=antigravity"], + ]) { + const blocked = parseOutput( + runAntigravityHook( + cwd, + { hookEventName: undefined, hook_event_name: "Stop" }, + { args, env: { CLAUDE_PLUGIN_ROOT: "/unrelated/claude" } }, + ), + ); + assert.equal(blocked.decision, "continue"); + assert.match(blocked.reason, /status must be active or blocked/); + + const workspaceFallback = parseOutput( + runAntigravityHook( + os.tmpdir(), + {}, + { + args, + rawInput: JSON.stringify({ + workspacePaths: [cwd], + hookEventName: "Stop", + terminationReason: "NO_TOOL_CALL", + }), + }, + ), + ); + assert.equal(workspaceFallback.decision, "continue"); + assert.match(workspaceFallback.reason, /status must be active or blocked/); + + const invalidJson = parseOutput( + runAntigravityHook(cwd, {}, { args, rawInput: "{not-json" }), + ); + assert.deepEqual(invalidJson, {}); + } + } finally { + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); + +test("camelCase hookEventName does not hijack Claude, ZCode, or WorkBuddy plugin roots", () => { + const cwd = makeWorkspace(); + try { + writeState(cwd, validState({ status: "complete" })); + const claude = parseOutput( + runAntigravityHook( + cwd, + { hookEventName: "Stop" }, + { env: { CLAUDE_PLUGIN_ROOT: "root" } }, + ), + ); + assert.equal(claude.decision, "block"); + + const workbuddy = parseOutput( + runAntigravityHook( + cwd, + { hookEventName: "Stop" }, + { env: { CODEBUDDY_PLUGIN_ROOT: "root" } }, + ), + ); + assert.equal(workbuddy.continue, false); + } finally { + fs.rmSync(cwd, { recursive: true, force: true }); + } +}); diff --git a/tests/platform-capabilities.test.mjs b/tests/platform-capabilities.test.mjs index 992125c..398b9c3 100644 --- a/tests/platform-capabilities.test.mjs +++ b/tests/platform-capabilities.test.mjs @@ -8,6 +8,9 @@ import { zcodeFixture } from "./helpers/zcode-fixture.mjs"; import { fileURLToPath, pathToFileURL } from "node:url"; import { + expectedAntigravityHooks, + expectedAntigravityManifest, + expectedAntigravityRules, formatText, inspectInstallations, } from "../scripts/verify-install.mjs"; @@ -185,7 +188,77 @@ function resultMap(report) { ); } -test("platform registry is the nine-platform capability contract", () => { +function installAntigravityFixture( + homeDir, + { + environment = {}, + manifestOverrides = {}, + hooksConfig, + rulesContent, + perSkillLinks = false, + copySkills = false, + extraSkills = [], + skipHooksLink = false, + } = {}, +) { + const configRoot = environment.ANTIGRAVITY_CONFIG_DIR + ? path.resolve(environment.ANTIGRAVITY_CONFIG_DIR) + : path.join(homeDir, ".gemini", "config"); + const pluginDir = path.join(configRoot, "plugins", "thinloop"); + fs.mkdirSync(path.join(pluginDir, "rules"), { recursive: true }); + + const manifest = { + ...expectedAntigravityManifest(root), + ...manifestOverrides, + }; + for (const [key, value] of Object.entries(manifest)) { + if (value === undefined) delete manifest[key]; + } + fs.writeFileSync( + path.join(pluginDir, "plugin.json"), + `${JSON.stringify(manifest, null, 2)}\n`, + ); + fs.writeFileSync( + path.join(pluginDir, "hooks.json"), + `${JSON.stringify(hooksConfig ?? expectedAntigravityHooks(), null, 2)}\n`, + ); + fs.writeFileSync( + path.join(pluginDir, "rules", "AGENTS.md"), + rulesContent ?? expectedAntigravityRules(root), + ); + + const linkType = process.platform === "win32" ? "junction" : "dir"; + if (!skipHooksLink) { + fs.symlinkSync( + path.join(root, "hooks"), + path.join(pluginDir, "hooks"), + linkType, + ); + } + const skillsDest = path.join(pluginDir, "skills"); + if (copySkills) { + fs.cpSync(path.join(root, "skills"), skillsDest, { recursive: true }); + } else if (perSkillLinks || extraSkills.length > 0) { + fs.mkdirSync(skillsDest, { recursive: true }); + for (const skillName of expectedSkills) { + fs.symlinkSync( + path.join(root, "skills", skillName), + path.join(skillsDest, skillName), + linkType, + ); + } + for (const extra of extraSkills) { + const extraPath = path.join(skillsDest, extra); + fs.mkdirSync(extraPath, { recursive: true }); + fs.writeFileSync(path.join(extraPath, "SKILL.md"), `# ${extra}\n`); + } + } else { + fs.symlinkSync(path.join(root, "skills"), skillsDest, linkType); + } + return { configRoot, pluginDir }; +} + +test("platform registry is the ten-platform capability contract", () => { assert.equal(registry.schemaVersion, 1); assert.deepEqual( registry.platforms.map((entry) => entry.id), @@ -199,6 +272,7 @@ test("platform registry is the nine-platform capability contract", () => { "claude-code", "workbuddy", "zcode", + "antigravity", ], ); assert.equal(expectedSkills.length, 15); @@ -221,10 +295,17 @@ test("platform registry is the nine-platform capability contract", () => { installation, new RegExp(escapeRegex(definition.installation.takesEffect)), ); - assert.match( - verification, - new RegExp(escapeRegex(definition.verification.summary)), - ); + if (definition.id === "antigravity") { + assert.match( + installation, + new RegExp(escapeRegex(definition.verification.summary)), + ); + } else { + assert.match( + verification, + new RegExp(escapeRegex(definition.verification.summary)), + ); + } if (definition.installation.manifest) { const manifest = readJson(definition.installation.manifest); @@ -239,6 +320,12 @@ test("platform registry is the nine-platform capability contract", () => { ); continue; } + if (hook.kind === "antigravity-plugin-hook") { + assert.equal(hook.event, "Stop"); + assert.equal(hook.source, "hooks.json"); + assert.equal(hook.name, "thinloop-continuity"); + continue; + } const hooks = readJson(hook.source).hooks?.[hook.event]; assert.ok(Array.isArray(hooks), `${definition.id} ${hook.event}`); if (hook.matcher) { @@ -267,6 +354,7 @@ test("read-only checker verifies complete automatic installs", () => { linkSkills(homeDir, "codewhale"); linkSkills(homeDir, "reasonix"); linkSkills(homeDir, "dsh"); + installAntigravityFixture(homeDir); const report = inspectInstallations({ registryPath, sourceRoot: root, @@ -296,6 +384,7 @@ test("read-only checker verifies complete automatic installs", () => { assert.equal(results["claude-code"].status, "PASS"); assert.equal(results.workbuddy.status, "SKIP"); assert.equal(results.zcode.status, "UNVERIFIED"); + assert.equal(results.antigravity.status, "PASS"); assert.match(formatText(report), /Mode: read-only/); } finally { fs.rmSync(homeDir, { recursive: true, force: true }); @@ -476,6 +565,7 @@ test("unavailable automatic plugin CLI stays unverified instead of failing", () linkSkills(homeDir, "codewhale"); linkSkills(homeDir, "reasonix"); linkSkills(homeDir, "dsh"); + installAntigravityFixture(homeDir); const report = inspectInstallations({ registryPath, sourceRoot: root, @@ -515,6 +605,7 @@ test("missing plugin evidence stays unverified instead of being guessed", () => linkSkills(homeDir, "codewhale"); linkSkills(homeDir, "reasonix"); linkSkills(homeDir, "dsh"); + installAntigravityFixture(homeDir); const report = inspectInstallations({ registryPath, sourceRoot: root, @@ -561,6 +652,7 @@ test("checker has a dedicated not-installed fixture", () => { assert.equal(report.exitCode, 1); assert.equal(results["claude-code"].status, "FAIL"); assert.equal(results.workbuddy.status, "SKIP"); + assert.equal(results.antigravity.status, "NOT_INSTALLED"); assert.match( results["claude-code"].checks.find((check) => check.name === "plugin") .detail, @@ -822,6 +914,15 @@ test("checker source and registered probes are read-only", () => { assert.match(platform("workbuddy").verification.summary, /不验证/); assert.equal(platform("zcode").verification.mode, "plugin-cli"); assert.deepEqual(platform("zcode").verification.command, ["zcode", "plugins", "list", "--json"]); + assert.equal(platform("antigravity").verification.mode, "plugin-dir"); + assert.equal(platform("antigravity").verification.command, undefined); + assert.equal(platform("antigravity").installation.configRoot, ".gemini/config"); + assert.equal(platform("antigravity").installation.pluginDir, "plugins/thinloop"); + assert.equal( + platform("antigravity").installation.configRootOverride.environment, + "ANTIGRAVITY_CONFIG_DIR", + ); + assert.equal(platform("antigravity").capabilities.hookHandler, "hooks/check-state.mjs"); }); test("checker can target Pi without probing unrelated platforms", () => { @@ -1311,3 +1412,325 @@ test("ZCode invalid JSON remains UNVERIFIED", () => { assert.equal(report.results[0].status, "UNVERIFIED"); assert.match(report.results[0].checks[0].detail, /invalid JSON/); }); + +test("Antigravity reports NOT_INSTALLED without running any CLI when plugin directory is absent", () => { + const homeDir = makeFixture(); + try { + const report = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + runCommand() { + throw new Error("Antigravity check must remain read-only without CLI execution"); + }, + }); + assert.equal(report.exitCode, 0); + assert.equal(report.counts.NOT_INSTALLED, 1); + assert.equal(report.results[0].status, "NOT_INSTALLED"); + assert.equal(report.results[0].checks[0].status, "NOT_INSTALLED"); + assert.match(report.results[0].checks[0].detail, /is not installed/); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } +}); + +test("Antigravity verifies default install, per-skill symlinks, and ANTIGRAVITY_CONFIG_DIR override", () => { + const homeDir = makeFixture(); + const customConfig = path.join(homeDir, "custom-antigravity-config"); + try { + installAntigravityFixture(homeDir); + const defaultReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + runCommand() { + throw new Error("Antigravity check must not run a CLI probe"); + }, + }); + assert.equal(defaultReport.exitCode, 0); + assert.equal(defaultReport.results[0].status, "PASS"); + assert.deepEqual( + defaultReport.results[0].checks.map((check) => check.name), + ["manifest", "version", "hooks", "rules", "skills", "duplication"], + ); + assert.ok(defaultReport.results[0].checks.every((check) => check.status === "PASS")); + + installAntigravityFixture(homeDir, { + environment: { ANTIGRAVITY_CONFIG_DIR: customConfig }, + perSkillLinks: true, + }); + const overrideReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: { ANTIGRAVITY_CONFIG_DIR: customConfig }, + platformId: "antigravity", + }); + assert.equal(overrideReport.exitCode, 0); + assert.equal(overrideReport.results[0].status, "PASS"); + assert.match( + overrideReport.results[0].checks.find((check) => check.name === "skills").detail, + /custom-antigravity-config/, + ); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } +}); + +test("Antigravity rejects unknown plugin.json fields, stale version, invalid prompts, and disabled flag", () => { + for (const [label, manifestOverrides, expectedCheck, pattern] of [ + ["unknown top-level fields", { skills: "./skills/", keywords: ["bad"] }, "manifest", /unknown top-level fields: skills, keywords/], + ["stale version", { version: "0.0.0" }, "version", /0\.0\.0 installed/], + ["missing displayName", { displayName: undefined }, "manifest", /displayName missing/], + ["non-https homepage", { homepage: "http://example.com" }, "manifest", /homepage must be an https/], + ["wrong suggestedPrompts count", { suggestedPrompts: ["只有一条"] }, "manifest", /exactly 3/], + ["disabled true", { disabled: true }, "manifest", /disabled: true/], + ]) { + const homeDir = makeFixture(); + try { + installAntigravityFixture(homeDir, { manifestOverrides }); + const report = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + }); + assert.equal(report.exitCode, 1, label); + assert.equal(report.results[0].status, "FAIL", label); + const check = report.results[0].checks.find((entry) => entry.name === expectedCheck); + assert.equal(check.status, "FAIL", label); + assert.match(check.detail, pattern, label); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + } +}); + +test("Antigravity rejects nested, disabled, flagless, or stale hooks.json and executes valid hook command", () => { + for (const [label, hooksConfig, pattern] of [ + ["nested Claude hooks wrapper", { hooks: { Stop: [] } }, /missing root flat hook/], + ["grouped matcher/hooks Stop entry", { "thinloop-continuity": { Stop: [{ matcher: "*", hooks: [] }] } }, /flat handler format/], + ["disabled hook", { "thinloop-continuity": { enabled: false, Stop: [{ type: "command", command: 'node "./hooks/check-state.mjs" --platform antigravity' }] } }, /is disabled/], + ["missing --platform antigravity", { "thinloop-continuity": { Stop: [{ type: "command", command: 'node "./hooks/check-state.mjs"' }] } }, /--platform antigravity/], + ["unreadable handler path", { "thinloop-continuity": { Stop: [{ type: "command", command: 'node "./hooks/missing-check-state.mjs" --platform antigravity' }] } }, /check-state\.mjs/], + ]) { + const homeDir = makeFixture(); + try { + installAntigravityFixture(homeDir, { hooksConfig }); + const report = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + }); + assert.equal(report.exitCode, 1, label); + const hooksCheck = report.results[0].checks.find((entry) => entry.name === "hooks"); + assert.equal(hooksCheck.status, "FAIL", label); + assert.match(hooksCheck.detail, pattern, label); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + } + + // Verify the generated hooks.json command actually executes from pluginDir. + const homeDir = makeFixture(); + const workspace = makeFixture(); + try { + const { pluginDir } = installAntigravityFixture(homeDir); + const stopCommand = JSON.parse( + fs.readFileSync(path.join(pluginDir, "hooks.json"), "utf8"), + )["thinloop-continuity"].Stop[0].command; + + const cleanRun = spawnSync(stopCommand, { + cwd: pluginDir, + encoding: "utf8", + input: JSON.stringify({ + cwd: workspace, + hookEventName: "Stop", + terminationReason: "NO_TOOL_CALL", + }), + shell: true, + }); + assert.equal(cleanRun.status, 0, cleanRun.stderr); + assert.deepEqual(JSON.parse(cleanRun.stdout), {}); + + fs.mkdirSync(path.join(workspace, ".scd", "tasks"), { recursive: true }); + fs.writeFileSync( + path.join(workspace, ".scd", "tasks", "current.md"), + "---\nmanaged_by: scd-quickdev\nstatus: complete\nupdated_at: 2026-11-23T12:00:00+08:00\n---\n", + ); + const blockedRun = spawnSync(stopCommand, { + cwd: pluginDir, + encoding: "utf8", + input: JSON.stringify({ + cwd: workspace, + hookEventName: "Stop", + terminationReason: "NO_TOOL_CALL", + continuationActive: false, + }), + shell: true, + }); + assert.equal(blockedRun.status, 0, blockedRun.stderr); + const parsed = JSON.parse(blockedRun.stdout); + assert.equal(parsed.decision, "continue"); + assert.match(parsed.reason, /status must be active or blocked/); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + fs.rmSync(workspace, { recursive: true, force: true }); + } +}); + +test("Antigravity rejects rules/AGENTS.md with Delivery Default, frontmatter, or kernel drift", () => { + const validRules = expectedAntigravityRules(root); + for (const [label, rulesContent, pattern] of [ + ["Thinloop Delivery Default leak", `${validRules}\n# Thinloop Delivery Default\nDo internal delivery\n`, /Thinloop Delivery Default/], + ["YAML frontmatter", `---\ntrigger: always_on\n---\n\n${validRules}`, /YAML frontmatter/], + ["drifted routing kernel", "# Thinloop Routing Kernel\n\nOutdated rules\n", /drifted from config\/routing-kernel\.json/], + ["unexpected trailing content", `${validRules}\nExtra repo rule\n`, /unexpected content/], + ]) { + const homeDir = makeFixture(); + try { + installAntigravityFixture(homeDir, { rulesContent }); + const report = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + }); + assert.equal(report.exitCode, 1, label); + const rulesCheck = report.results[0].checks.find((entry) => entry.name === "rules"); + assert.equal(rulesCheck.status, "FAIL", label); + assert.match(rulesCheck.detail, pattern, label); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + } +}); + +test("Antigravity rejects copied skills or unexpected legacy skills", () => { + const copiedHome = makeFixture(); + const legacyHome = makeFixture(); + try { + installAntigravityFixture(copiedHome, { copySkills: true }); + const copiedReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir: copiedHome, + environment: {}, + platformId: "antigravity", + }); + assert.equal(copiedReport.exitCode, 1); + assert.equal( + copiedReport.results[0].checks.find((check) => check.name === "skills").status, + "FAIL", + ); + assert.match( + copiedReport.results[0].checks.find((check) => check.name === "skills").detail, + /not source links/, + ); + + installAntigravityFixture(legacyHome, { extraSkills: ["scd-dev-loop"] }); + const legacyReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir: legacyHome, + environment: {}, + platformId: "antigravity", + }); + assert.equal(legacyReport.exitCode, 1); + assert.match( + legacyReport.results[0].checks.find((check) => check.name === "skills").detail, + /unexpected scd skills: scd-dev-loop/, + ); + } finally { + fs.rmSync(copiedHome, { recursive: true, force: true }); + fs.rmSync(legacyHome, { recursive: true, force: true }); + } +}); + +test("Antigravity detects duplicate exposure via skills.json entries and global skills/scd-*", () => { + const homeDir = makeFixture(); + try { + const { configRoot } = installAntigravityFixture(homeDir); + const skillsJsonPath = path.join(configRoot, "skills.json"); + + // 1. skills.json pointing to Thinloop skills/ fails duplication check. + fs.writeFileSync( + skillsJsonPath, + JSON.stringify({ entries: [{ path: path.join(root, "skills") }] }), + ); + const dupJsonReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + }); + assert.equal(dupJsonReport.exitCode, 1); + assert.equal(dupJsonReport.results[0].status, "FAIL"); + const dupCheck = dupJsonReport.results[0].checks.find( + (check) => check.name === "duplication", + ); + assert.equal(dupCheck.status, "FAIL"); + assert.match(dupCheck.detail, /duplicate exposure/); + assert.match(dupCheck.detail, /skills\.json/); + assert.match(dupCheck.detail, /remove this entry/); + + // 2. skills.json pointing to an unrelated skill directory passes. + const unrelatedDir = path.join(homeDir, "other-skills"); + fs.mkdirSync(path.join(unrelatedDir, "my-helper"), { recursive: true }); + fs.writeFileSync(path.join(unrelatedDir, "my-helper", "SKILL.md"), "# helper\n"); + fs.writeFileSync( + skillsJsonPath, + JSON.stringify({ + entries: [ + { path: unrelatedDir }, + { path: path.join(root, "skills"), exclude: ["scd-.*"] }, + ], + }), + ); + const cleanJsonReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + }); + assert.equal(cleanJsonReport.exitCode, 0); + assert.equal(cleanJsonReport.results[0].status, "PASS"); + + // 3. Global ~/.gemini/config/skills/scd-* fails duplication check. + const globalSkill = path.join(configRoot, "skills", "scd-quickdev"); + fs.mkdirSync(path.dirname(globalSkill), { recursive: true }); + fs.symlinkSync( + path.join(root, "skills", "scd-quickdev"), + globalSkill, + process.platform === "win32" ? "junction" : "dir", + ); + const dupDirReport = inspectInstallations({ + registryPath, + sourceRoot: root, + homeDir, + environment: {}, + platformId: "antigravity", + }); + assert.equal(dupDirReport.exitCode, 1); + assert.equal(dupDirReport.results[0].status, "FAIL"); + const dupDirCheck = dupDirReport.results[0].checks.find( + (check) => check.name === "duplication", + ); + assert.equal(dupDirCheck.status, "FAIL"); + assert.match(dupDirCheck.detail, /duplicate exposure/); + assert.match(dupDirCheck.detail, /scd-quickdev/); + assert.match(dupDirCheck.detail, /remove these entries/); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } +}); diff --git a/tests/refresh-install.test.mjs b/tests/refresh-install.test.mjs index 2cd9883..cb8299a 100644 --- a/tests/refresh-install.test.mjs +++ b/tests/refresh-install.test.mjs @@ -5,7 +5,11 @@ import path from "node:path"; import test from "node:test"; import { zcodeFixture } from "./helpers/zcode-fixture.mjs"; import { fileURLToPath } from "node:url"; -import { refreshInstallation } from "../scripts/refresh-install.mjs"; +import { + installAntigravityPlugin, + refreshInstallation, +} from "../scripts/refresh-install.mjs"; +import { ANTIGRAVITY_MANIFEST_ALLOWED_KEYS } from "../scripts/verify-install.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const version = JSON.parse(fs.readFileSync(path.join(root, ".codex-plugin/plugin.json"))).version; @@ -220,3 +224,190 @@ for (const response of [null, {}, { plugins: null }, { plugins: {} }, [null], assert.equal(requests, 0); }); } + +test("Antigravity refresh refuses a missing installation without creating directories or config.json", async () => { + const home = fixture(); + const configRoot = path.join(home, ".gemini", "config"); + try { + await assert.rejects( + refreshInstallation({ + platformId: "antigravity", + sourceRoot: root, + homeDir: home, + environment: {}, + runCommand() { + throw new Error("Antigravity refresh must not call a plugin CLI"); + }, + }), + /No installed Antigravity Thinloop plugin/, + ); + assert.equal(fs.existsSync(configRoot), false); + assert.equal(fs.existsSync(path.join(configRoot, "config.json")), false); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("Antigravity install assembles whitelisted plugin payload without touching config.json", () => { + const home = fixture(); + const configDir = path.join(home, "custom-agy"); + const configJsonPath = path.join(configDir, "config.json"); + const originalConfig = `${JSON.stringify({ userSettings: { theme: "dark" }, plugins: { other: { enabled: true } } }, null, 2)}\n`; + try { + fs.mkdirSync(configDir, { recursive: true }); + fs.writeFileSync(configJsonPath, originalConfig); + + const report = installAntigravityPlugin({ + sourceRoot: root, + homeDir: home, + environment: { ANTIGRAVITY_CONFIG_DIR: configDir }, + }); + assert.equal(report.results[0].status, "PASS"); + assert.equal(fs.readFileSync(configJsonPath, "utf8"), originalConfig); + + const pluginDir = path.join(configDir, "plugins", "thinloop"); + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, "plugin.json"), "utf8")); + assert.equal(manifest.name, "thinloop"); + assert.equal(manifest.displayName, "Thinloop"); + assert.equal(manifest.version, version); + assert.equal(manifest.suggestedPrompts.length, 3); + for (const key of Object.keys(manifest)) { + assert.ok(ANTIGRAVITY_MANIFEST_ALLOWED_KEYS.has(key), `unexpected top-level key: ${key}`); + } + + const hooksJson = JSON.parse(fs.readFileSync(path.join(pluginDir, "hooks.json"), "utf8")); + assert.equal(hooksJson["thinloop-continuity"].Stop.length, 1); + assert.match(hooksJson["thinloop-continuity"].Stop[0].command, /--platform antigravity/); + + const rules = fs.readFileSync(path.join(pluginDir, "rules", "AGENTS.md"), "utf8"); + assert.doesNotMatch(rules, /^---\s*\n/); + assert.doesNotMatch(rules, /Thinloop Delivery Default/); + assert.match(rules, /thinloop-routing-kernel:start/); + + assert.equal( + fs.realpathSync(path.join(pluginDir, "skills")), + fs.realpathSync(path.join(root, "skills")), + ); + assert.equal( + fs.realpathSync(path.join(pluginDir, "hooks")), + fs.realpathSync(path.join(root, "hooks")), + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("Antigravity refresh is repeatable, repairs drifted payload and preserves config.json", async () => { + const home = fixture(); + const configDir = path.join(home, "agy-config"); + const configJsonPath = path.join(configDir, "config.json"); + const originalConfig = '{"plugins":{"thinloop":{"enabled":true}}}\n'; + const pluginDir = path.join(configDir, "plugins", "thinloop"); + const oldCheckout = path.join(home, "old-checkout"); + try { + fs.mkdirSync(path.join(oldCheckout, "skills"), { recursive: true }); + fs.mkdirSync(path.join(oldCheckout, "hooks"), { recursive: true }); + fs.mkdirSync(path.join(pluginDir, "rules"), { recursive: true }); + fs.writeFileSync(configJsonPath, originalConfig); + + // Seed drifted installation: stale version, unknown field, bad hooks, polluted rules, old symlinks. + fs.writeFileSync( + path.join(pluginDir, "plugin.json"), + JSON.stringify({ name: "thinloop", version: "0.0.0", unknownField: true }), + ); + fs.writeFileSync(path.join(pluginDir, "hooks.json"), JSON.stringify({ hooks: {} })); + fs.writeFileSync( + path.join(pluginDir, "rules", "AGENTS.md"), + "# Thinloop Delivery Default\nstale\n", + ); + fs.symlinkSync( + path.join(oldCheckout, "skills"), + path.join(pluginDir, "skills"), + process.platform === "win32" ? "junction" : "dir", + ); + fs.symlinkSync( + path.join(oldCheckout, "hooks"), + path.join(pluginDir, "hooks"), + process.platform === "win32" ? "junction" : "dir", + ); + + for (let attempt = 0; attempt < 2; attempt += 1) { + const report = await refreshInstallation({ + platformId: "antigravity", + sourceRoot: root, + homeDir: home, + environment: { ANTIGRAVITY_CONFIG_DIR: configDir }, + runCommand() { + throw new Error("Antigravity refresh must not invoke a plugin CLI"); + }, + }); + assert.equal(report.results[0].status, "PASS"); + assert.equal(fs.readFileSync(configJsonPath, "utf8"), originalConfig); + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, "plugin.json"), "utf8")); + assert.equal(manifest.version, version); + assert.equal("unknownField" in manifest, false); + assert.doesNotMatch( + fs.readFileSync(path.join(pluginDir, "rules", "AGENTS.md"), "utf8"), + /Thinloop Delivery Default/, + ); + assert.equal( + fs.realpathSync(path.join(pluginDir, "skills")), + fs.realpathSync(path.join(root, "skills")), + ); + assert.equal( + fs.realpathSync(path.join(pluginDir, "hooks")), + fs.realpathSync(path.join(root, "hooks")), + ); + } + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("Antigravity refresh refuses non-Thinloop plugin directory or colliding non-link before mutation", async () => { + const home = fixture(); + const pluginDir = path.join(home, ".gemini", "config", "plugins", "thinloop"); + try { + fs.mkdirSync(pluginDir, { recursive: true }); + fs.writeFileSync(path.join(pluginDir, "plugin.json"), JSON.stringify({ name: "other-plugin" })); + await assert.rejects( + refreshInstallation({ platformId: "antigravity", sourceRoot: root, homeDir: home, environment: {} }), + /Not an owned Antigravity Thinloop plugin/, + ); + assert.equal(JSON.parse(fs.readFileSync(path.join(pluginDir, "plugin.json"), "utf8")).name, "other-plugin"); + + fs.writeFileSync(path.join(pluginDir, "plugin.json"), JSON.stringify({ name: "thinloop", version: "0.0.0" })); + fs.mkdirSync(path.join(pluginDir, "skills"), { recursive: true }); + fs.writeFileSync(path.join(pluginDir, "skills", "custom-user-file.txt"), "keep me"); + await assert.rejects( + refreshInstallation({ platformId: "antigravity", sourceRoot: root, homeDir: home, environment: {} }), + /Refusing to replace non-link/, + ); + assert.equal(JSON.parse(fs.readFileSync(path.join(pluginDir, "plugin.json"), "utf8")).version, "0.0.0"); + assert.equal( + fs.readFileSync(path.join(pluginDir, "skills", "custom-user-file.txt"), "utf8"), + "keep me", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); + +test("Antigravity refresh fails verification without editing skills.json when duplicate exposure exists", async () => { + const home = fixture(); + const configDir = path.join(home, ".gemini", "config"); + const skillsJsonPath = path.join(configDir, "skills.json"); + const originalSkillsJson = `${JSON.stringify({ entries: [{ path: path.join(root, "skills") }] })}\n`; + try { + installAntigravityPlugin({ sourceRoot: root, homeDir: home, environment: {} }); + fs.writeFileSync(skillsJsonPath, originalSkillsJson); + + await assert.rejects( + refreshInstallation({ platformId: "antigravity", sourceRoot: root, homeDir: home, environment: {} }), + /did not verify PASS/, + ); + assert.equal(fs.readFileSync(skillsJsonPath, "utf8"), originalSkillsJson); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +});