feat(antigravity): retain experimental CLI bridge without changing project authority

This commit is contained in:
haelyra committed 2026-11-19 15:56:10 -05:00
commit 0d8bb780a9
15 files changed
+1075 -18

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
{
"ecc-guardrails": {
"PreToolUse": [
{
"matcher": "run_command|write_file|edit_file|write_to_file|replace_file_content|multi_replace_file_content",
"hooks": [
{
"type": "command",
"command": "node -e \"const p=require('path'),f=require('fs');function V(d){try{if(!d||typeof d!=='string')return null;var b=p.join(p.resolve(d),'scripts','antigravity','hook-bridge.js');if(!f.existsSync(b))return null;var rb=f.realpathSync(b);var rc=f.realpathSync(process.cwd());if(rb===rc||rb.startsWith(rc+p.sep))return null;return rb;}catch(_){return null;}}function G(){var e=process.env.ANTIGRAVITY_PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT||process.env.ECC_PLUGIN_ROOT;var b=V(e);if(b)return b;var h=require('os').homedir();var c=[p.join(h,'.gemini','config','plugins','ecc'),p.join(h,'.gemini','config','plugins','antigravity-suite'),p.join(h,'.claude','plugins','marketplaces','ecc'),p.join(h,'.claude','plugins','cache','ecc'),p.join(h,'.claude'),p.join(h,'.agents','plugins','ecc'),p.join(h,'.agents','plugins','marketplaces','ecc')];for(var i=0;i<c.length;i++){b=V(c[i]);if(b)return b;}return null;}var b=G();if(!b){process.stdout.write(JSON.stringify({decision:'allow'}));process.exit(0);}var m=require(b);if(typeof m==='function')m();else if(m&&typeof m.main==='function')m.main();\" -- --hook config-protection",
"timeout": 30
}
]
}
]
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"name": "ecc",
"version": "2.2.3",
"description": "Experimental ECC adapter metadata for Antigravity 2.0 and agy CLI; native acceptance pending",
"author": {
"name": "Affaan Mustafa",
"url": "https://x.com/affaanmustafa"
},
"homepage": "https://ecc.tools",
"repository": "https://github.com/affaan-m/ECC",
"license": "MIT",
"keywords": [
"antigravity",
"agy",
"agents",
"skills",
"hooks",
"rules",
"tdd",
"code-review",
"security"
]
}
+6
View File
@@ -1341,6 +1341,12 @@ Treat `stable`, `beta`, `experimental`, and `instruction-only` below as capabili
| GitHub Copilot CLI | Beta project adapter | `--target copilot` places skills, adapted agents, and converted rules in `.github/` | ECC hooks and command shims are not installed by this target. |
| Gemini, Zed, Qwen, Hermes, OpenClaw, Kimi, Mistral Vibe, CodeBuddy, JoyCode | Experimental/minimal adapters | Harness-specific selective target | File placement and instruction portability are tested; full Claude feature parity is not claimed. |
The additional Antigravity CLI bridge and plugin metadata are experimental. Its manifest-command and
agent-transform fixtures pass locally; native loader and lifecycle acceptance remain pending. Existing
project/global installers retain their owned hook and MCP configuration. CLI-specific agent tool names
require explicit `ANTIGRAVITY_RUNTIME=cli`; the default project tool mapping remains unchanged. Unsupported
editor search, fetch, and subagent capabilities are omitted instead of mapped to broader tools.
<details>
<summary><strong>Package manager detection</strong></summary>
@@ -46,7 +46,7 @@ The matrix below is rendered from
| Zed | Adapter-backed | Zed project settings; flattened project rules; shared skills; commands; agents | Zed external agents and native Agent Panel permissions are not Claude hooks | `./install.sh --profile minimal --target zed` | `node tests/lib/install-targets.test.js`; `npm run harness:audit -- --format json` | Keep project settings conservative and do not copy BYOK/OpenRouter secrets into `.zed/`. |
| dmux | Adapter-backed | session snapshots; tmux/worktree orchestration status; handoff exports | dmux is an orchestration runtime, not an install target for skills/rules | `node scripts/session-inspect.js --list-adapters`; dmux session target inspection | `node tests/lib/session-adapters.test.js` | Treat dmux events as session/runtime signals, not as a replacement for repo validation. |
| DeepSeek Harness | Adapter-backed | canonical ECC skills (skills/) via native DSH skill roots; command hooks through the first-party @deepseek-ai/dsh-hooks-claude-code bridge (23 commands on 5 of 7 bridged events); hooks config generator (scripts/dsh/generate-hooks-config.js); profile patch mounting with compose-time validation | Claude slash commands and ECC subagent surfaces have no DSH equivalent; workflows are covered by skills; PreCompact, PostToolUseFailure, and SessionEnd hook events have no bridge counterpart; no dedicated installer target; setup is documented manual configuration | link the curated catalog: ln -s /path/to/ECC/skills/<skill> ~/.dsh/skills/<skill>; generate the hooks config: node scripts/dsh/generate-hooks-config.js --ecc-root /path/to/ECC --out ~/.dsh/ecc/hooks-dsh.json; mount a bare - insert: entry for @deepseek-ai/dsh-hooks-claude-code in ~/.dsh/profiles/<profile>/cordis.patch.yml | `node tests/scripts/dsh-generate-hooks-config.test.js`; `node scripts/ci/validate-skills.js`; `dsh --profile <profile> --dump-config` (compose-time validation) | Hook commands embed the ECC checkout path; regenerate the hooks config after moving the repo; Keep the tool-name matcher mapping (Bash to bash, Edit/MultiEdit to edit) in sync with DSH tool names; A plain top-level patch entry is silently dropped; additions require a bare insert entry |
| Antigravity | Adapter-backed | flattened workspace rules (.agents/rules/) with always_on and glob activation frontmatter; slash workflows (.agents/workflows/) projected from commands/; canonical ECC skills (.agents/skills/<name>/SKILL.md); custom agents (.agents/agents/) with adapted flash/pro models and tool allowlists | Claude runtime hooks and MCP configs are not installed by the Antigravity project target; Unsupported Claude tool names are omitted from custom agents because unmapped tool identifiers can stall execution | `./install.sh --profile minimal --target antigravity`; `npx ecc-universal install --profile minimal --target antigravity` | `node tests/lib/antigravity-install-target.test.js`; `node tests/lib/antigravity-rule.test.js`; `node scripts/doctor.js --target antigravity` | Do not copy the repository .agents/ Codex packaging tree wholesale or rename legacy .agent/ directories manually because ecc-install-state.json records absolute managed paths. |
| Antigravity | Adapter-backed | flattened workspace rules (.agents/rules/) with always_on and glob activation frontmatter; slash workflows (.agents/workflows/) projected from commands/; canonical ECC skills (.agents/skills/<name>/SKILL.md); custom agents (.agents/agents/) with adapted flash/pro models and tool allowlists; experimental external-root CLI bridge and plugin metadata (native acceptance pending) | Authenticated native tool and lifecycle acceptance remains unverified; transform fixtures do not establish native compatibility; Unsupported Claude tool names are omitted from custom agents because unmapped tool identifiers can stall execution | `./install.sh --profile minimal --target antigravity`; `npx ecc-universal install --profile minimal --target antigravity` | `node tests/lib/antigravity-install-target.test.js`; `node tests/lib/antigravity-hook-bridge.test.js`; `node tests/lib/antigravity-rule.test.js`; `node scripts/doctor.js --target antigravity` | Do not copy the repository .agents/ Codex packaging tree wholesale or rename legacy .agent/ directories manually because ecc-install-state.json records absolute managed paths.; Default project tools remain unchanged; CLI transforms require explicit ANTIGRAVITY_RUNTIME=cli and unsupported editor tools remain omitted. |
| Qwen Code | Adapter-backed | Qwen home instructions (~/.qwen/QWEN.md); canonical ECC skills, commands, rules, and MCP configs under ~/.qwen/; managed custom agents (~/.qwen/agents/) with Qwen tool IDs, palette colors, and model: inherit | Claude hook runtime parity is not claimed or installed; Empty or null agent tools lists are rejected because Qwen Code treats an empty list in named-agent files as inheriting all parent tools rather than deny-all | `./install.sh --target qwen --profile minimal`; `qwen extensions install https://github.com/affaan-m/ECC:ecc` (extension path; conditional rules only) | `node tests/scripts/qwen-adapt-agents.test.js`; `node tests/lib/install-targets.test.js` | Do not layer a full managed ~/.qwen install over an active Qwen extension install unintentionally, and do not add artificial paths: ["**/*"] globs to common rules. |
| GitHub Copilot | Adapter-backed | project-local skills (.github/skills/) with projected helper paths; custom agents (.github/agents/) restricted to name and description frontmatter; path-scoped instructions (.github/instructions/ecc/**/*.instructions.md) with applyTo glob mapping; managed package-manager detection helpers under .github/ecc/scripts/ | Claude runtime hooks and slash commands are not installed because Copilot CLI governs tool permissions at the session level and lacks slash-command argument substitution; Agent model, tools, and color fields are omitted from Copilot custom agent frontmatter | `./install.sh --profile minimal --target copilot` | `node tests/lib/copilot-install-target.test.js`; `node tests/lib/install-targets.test.js` | Copilot CLI governs tool permissions via session --allow-tool and --deny-tool flags rather than per-agent frontmatter allowlists. |
| Hermes | Adapter-backed | managed home rules, skills, commands, and MCP configs under ~/.hermes/; opt-in self-contained Python hooks (config-protection.py and check-console-log.py) via --modules hermes-hooks --enable-hooks | Full 24-command Claude hook runtime is not installed; Hermes uses its own ~/.hermes/config.yaml event mapping and consent allowlist; Installer never mutates ~/.hermes/config.yaml automatically | `./install.sh --profile minimal --target hermes`; `./install.sh --target hermes --modules hermes-hooks --enable-hooks` | `node tests/hermes-hooks.test.js`; `node tests/lib/install-targets.test.js` | Register hooks manually in ~/.hermes/config.yaml using expanded paths because Hermes resolves hook commands verbatim without ~ expansion, and never commit raw ~/.hermes exports. |
+16
View File
@@ -0,0 +1,16 @@
{
"ecc-guardrails": {
"PreToolUse": [
{
"matcher": "run_command|write_file|edit_file|write_to_file|replace_file_content|multi_replace_file_content",
"hooks": [
{
"type": "command",
"command": "node -e \"const p=require('path'),f=require('fs');function V(d){try{if(!d||typeof d!=='string')return null;var b=p.join(p.resolve(d),'scripts','antigravity','hook-bridge.js');if(!f.existsSync(b))return null;var rb=f.realpathSync(b);var rc=f.realpathSync(process.cwd());if(rb===rc||rb.startsWith(rc+p.sep))return null;return rb;}catch(_){return null;}}function G(){var e=process.env.ANTIGRAVITY_PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT||process.env.ECC_PLUGIN_ROOT;var b=V(e);if(b)return b;var h=require('os').homedir();var c=[p.join(h,'.gemini','config','plugins','ecc'),p.join(h,'.gemini','config','plugins','antigravity-suite'),p.join(h,'.claude','plugins','marketplaces','ecc'),p.join(h,'.claude','plugins','cache','ecc'),p.join(h,'.claude'),p.join(h,'.agents','plugins','ecc'),p.join(h,'.agents','plugins','marketplaces','ecc')];for(var i=0;i<c.length;i++){b=V(c[i]);if(b)return b;}return null;}var b=G();if(!b){process.stdout.write(JSON.stringify({decision:'allow'}));process.exit(0);}var m=require(b);if(typeof m==='function')m();else if(m&&typeof m.main==='function')m.main();\" -- --hook config-protection",
"timeout": 30
}
]
}
]
}
}
+2
View File
@@ -53,6 +53,7 @@
"files": [
".adal/",
".agents/",
".antigravity-plugin/",
".claude-plugin/",
".codex/",
".codex-plugin/",
@@ -113,6 +114,7 @@
"rules/",
"schemas/",
"scripts/agent-convert.js",
"scripts/antigravity/",
"scripts/catalog.js",
"scripts/config-health.py",
"scripts/config_health_constants.py",
+12
View File
@@ -0,0 +1,12 @@
{
"name": "ecc",
"version": "2.2.3",
"description": "Experimental ECC adapter metadata for Antigravity 2.0 and agy CLI; native acceptance pending",
"author": {
"name": "Affaan Mustafa",
"url": "https://x.com/affaanmustafa"
},
"homepage": "https://ecc.tools",
"repository": "https://github.com/affaan-m/ECC",
"license": "MIT"
}
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env node
/**
* Antigravity 2.0 Hook Bridge for ECC
*
* Translates Antigravity 2.0 lifecycle hook payloads (camelCase protojson on stdin)
* to Claude Code / Hermes hook payloads (snake_case on stdin), executes the target
* ECC hook script, and translates the outcome back to Antigravity's expected JSON
* contract on stdout ({ "decision": "allow" | "deny" | "ask", "reason": "..." }).
*/
'use strict';
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const REPO_ROOT = path.resolve(__dirname, '..', '..');
const KNOWN_HOOKS = Object.freeze({
'config-protection': path.join(REPO_ROOT, 'scripts', 'hooks', 'config-protection.js'),
'check-console-log': path.join(REPO_ROOT, 'scripts', 'hooks', 'check-console-log.js'),
'quality-gate': path.join(REPO_ROOT, 'scripts', 'hooks', 'quality-gate.js'),
'pre-bash-commit-quality': path.join(REPO_ROOT, 'scripts', 'hooks', 'pre-bash-commit-quality.js'),
'block-no-verify': path.join(REPO_ROOT, 'scripts', 'hooks', 'block-no-verify.js'),
});
let _hookFlags = null;
function getHookFlags() {
if (_hookFlags === null) {
try {
_hookFlags = require('../lib/hook-flags');
} catch (_) {
try {
_hookFlags = require(path.join(REPO_ROOT, 'scripts', 'lib', 'hook-flags.js'));
} catch (_err) {
_hookFlags = {
areHooksEnabled: () => true,
isHookEnabled: () => true,
isDryRun: () => false,
};
}
}
}
return _hookFlags;
}
function parseArgs(argv) {
const args = Array.isArray(argv) ? argv : [];
let hookTarget = null;
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (arg === '--hook' && i + 1 < args.length) {
hookTarget = args[i + 1];
i += 1;
} else if (arg.startsWith('--hook=')) {
hookTarget = arg.slice('--hook='.length);
} else if (arg === '--script' && i + 1 < args.length) {
hookTarget = args[i + 1];
i += 1;
} else if (arg.startsWith('--script=')) {
hookTarget = arg.slice('--script='.length);
}
}
return { hookTarget };
}
function resolveHookScript(hookTarget) {
if (!hookTarget) return null;
if (Object.prototype.hasOwnProperty.call(KNOWN_HOOKS, hookTarget)) {
const known = KNOWN_HOOKS[hookTarget];
if (fs.existsSync(known)) return known;
}
// Sibling hooks folder relative to this bridge script
const siblingDir = path.resolve(__dirname, '..', 'hooks');
const sibling = path.resolve(siblingDir, `${hookTarget}.js`);
if (sibling.startsWith(siblingDir + path.sep) && fs.existsSync(sibling)) {
return sibling;
}
// Canonical hooks directory under REPO_ROOT (reject path traversal escapes)
const canonicalHooksDir = path.resolve(REPO_ROOT, 'scripts', 'hooks');
const targetScript = path.resolve(canonicalHooksDir, `${hookTarget}.js`);
if (targetScript.startsWith(canonicalHooksDir + path.sep) && fs.existsSync(targetScript)) {
return targetScript;
}
return null;
}
function normalizeAntigravityToClaude(payload) {
const toolCall = payload.toolCall || {};
const rawToolName = String(toolCall.name || '');
const args = toolCall.args || {};
let claudeToolName = rawToolName;
const claudeToolInput = { ...args };
if (
rawToolName === 'edit_file'
|| rawToolName === 'replace_file_content'
|| rawToolName === 'multi_replace_file_content'
) {
claudeToolName = 'Edit';
const filePath = args.TargetFile || args.targetFile || args.Path || args.path || args.filePath || '';
claudeToolInput.file_path = filePath;
claudeToolInput.path = filePath;
claudeToolInput.file = filePath;
} else if (rawToolName === 'write_file' || rawToolName === 'write_to_file') {
claudeToolName = 'Write';
const filePath = args.TargetFile || args.targetFile || args.Path || args.path || args.filePath || '';
claudeToolInput.file_path = filePath;
claudeToolInput.path = filePath;
claudeToolInput.file = filePath;
claudeToolInput.content = args.Content || args.content || '';
} else if (rawToolName === 'run_command') {
claudeToolName = 'Bash';
claudeToolInput.command = args.CommandLine || args.command || '';
} else if (rawToolName === 'read_file' || rawToolName === 'view_file') {
claudeToolName = 'Read';
const filePath = args.TargetFile || args.targetFile || args.Path || args.path || args.filePath || '';
claudeToolInput.file_path = filePath;
claudeToolInput.path = filePath;
}
return {
hook_event_name: 'pre_tool_call',
session_id: payload.conversationId || '',
tool_name: claudeToolName,
tool_input: claudeToolInput,
transcript_path: payload.transcriptPath || '',
cwd: Array.isArray(payload.workspacePaths) && payload.workspacePaths.length > 0
? payload.workspacePaths[0]
: process.cwd(),
};
}
function emitAntigravityDecision(decision, reason) {
const result = { decision };
if (reason) {
result.reason = reason;
}
process.stdout.write(JSON.stringify(result) + '\n');
}
function main() {
const { hookTarget } = parseArgs(process.argv);
const hookFlags = getHookFlags();
// 1. Central ECC policy check: are hooks globally enabled?
if (!hookFlags.areHooksEnabled()) {
emitAntigravityDecision('allow');
process.exit(0);
}
// 2. Is this specific hook enabled in active profile / not in ECC_DISABLED_HOOKS?
if (hookTarget && !hookFlags.isHookEnabled(hookTarget)) {
emitAntigravityDecision('allow');
process.exit(0);
}
// 3. Dry-run mode check
if (hookFlags.isDryRun()) {
emitAntigravityDecision('allow');
process.exit(0);
}
const hookScript = resolveHookScript(hookTarget);
let rawStdin = '';
try {
rawStdin = fs.readFileSync(0, 'utf8');
} catch (_e) {
rawStdin = '';
}
let antigravityPayload = {};
if (rawStdin && rawStdin.trim()) {
try {
antigravityPayload = JSON.parse(rawStdin);
} catch (_err) {
// Unparseable payload fails open per ECC hook contract
emitAntigravityDecision('allow');
process.exit(0);
}
}
if (!hookScript) {
// If no specific hook script was configured or found, allow
emitAntigravityDecision('allow');
process.exit(0);
}
const claudePayload = normalizeAntigravityToClaude(antigravityPayload);
const childStdin = JSON.stringify(claudePayload);
const isPython = hookScript.endsWith('.py');
const runner = isPython ? (process.platform === 'win32' ? 'python' : 'python3') : process.execPath;
const result = spawnSync(runner, [hookScript], {
input: childStdin,
encoding: 'utf8',
timeout: 30000,
cwd: claudePayload.cwd || process.cwd(),
});
if (result.error) {
// Execution failed, fail open with warning
process.stderr.write(`[antigravity-hook-bridge] Error invoking hook ${hookScript}: ${result.error.message}\n`);
emitAntigravityDecision('allow');
process.exit(0);
}
// Parse stdout from hook
const childStdout = (result.stdout || '').trim();
const childStderr = (result.stderr || '').trim();
let childDecision = null;
let childReason = null;
if (childStdout) {
try {
const parsedStdout = JSON.parse(childStdout);
if (parsedStdout && typeof parsedStdout === 'object') {
if (parsedStdout.decision === 'block' || parsedStdout.decision === 'deny') {
childDecision = 'deny';
childReason = parsedStdout.reason || childStderr || 'Operation blocked by ECC guardrail';
}
}
} catch (_ignore) {
// Not JSON stdout, check exit code
}
}
// If exit code is 2 (blocking) or non-zero and not explicitly allowed
if (result.status === 2 || childDecision === 'deny') {
emitAntigravityDecision('deny', childReason || childStderr || 'Operation blocked by ECC config-protection guardrail');
} else if (result.status !== 0 && result.status !== null) {
// Other error
emitAntigravityDecision('deny', childReason || childStderr || `Hook failed with exit code ${result.status}`);
} else {
emitAntigravityDecision('allow');
}
}
if (require.main === module) {
main();
}
module.exports = {
KNOWN_HOOKS,
normalizeAntigravityToClaude,
resolveHookScript,
main,
getHookFlags,
};
+4 -1
View File
@@ -345,9 +345,10 @@ const ADAPTER_RECORDS = Object.freeze([
'slash workflows (.agents/workflows/) projected from commands/',
'canonical ECC skills (.agents/skills/<name>/SKILL.md)',
'custom agents (.agents/agents/) with adapted flash/pro models and tool allowlists',
'experimental external-root CLI bridge and plugin metadata (native acceptance pending)',
],
unsupported_surfaces: [
'Claude runtime hooks and MCP configs are not installed by the Antigravity project target',
'Authenticated native tool and lifecycle acceptance remains unverified; transform fixtures do not establish native compatibility',
'Unsupported Claude tool names are omitted from custom agents because unmapped tool identifiers can stall execution',
],
install_or_onramp: [
@@ -356,11 +357,13 @@ const ADAPTER_RECORDS = Object.freeze([
],
verification_commands: [
'`node tests/lib/antigravity-install-target.test.js`',
'`node tests/lib/antigravity-hook-bridge.test.js`',
'`node tests/lib/antigravity-rule.test.js`',
'`node scripts/doctor.js --target antigravity`',
],
risk_notes: [
'Do not copy the repository .agents/ Codex packaging tree wholesale or rename legacy .agent/ directories manually because ecc-install-state.json records absolute managed paths.',
'Default project tools remain unchanged; CLI transforms require explicit ANTIGRAVITY_RUNTIME=cli and unsupported editor tools remain omitted.',
],
last_verified_at: '2026-10-30',
owner: 'ECC maintainers',
@@ -77,7 +77,7 @@ module.exports = createInstallTargetAdapter({
return modules.flatMap(module => {
const paths = Array.isArray(module.paths) ? module.paths : [];
return paths
const operations = paths
.filter(supportsAntigravitySourcePath)
.flatMap(sourceRelativePath => {
const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);
@@ -223,6 +223,10 @@ module.exports = createInstallTargetAdapter({
return [];
});
return module.id === 'hooks-runtime' ? [...operations,
createManagedScaffoldOperation(module.id, 'scripts/antigravity/hook-bridge.js',
path.join(targetRoot, 'scripts', 'antigravity', 'hook-bridge.js'), 'preserve-relative-path'),
] : operations;
});
},
});
+46 -6
View File
@@ -2,6 +2,32 @@
const { normalizeAgentTools } = require('../agent-tools');
const EDITOR_TOOL_NAMES = Object.freeze({
Read: 'view_file',
ReadFile: 'view_file',
NotebookRead: 'view_file',
Write: 'write_to_file',
Edit: 'replace_file_content',
MultiEdit: 'replace_file_content',
Bash: 'run_command',
WebSearch: 'search_web',
});
const CLI_TOOL_NAMES = Object.freeze({
Read: 'read_file',
ReadFile: 'read_file',
NotebookRead: 'read_file',
Write: 'write_file',
Edit: 'edit_file',
MultiEdit: 'edit_file',
Grep: 'grep_search',
Glob: 'find_by_name',
Bash: 'run_command',
WebSearch: 'search_web',
WebFetch: 'read_url_content',
Task: 'invoke_subagent',
});
const TOOL_NAMES = Object.freeze({
Read: 'view_file',
ReadFile: 'view_file',
@@ -22,6 +48,16 @@ const MODEL_NAMES = Object.freeze({
opus: 'pro',
});
function resolveToolMap(runtimeOrOptions) {
const runtime = typeof runtimeOrOptions === 'string'
? runtimeOrOptions
: (runtimeOrOptions?.runtime || runtimeOrOptions?.capability || process.env.ANTIGRAVITY_RUNTIME || 'project');
if (runtime === 'editor') return EDITOR_TOOL_NAMES;
if (runtime === 'cli') return CLI_TOOL_NAMES;
return TOOL_NAMES;
}
function splitFrontmatter(source, label) {
const raw = String(source || '');
const match = raw.match(/^---(\r?\n)([\s\S]*?)\r?\n---(\r?\n)/);
@@ -45,18 +81,19 @@ function splitFrontmatter(source, label) {
};
}
function normalizeToolNames(value) {
function normalizeToolNames(value, toolMap = CLI_TOOL_NAMES) {
return [...new Set(normalizeAgentTools(value)
.filter(name => Object.hasOwn(TOOL_NAMES, name))
.map(name => TOOL_NAMES[name]))];
.filter(name => Object.hasOwn(toolMap, name))
.map(name => toolMap[name]))];
}
function adaptAntigravityAgent(source, label = '<unknown>') {
function adaptAntigravityAgent(source, label = '<unknown>', options = {}) {
const { frontmatter, body, headerEol, trailingFenceEol } = splitFrontmatter(source, label);
const toolMap = resolveToolMap(options);
const { color: _claudeColor, ...supportedFrontmatter } = frontmatter;
const adapted = { ...supportedFrontmatter };
if (Object.hasOwn(frontmatter, 'tools')) {
adapted.tools = normalizeToolNames(frontmatter.tools);
adapted.tools = normalizeToolNames(frontmatter.tools, toolMap);
}
if (Object.hasOwn(frontmatter, 'model')) {
adapted.model = Object.hasOwn(MODEL_NAMES, frontmatter.model)
@@ -72,6 +109,9 @@ function adaptAntigravityAgent(source, label = '<unknown>') {
module.exports = {
adaptAntigravityAgent,
MODEL_NAMES,
resolveToolMap,
EDITOR_TOOL_NAMES,
CLI_TOOL_NAMES,
TOOL_NAMES,
MODEL_NAMES,
};
+511
View File
@@ -0,0 +1,511 @@
/**
* Contract tests for the Antigravity 2.0 hook bridge.
*/
'use strict';
const assert = require('assert');
const path = require('path');
const { spawnSync } = require('child_process');
const REPO_ROOT = path.resolve(__dirname, '..', '..');
const {
normalizeAntigravityToClaude,
resolveHookScript,
} = require(path.join(REPO_ROOT, 'scripts', 'antigravity', 'hook-bridge'));
let passed = 0;
let failed = 0;
function test(name, fn) {
try {
fn();
console.log(` \u2713 ${name}`);
passed += 1;
} catch (error) {
console.log(` \u2717 ${name}`);
console.log(` Error: ${error.message}`);
failed += 1;
}
}
console.log('=== Testing Antigravity Hook Bridge ===\n');
test('resolves known hook aliases to absolute paths', () => {
const resolved = resolveHookScript('config-protection');
assert.ok(resolved, 'Expected config-protection to resolve');
assert.ok(resolved.endsWith('config-protection.js'));
});
test('translates Antigravity edit_file payload to Claude Edit tool shape', () => {
const agyPayload = {
conversationId: 'test-conv-123',
toolCall: {
name: 'edit_file',
args: {
Path: 'eslint.config.js',
Target: 'old',
Replacement: 'new',
},
},
workspacePaths: [REPO_ROOT],
};
const claudePayload = normalizeAntigravityToClaude(agyPayload);
assert.strictEqual(claudePayload.session_id, 'test-conv-123');
assert.strictEqual(claudePayload.tool_name, 'Edit');
assert.strictEqual(claudePayload.tool_input.file_path, 'eslint.config.js');
assert.strictEqual(claudePayload.tool_input.path, 'eslint.config.js');
});
test('normalizes TargetFile argument for replace_file_content and write_to_file', () => {
const replacePayload = {
conversationId: 'conv-targetfile-1',
toolCall: {
name: 'replace_file_content',
args: {
TargetFile: 'prettier.config.js',
Target: 'old',
Replacement: 'new',
},
},
workspacePaths: [REPO_ROOT],
};
const claudeEdit = normalizeAntigravityToClaude(replacePayload);
assert.strictEqual(claudeEdit.tool_name, 'Edit');
assert.strictEqual(claudeEdit.tool_input.file_path, 'prettier.config.js');
const writePayload = {
conversationId: 'conv-targetfile-2',
toolCall: {
name: 'write_to_file',
args: {
TargetFile: 'some.config.js',
Content: 'content',
},
},
workspacePaths: [REPO_ROOT],
};
const claudeWrite = normalizeAntigravityToClaude(writePayload);
assert.strictEqual(claudeWrite.tool_name, 'Write');
assert.strictEqual(claudeWrite.tool_input.file_path, 'some.config.js');
assert.strictEqual(claudeWrite.tool_input.content, 'content');
});
test('translates Antigravity run_command payload to Claude Bash tool shape', () => {
const agyPayload = {
conversationId: 'test-conv-456',
toolCall: {
name: 'run_command',
args: {
CommandLine: 'npm test',
},
},
workspacePaths: [REPO_ROOT],
};
const claudePayload = normalizeAntigravityToClaude(agyPayload);
assert.strictEqual(claudePayload.session_id, 'test-conv-456');
assert.strictEqual(claudePayload.tool_name, 'Bash');
assert.strictEqual(claudePayload.tool_input.command, 'npm test');
});
test('hook bridge blocks modifications to protected files via config-protection hook', () => {
const bridgeScript = path.join(REPO_ROOT, 'scripts', 'antigravity', 'hook-bridge.js');
const agyPayload = {
conversationId: 'block-test',
toolCall: {
name: 'edit_file',
args: {
Path: path.join(REPO_ROOT, 'eslint.config.js'),
Target: 'a',
Replacement: 'b',
},
},
workspacePaths: [REPO_ROOT],
};
const result = spawnSync(process.execPath, [bridgeScript, '--hook', 'config-protection'], {
input: JSON.stringify(agyPayload),
encoding: 'utf8',
cwd: REPO_ROOT,
});
assert.strictEqual(result.status, 0, 'Bridge itself should exit 0 with JSON decision');
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'deny');
assert.ok(decision.reason && decision.reason.length > 0);
});
test('hook bridge allows modifications to unprotected files via config-protection hook', () => {
const bridgeScript = path.join(REPO_ROOT, 'scripts', 'antigravity', 'hook-bridge.js');
const agyPayload = {
conversationId: 'allow-test',
toolCall: {
name: 'edit_file',
args: {
Path: path.join(REPO_ROOT, 'some-regular-feature.js'),
Target: 'a',
Replacement: 'b',
},
},
workspacePaths: [REPO_ROOT],
};
const result = spawnSync(process.execPath, [bridgeScript, '--hook', 'config-protection'], {
input: JSON.stringify(agyPayload),
encoding: 'utf8',
cwd: REPO_ROOT,
});
assert.strictEqual(result.status, 0);
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'allow');
});
test('rejects path traversal escapes in resolveHookScript', () => {
assert.strictEqual(resolveHookScript('../../../etc/passwd'), null);
assert.strictEqual(resolveHookScript('..\\..\\malicious'), null);
});
test('honors ECC_HOOKS_ENABLED=false policy by failing open (allow)', () => {
const bridgeScript = path.join(REPO_ROOT, 'scripts', 'antigravity', 'hook-bridge.js');
const agyPayload = {
conversationId: 'disabled-policy-test',
toolCall: {
name: 'edit_file',
args: {
Path: path.join(REPO_ROOT, 'eslint.config.js'),
},
},
};
const result = spawnSync(process.execPath, [bridgeScript, '--hook', 'config-protection'], {
input: JSON.stringify(agyPayload),
encoding: 'utf8',
env: { ...process.env, ECC_HOOKS_ENABLED: 'false' },
cwd: REPO_ROOT,
});
assert.strictEqual(result.status, 0);
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'allow');
});
test('honors ECC_DISABLED_HOOKS=config-protection policy', () => {
const bridgeScript = path.join(REPO_ROOT, 'scripts', 'antigravity', 'hook-bridge.js');
const agyPayload = {
conversationId: 'disabled-hook-test',
toolCall: {
name: 'edit_file',
args: {
Path: path.join(REPO_ROOT, 'eslint.config.js'),
},
},
};
const result = spawnSync(process.execPath, [bridgeScript, '--hook', 'config-protection'], {
input: JSON.stringify(agyPayload),
encoding: 'utf8',
env: { ...process.env, ECC_DISABLED_HOOKS: 'config-protection' },
cwd: REPO_ROOT,
});
assert.strictEqual(result.status, 0);
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'allow');
});
test('honors ECC_DRY_RUN=1 policy without blocking modifications', () => {
const bridgeScript = path.join(REPO_ROOT, 'scripts', 'antigravity', 'hook-bridge.js');
const agyPayload = {
conversationId: 'dry-run-test',
toolCall: {
name: 'edit_file',
args: {
Path: path.join(REPO_ROOT, 'eslint.config.js'),
},
},
};
const result = spawnSync(process.execPath, [bridgeScript, '--hook', 'config-protection'], {
input: JSON.stringify(agyPayload),
encoding: 'utf8',
env: { ...process.env, ECC_DRY_RUN: '1' },
cwd: REPO_ROOT,
});
assert.strictEqual(result.status, 0);
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'allow');
});
test('rejects execution of decoy scripts planted in unrelated project directories', () => {
const fs = require('fs');
const os = require('os');
const tempDecoy = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-decoy-repo-'));
try {
fs.mkdirSync(path.join(tempDecoy, 'scripts', 'antigravity'), { recursive: true });
fs.mkdirSync(path.join(tempDecoy, '.agents', 'scripts', 'antigravity'), { recursive: true });
const sentinelFile = path.join(tempDecoy, 'decoy-executed.txt');
const maliciousCode = `require('fs').writeFileSync(${JSON.stringify(sentinelFile)}, 'PWNED');`;
fs.writeFileSync(path.join(tempDecoy, 'scripts', 'antigravity', 'hook-bridge.js'), maliciousCode);
fs.writeFileSync(path.join(tempDecoy, '.agents', 'scripts', 'antigravity', 'hook-bridge.js'), maliciousCode);
// Read the hooks command from hooks/antigravity-hooks.json
const hookConfig = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'hooks', 'antigravity-hooks.json'), 'utf8'));
const hookCmd = hookConfig['ecc-guardrails'].PreToolUse[0].hooks[0].command;
// Execute the hook command inside the decoy repo without setting ECC plugin env
const agyPayload = {
conversationId: 'decoy-test',
toolCall: { name: 'edit_file', args: { Path: 'safe.js' } }
};
const cleanEnv = { ...process.env };
delete cleanEnv.ANTIGRAVITY_PLUGIN_ROOT;
delete cleanEnv.CLAUDE_PLUGIN_ROOT;
delete cleanEnv.ECC_PLUGIN_ROOT;
cleanEnv.HOME = path.join(tempDecoy, 'empty-home');
// Run hook command in decoy directory
const result = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify(agyPayload),
encoding: 'utf8',
cwd: tempDecoy,
env: cleanEnv,
});
assert.strictEqual(result.status, 0, 'Hook runner must succeed and fail open');
// Sentinel file must NOT have been created!
assert.strictEqual(fs.existsSync(sentinelFile), false, 'Planted decoy bridge must not be executed!');
} finally {
fs.rmSync(tempDecoy, { recursive: true, force: true });
}
});
test('registered command in hooks/antigravity-hooks.json executes allowed and denied calls via entry point', () => {
const fs = require('fs');
const os = require('os');
const tempWorkspace = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-user-project-'));
try {
const protectedFile = path.join(tempWorkspace, 'eslint.config.js');
fs.writeFileSync(protectedFile, 'module.exports = {};');
const safeFile = path.join(tempWorkspace, 'safe-app.js');
fs.writeFileSync(safeFile, 'console.log("hello");');
const hooksConfig = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'hooks', 'antigravity-hooks.json'), 'utf8'));
const hookCmd = hooksConfig['ecc-guardrails'].PreToolUse[0].hooks[0].command;
const envTrusted = {
...process.env,
ANTIGRAVITY_PLUGIN_ROOT: REPO_ROOT,
};
// Allowed call
const resAllow = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify({
conversationId: 'allow-cmd-test',
toolCall: { name: 'edit_file', args: { Path: safeFile } },
workspacePaths: [tempWorkspace],
}),
encoding: 'utf8',
env: envTrusted,
cwd: tempWorkspace,
});
assert.strictEqual(resAllow.status, 0);
const allowDecision = JSON.parse(resAllow.stdout.trim());
assert.strictEqual(allowDecision.decision, 'allow');
// Denied call
const resDeny = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify({
conversationId: 'deny-cmd-test',
toolCall: { name: 'edit_file', args: { Path: protectedFile } },
workspacePaths: [tempWorkspace],
}),
encoding: 'utf8',
env: envTrusted,
cwd: tempWorkspace,
});
assert.strictEqual(resDeny.status, 0);
const denyDecision = JSON.parse(resDeny.stdout.trim());
assert.strictEqual(denyDecision.decision, 'deny');
assert.ok(denyDecision.reason && denyDecision.reason.length > 0);
} finally {
fs.rmSync(tempWorkspace, { recursive: true, force: true });
}
});
test('registered command in .antigravity-plugin/hooks.json executes allowed and denied calls via entry point', () => {
const fs = require('fs');
const os = require('os');
const tempWorkspace = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-user-plugin-project-'));
try {
const protectedFile = path.join(tempWorkspace, 'eslint.config.js');
fs.writeFileSync(protectedFile, 'module.exports = {};');
const safeFile = path.join(tempWorkspace, 'safe-app.js');
fs.writeFileSync(safeFile, 'console.log("hello");');
const hooksConfig = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, '.antigravity-plugin', 'hooks.json'), 'utf8'));
const hookCmd = hooksConfig['ecc-guardrails'].PreToolUse[0].hooks[0].command;
const envTrusted = {
...process.env,
ANTIGRAVITY_PLUGIN_ROOT: REPO_ROOT,
};
// Allowed call
const resAllow = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify({
conversationId: 'allow-plugin-cmd-test',
toolCall: { name: 'edit_file', args: { Path: safeFile } },
workspacePaths: [tempWorkspace],
}),
encoding: 'utf8',
env: envTrusted,
cwd: tempWorkspace,
});
assert.strictEqual(resAllow.status, 0);
const allowDecision = JSON.parse(resAllow.stdout.trim());
assert.strictEqual(allowDecision.decision, 'allow');
// Denied call
const resDeny = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify({
conversationId: 'deny-plugin-cmd-test',
toolCall: { name: 'edit_file', args: { Path: protectedFile } },
workspacePaths: [tempWorkspace],
}),
encoding: 'utf8',
env: envTrusted,
cwd: tempWorkspace,
});
assert.strictEqual(resDeny.status, 0);
const denyDecision = JSON.parse(resDeny.stdout.trim());
assert.strictEqual(denyDecision.decision, 'deny');
assert.ok(denyDecision.reason && denyDecision.reason.length > 0);
} finally {
fs.rmSync(tempWorkspace, { recursive: true, force: true });
}
});
test('rejects execution of forged-receipt sentinel planted in untrusted project', () => {
const fs = require('fs');
const os = require('os');
const tempUntrusted = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-forged-repo-'));
try {
const decoyAgents = path.join(tempUntrusted, '.agents');
const decoyBridgeDir = path.join(decoyAgents, 'scripts', 'antigravity');
fs.mkdirSync(decoyBridgeDir, { recursive: true });
// Plant forged receipt
fs.writeFileSync(path.join(decoyAgents, 'ecc-install-state.json'), JSON.stringify({
schemaVersion: 'ecc.install.v1',
target: { id: 'antigravity-project' },
}));
// Plant sentinel bridge that creates a marker file
const sentinelFile = path.join(tempUntrusted, 'forged-sentinel-executed.marker');
const maliciousCode = `
require('fs').writeFileSync(${JSON.stringify(sentinelFile)}, 'FORGED_EXECUTED');
module.exports = { main() { process.stdout.write(JSON.stringify({ decision: 'deny', reason: 'SENTINEL' })); } };
`;
fs.writeFileSync(path.join(decoyBridgeDir, 'hook-bridge.js'), maliciousCode);
const hooksConfig = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'hooks', 'antigravity-hooks.json'), 'utf8'));
const hookCmd = hooksConfig['ecc-guardrails'].PreToolUse[0].hooks[0].command;
const cleanEnv = { ...process.env };
delete cleanEnv.ANTIGRAVITY_PLUGIN_ROOT;
delete cleanEnv.CLAUDE_PLUGIN_ROOT;
delete cleanEnv.ECC_PLUGIN_ROOT;
cleanEnv.HOME = path.join(tempUntrusted, 'empty-home');
cleanEnv.USERPROFILE = path.join(tempUntrusted, 'empty-home');
const result = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify({
conversationId: 'forged-receipt-test',
toolCall: { name: 'edit_file', args: { Path: 'safe.js' } },
}),
encoding: 'utf8',
cwd: tempUntrusted,
env: cleanEnv,
});
assert.strictEqual(result.status, 0, 'Hook runner must succeed and fail open');
assert.strictEqual(fs.existsSync(sentinelFile), false, 'Forged receipt sentinel must NOT be executed!');
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'allow');
} finally {
fs.rmSync(tempUntrusted, { recursive: true, force: true });
}
});
test('rejects symlink-decoy realpath escapes pointing into untrusted directory', () => {
const fs = require('fs');
const os = require('os');
const tempUntrusted = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-symlink-repo-'));
try {
const sentinelFile = path.join(tempUntrusted, 'symlink-sentinel-executed.marker');
const sentinelDir = path.join(tempUntrusted, 'sentinel-src', 'scripts', 'antigravity');
fs.mkdirSync(sentinelDir, { recursive: true });
fs.writeFileSync(path.join(sentinelDir, 'hook-bridge.js'), `
require('fs').writeFileSync(${JSON.stringify(sentinelFile)}, 'SYMLINK_EXECUTED');
module.exports = { main() { process.stdout.write(JSON.stringify({ decision: 'deny', reason: 'SENTINEL' })); } };
`);
// Create a symlink or junction attempting to escape to sentinel
const symlinkDir = path.join(tempUntrusted, 'symlink-plugin');
try {
fs.symlinkSync(path.join(tempUntrusted, 'sentinel-src'), symlinkDir, 'junction');
} catch (_symErr) {
// If junction/symlink fails on restricted Windows permissions, skip symlink creation
return;
}
const hooksConfig = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'hooks', 'antigravity-hooks.json'), 'utf8'));
const hookCmd = hooksConfig['ecc-guardrails'].PreToolUse[0].hooks[0].command;
const envWithSymlink = {
...process.env,
ANTIGRAVITY_PLUGIN_ROOT: symlinkDir,
};
const result = spawnSync(hookCmd, {
shell: true,
input: JSON.stringify({
conversationId: 'symlink-test',
toolCall: { name: 'edit_file', args: { Path: 'safe.js' } },
}),
encoding: 'utf8',
cwd: tempUntrusted,
env: envWithSymlink,
});
assert.strictEqual(result.status, 0);
assert.strictEqual(fs.existsSync(sentinelFile), false, 'Symlink decoy sentinel must NOT be executed!');
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'allow');
} finally {
fs.rmSync(tempUntrusted, { recursive: true, force: true });
}
});
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
if (failed > 0) {
process.exit(1);
}
+148 -9
View File
@@ -67,9 +67,27 @@ test('antigravity is a supported install target', () => {
assert.ok(SUPPORTED_INSTALL_TARGETS.includes('antigravity'));
});
test('transform maps Claude tools (including MultiEdit/ReadFile/NotebookRead), maps model tiers, and strips color', () => {
test('default project agent tools retain the shipped contract without new subagent authority', () => {
const priorRuntime = process.env.ANTIGRAVITY_RUNTIME;
try {
delete process.env.ANTIGRAVITY_RUNTIME;
const yaml = require('js-yaml');
const adapted = adaptAntigravityAgent(CLAUDE_AGENT, 'agents/code-simplifier.md');
const parsed = yaml.load(adapted.match(/^---\n([\s\S]*?)\n---\n/)[1]);
assert.deepStrictEqual(parsed.tools, [
'view_file', 'replace_file_content', 'write_to_file', 'grep_search',
'find_by_name', 'run_command', 'search_web', 'read_url_content',
]);
assert.ok(!parsed.tools.includes('invoke_subagent'));
} finally {
if (priorRuntime === undefined) delete process.env.ANTIGRAVITY_RUNTIME;
else process.env.ANTIGRAVITY_RUNTIME = priorRuntime;
}
});
test('CLI transform maps Claude tools (including MultiEdit/ReadFile/NotebookRead), maps model tiers, and strips color', () => {
const yaml = require('js-yaml');
const adapted = adaptAntigravityAgent(CLAUDE_AGENT, 'agents/code-simplifier.md');
const adapted = adaptAntigravityAgent(CLAUDE_AGENT, 'agents/code-simplifier.md', { runtime: 'cli' });
const match = adapted.match(/^---\n([\s\S]*?)\n---\n/);
assert.ok(match, 'Expected YAML frontmatter');
const parsed = yaml.load(match[1]);
@@ -79,14 +97,15 @@ test('transform maps Claude tools (including MultiEdit/ReadFile/NotebookRead), m
assert.strictEqual(parsed.model, 'pro');
assert.strictEqual(Object.hasOwn(parsed, 'color'), false);
assert.deepStrictEqual(parsed.tools, [
'view_file',
'replace_file_content',
'write_to_file',
'read_file',
'edit_file',
'write_file',
'grep_search',
'find_by_name',
'run_command',
'search_web',
'read_url_content',
'invoke_subagent',
]);
assert.ok(adapted.includes('## Role'));
assert.ok(adapted.includes('You simplify complex code.'));
@@ -105,10 +124,106 @@ test('transform parses quoted tool scalars and maps haiku to flash', () => {
'Body',
'',
].join('\n');
const adapted = adaptAntigravityAgent(source, 'agents/fast-helper.md');
const adapted = adaptAntigravityAgent(source, 'agents/fast-helper.md', { runtime: 'cli' });
const parsed = yaml.load(adapted.match(/^---\n([\s\S]*?)\n---\n/)[1]);
assert.strictEqual(parsed.model, 'flash');
assert.deepStrictEqual(parsed.tools, ['view_file', 'replace_file_content']);
assert.deepStrictEqual(parsed.tools, ['read_file', 'edit_file']);
});
test('search-only agent receives search tools without shell access (run_command)', () => {
const yaml = require('js-yaml');
const source = [
'---',
'name: read-only-reviewer',
'description: Review without shell',
'tools: Read, Grep, Glob',
'model: sonnet',
'---',
'',
'Review only.',
].join('\n');
const adapted = adaptAntigravityAgent(source, 'agents/read-only-reviewer.md', { runtime: 'cli' });
const parsed = yaml.load(adapted.match(/^---\n([\s\S]*?)\n---\n/)[1]);
assert.deepStrictEqual(parsed.tools, ['read_file', 'grep_search', 'find_by_name']);
assert.strictEqual(parsed.tools.includes('run_command'), false);
});
test('transform-only capability fixture establishes distinct editor and CLI capability boundaries', () => {
const yaml = require('js-yaml');
const allClaudeTools = 'Read, ReadFile, NotebookRead, Write, Edit, MultiEdit, Grep, Glob, Bash, WebSearch, WebFetch, Task';
const source = [
'---',
'name: full-agent',
'description: Agent with all tools',
`tools: ${allClaudeTools}`,
'model: opus',
'---',
'',
'Full agent body',
].join('\n');
// CLI / Antigravity 2.0 runtime
const cliAdapted = adaptAntigravityAgent(source, 'agents/full-agent.md', { runtime: 'cli' });
const cliParsed = yaml.load(cliAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]);
assert.deepStrictEqual(cliParsed.tools, [
'read_file',
'write_file',
'edit_file',
'grep_search',
'find_by_name',
'run_command',
'search_web',
'read_url_content',
'invoke_subagent',
]);
assert.ok(cliParsed.tools.includes('invoke_subagent'), 'CLI runtime must support invoke_subagent');
// Editor-only runtime
const editorAdapted = adaptAntigravityAgent(source, 'agents/full-agent.md', { runtime: 'editor' });
const editorParsed = yaml.load(editorAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]);
assert.deepStrictEqual(editorParsed.tools, [
'view_file',
'write_to_file',
'replace_file_content',
'run_command',
'search_web',
]);
assert.strictEqual(editorParsed.tools.includes('invoke_subagent'), false, 'Editor runtime must exclude invoke_subagent');
// Isolated tool mappings for editor
const grepAdapted = adaptAntigravityAgent('---\nname: grep-agent\ntools: Grep\n---\nbody', 'agents/grep.md', { runtime: 'editor' });
assert.deepStrictEqual(yaml.load(grepAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]).tools, []);
const globAdapted = adaptAntigravityAgent('---\nname: glob-agent\ntools: Glob\n---\nbody', 'agents/glob.md', { runtime: 'editor' });
assert.deepStrictEqual(yaml.load(globAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]).tools, []);
const fetchAdapted = adaptAntigravityAgent('---\nname: fetch-agent\ntools: WebFetch\n---\nbody', 'agents/fetch.md', { runtime: 'editor' });
assert.deepStrictEqual(yaml.load(fetchAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]).tools, []);
const taskAdapted = adaptAntigravityAgent('---\nname: task-agent\ntools: Task\n---\nbody', 'agents/task.md', { runtime: 'editor' });
assert.deepStrictEqual(yaml.load(taskAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]).tools, []);
// Exercise ANTIGRAVITY_RUNTIME environment variable
const priorRuntime = process.env.ANTIGRAVITY_RUNTIME;
try {
process.env.ANTIGRAVITY_RUNTIME = 'editor';
const envAdapted = adaptAntigravityAgent(source, 'agents/full-agent.md');
const envParsed = yaml.load(envAdapted.match(/^---\n([\s\S]*?)\n---\n/)[1]);
assert.deepStrictEqual(envParsed.tools, [
'view_file',
'write_to_file',
'replace_file_content',
'run_command',
'search_web',
]);
assert.strictEqual(envParsed.tools.includes('invoke_subagent'), false);
} finally {
if (priorRuntime === undefined) {
delete process.env.ANTIGRAVITY_RUNTIME;
} else {
process.env.ANTIGRAVITY_RUNTIME = priorRuntime;
}
}
});
test('transform preserves CRLF line endings consistently on Windows-saved agents', () => {
@@ -125,11 +240,11 @@ test('transform preserves CRLF line endings consistently on Windows-saved agents
'Body line 2',
].join('\r\n');
const adapted = adaptAntigravityAgent(crlfSource, 'agents/windows-agent.md');
const adapted = adaptAntigravityAgent(crlfSource, 'agents/windows-agent.md', { runtime: 'cli' });
assert.ok(adapted.includes('\r\n'), 'Expected CRLF line endings to be preserved');
assert.ok(!/[^\r]\n/.test(adapted), 'Expected no mixed bare LF line endings in CRLF output');
assert.ok(!adapted.includes('color:'));
assert.ok(adapted.includes('replace_file_content'));
assert.ok(adapted.includes('edit_file'));
});
test('transform preserves mixed body line endings verbatim without rewriting body LFs', () => {
@@ -167,6 +282,7 @@ test('every planned operation is contained within .agents', () => {
{ id: 'agents-core', paths: ['agents', '.agents', 'AGENTS.md'] },
{ id: 'commands-core', paths: ['commands'] },
{ id: 'framework-language', paths: ['skills/api-design'] },
{ id: 'hooks-core', paths: ['hooks'] },
]);
const root = path.join('/project', '.agents');
assert.ok(operations.length > 0);
@@ -179,6 +295,29 @@ test('every planned operation is contained within .agents', () => {
}
});
test('an unrelated hooks module cannot replace canonical owned hook configuration', () => {
assert.deepStrictEqual(planFor([{ id: 'hooks-core', paths: ['hooks'] }]), []);
});
test('plans hook-bridge and runtime helpers when hooks-runtime is selected', () => {
const operations = planFor([
{
id: 'hooks-runtime',
paths: ['hooks', 'scripts/hooks', 'scripts/lib'],
},
]);
assert.strictEqual(operations.length, 6);
const destPaths = operations.map(op => op.destinationPath);
const hooks = operations.find(op => op.destinationPath === path.join('/project', '.agents', 'hooks.json'));
assert.strictEqual(hooks.kind, 'merge-json');
assert.ok(hooks.mergePayload['ecc-guard'], 'Retain canonical owned hook group');
assert.ok(operations.some(op => op.destinationPath === path.join('/project', '.agents', 'ecc', 'setup.json')));
assert.ok(destPaths.includes(path.join('/project', '.agents', 'hooks.json')));
assert.ok(destPaths.includes(path.join('/project', '.agents', 'scripts', 'antigravity', 'hook-bridge.js')));
assert.ok(destPaths.includes(path.join('/project', '.agents', 'scripts', 'hooks')));
assert.ok(destPaths.includes(path.join('/project', '.agents', 'scripts', 'lib')));
});
test('Antigravity installs non-Markdown agent assets byte-for-byte while adapting Markdown agents', () => {
const { createManifestInstallPlan, applyInstallPlan } = require('../../scripts/lib/install-executor');
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-antigravity-agent-assets-'));
+25
View File
@@ -490,6 +490,31 @@ test('qoder native surface ships in npm package', () => {
assert.ok(packageFiles.has('scripts/hooks/'));
});
// ── Antigravity plugin manifest ───────────────────────────────────────────────
console.log('\n=== .antigravity-plugin/plugin.json ===\n');
const antigravityPluginPath = path.join(repoRoot, '.antigravity-plugin', 'plugin.json');
const antigravityPlugin = loadJsonObject(antigravityPluginPath, '.antigravity-plugin/plugin.json');
test('antigravity plugin.json version matches package.json', () => {
assert.strictEqual(antigravityPlugin.name, 'ecc');
assert.strictEqual(antigravityPlugin.version, expectedVersion);
});
test('antigravity plugin manifest adheres to Antigravity 2.0 discovery specification', () => {
assert.strictEqual(typeof antigravityPlugin.name, 'string');
assert.strictEqual(typeof antigravityPlugin.description, 'string');
assert.ok(fs.existsSync(path.join(repoRoot, '.antigravity-plugin', 'hooks.json')));
// MCP is an explicit consent choice; plugin does not bundle forced mcp_config.json
assert.strictEqual(fs.existsSync(path.join(repoRoot, '.antigravity-plugin', 'mcp_config.json')), false);
});
test('antigravity native surface ships in npm package', () => {
const packageFiles = new Set(rootPackage.files);
assert.ok(packageFiles.has('.antigravity-plugin/'));
assert.ok(packageFiles.has('scripts/antigravity/'));
});
// ── .mcp.json at plugin root ──────────────────────────────────────────────────
// Per official docs: keep .mcp.json at plugin root, NOT inside .codex-plugin/
console.log('\n=== .mcp.json (plugin root) ===\n');
@@ -126,8 +126,10 @@ function buildExpectedPublishPaths(repoRoot) {
"scripts/codex/merge-codex-config.js",
"scripts/codex/merge-mcp-config.js",
".codex-plugin",
".antigravity-plugin",
".qoder-plugin",
"plugins/ecc",
"scripts/antigravity",
".mcp.json",
"install.sh",
"install.ps1",