Merge reviewed experimental Antigravity candidate into combined integration

This commit is contained in:
haelyra committed 2026-11-19 16:33:28 -05:00
commit ea52804c5e
17 files changed
+1292 -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 \"(function bootstrap() { const fs = require('fs'); const path = require('path'); const os = require('os'); const disabled = String(process.env.ECC_HOOKS_ENABLED || '').trim().toLowerCase(); if (['0', 'false', 'no', 'off'].includes(disabled) || process.env.ECC_DRY_RUN === '1') { process.stdout.write(JSON.stringify({ decision: 'allow' })); return; } const chunks = []; let bytes = 0; let settled = false; const deny = () => { if (settled) return; settled = true; clearTimeout(timer); process.stdin.destroy(); process.stdout.write(JSON.stringify({ decision: 'deny', reason: 'ECC could not bind a trusted external hook runtime' })); }; const within = (file, root) => { const relative = path.relative(root, file); return relative === '' || (!path.isAbsolute(relative) && relative.split(path.sep)[0] !== '..'); }; const metadata = file => { const handle = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0)); try { const state = fs.fstatSync(handle); if (!state.isFile() || state.size > 4096) throw new Error(); const buffer = Buffer.alloc(4097); let length = 0; while (length < buffer.length) { const count = fs.readSync(handle, buffer, length, buffer.length - length, null); if (!count) break; length += count; } if (length > 4096) throw new Error(); return buffer.subarray(0, length).toString('utf8').trim(); } finally { fs.closeSync(handle); } }; const gitCommon = directory => { let ancestor = directory; while (true) { const marker = path.join(ancestor, '.git'); if (fs.existsSync(marker)) { const state = fs.statSync(marker); let git = marker; if (!state.isDirectory()) { const pointer = metadata(marker); if (!pointer.startsWith('gitdir:')) throw new Error(); git = path.resolve(ancestor, pointer.slice(7).trim()); } const common = path.join(git, 'commondir'); const real = fs.realpathSync(fs.existsSync(common) ? path.resolve(git, metadata(common)) : git); if (!fs.statSync(real).isDirectory()) throw new Error(); return real; } const parent = path.dirname(ancestor); if (parent === ancestor) return null; ancestor = parent; } }; const timer = setTimeout(deny, 3000); process.stdin.on('data', chunk => { bytes += chunk.length; if (bytes > 1048576) deny(); else if (!settled) chunks.push(chunk); }); process.stdin.once('error', deny); process.stdin.once('end', () => { if (settled) return; try { const raw = Buffer.concat(chunks).toString('utf8'); const payload = JSON.parse(raw); if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error(); if (!Array.isArray(payload.workspacePaths) || !payload.workspacePaths.length || payload.workspacePaths.length > 32) throw new Error(); const cwd = fs.realpathSync(process.cwd()); const roots = payload.workspacePaths.map(root => { if (typeof root !== 'string' || root.length > 32768 || !path.isAbsolute(root)) throw new Error(); const real = fs.realpathSync(root); if (!fs.statSync(real).isDirectory()) throw new Error(); return real; }); if (!roots.some(root => within(cwd, root))) throw new Error(); const workspaceGit = [cwd, ...roots].map(gitCommon).filter(Boolean); let ancestor = cwd; while (true) { if (fs.existsSync(path.join(ancestor, '.git'))) { roots.push(ancestor); break; } const parent = path.dirname(ancestor); if (parent === ancestor) break; ancestor = parent; } const home = os.homedir(); const candidates = [ process.env.ANTIGRAVITY_PLUGIN_ROOT, process.env.ECC_PLUGIN_ROOT, process.env.CLAUDE_PLUGIN_ROOT, path.join(home, '.gemini', 'config', 'plugins', 'ecc'), path.join(home, '.gemini', 'config', 'plugins', 'antigravity-suite'), path.join(home, '.claude', 'plugins', 'marketplaces', 'ecc'), path.join(home, '.claude', 'plugins', 'cache', 'ecc'), path.join(home, '.agents', 'plugins', 'ecc'), ]; for (const candidate of candidates) { if (typeof candidate !== 'string' || !path.isAbsolute(candidate)) continue; let bridge; try { const candidatePath = path.resolve(candidate); let prefix = path.parse(candidatePath).root; const components = path.relative(prefix, candidatePath).split(path.sep).filter(Boolean); const crossesWorkspace = components.some(component => { prefix = path.join(prefix, component); const real = fs.realpathSync(prefix); return roots.some(workspace => within(real, workspace)); }); if (crossesWorkspace) continue; const root = fs.realpathSync(candidatePath); bridge = fs.realpathSync(path.join(root, 'scripts', 'antigravity', 'hook-bridge.js')); if (!fs.statSync(bridge).isFile() || !within(bridge, root) || roots.some(workspace => within(bridge, workspace))) continue; const candidateGit = gitCommon(path.dirname(bridge)); if (candidateGit && workspaceGit.some(common => path.relative(common, candidateGit) === '')) continue; } catch { continue; } settled = true; clearTimeout(timer); const runtime = require(bridge); if (!runtime || runtime.protocol !== 'ecc.antigravity-cli.v1' || typeof runtime.main !== 'function') throw new Error(); Promise.resolve(runtime.main(raw)).catch(() => { processLine truncated
"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"
]
}
+9
View File
@@ -1341,6 +1341,15 @@ 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. Enabled
bridge calls require complete JSON and an explicit `workspacePaths` context containing the hook working
directory; unbound, incomplete, or invalid safety calls deny instead of guessing. The bootstrap reads at
most 1 MiB and accepts up to 32 absolute workspace roots. 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 \"(function bootstrap() { const fs = require('fs'); const path = require('path'); const os = require('os'); const disabled = String(process.env.ECC_HOOKS_ENABLED || '').trim().toLowerCase(); if (['0', 'false', 'no', 'off'].includes(disabled) || process.env.ECC_DRY_RUN === '1') { process.stdout.write(JSON.stringify({ decision: 'allow' })); return; } const chunks = []; let bytes = 0; let settled = false; const deny = () => { if (settled) return; settled = true; clearTimeout(timer); process.stdin.destroy(); process.stdout.write(JSON.stringify({ decision: 'deny', reason: 'ECC could not bind a trusted external hook runtime' })); }; const within = (file, root) => { const relative = path.relative(root, file); return relative === '' || (!path.isAbsolute(relative) && relative.split(path.sep)[0] !== '..'); }; const metadata = file => { const handle = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0)); try { const state = fs.fstatSync(handle); if (!state.isFile() || state.size > 4096) throw new Error(); const buffer = Buffer.alloc(4097); let length = 0; while (length < buffer.length) { const count = fs.readSync(handle, buffer, length, buffer.length - length, null); if (!count) break; length += count; } if (length > 4096) throw new Error(); return buffer.subarray(0, length).toString('utf8').trim(); } finally { fs.closeSync(handle); } }; const gitCommon = directory => { let ancestor = directory; while (true) { const marker = path.join(ancestor, '.git'); if (fs.existsSync(marker)) { const state = fs.statSync(marker); let git = marker; if (!state.isDirectory()) { const pointer = metadata(marker); if (!pointer.startsWith('gitdir:')) throw new Error(); git = path.resolve(ancestor, pointer.slice(7).trim()); } const common = path.join(git, 'commondir'); const real = fs.realpathSync(fs.existsSync(common) ? path.resolve(git, metadata(common)) : git); if (!fs.statSync(real).isDirectory()) throw new Error(); return real; } const parent = path.dirname(ancestor); if (parent === ancestor) return null; ancestor = parent; } }; const timer = setTimeout(deny, 3000); process.stdin.on('data', chunk => { bytes += chunk.length; if (bytes > 1048576) deny(); else if (!settled) chunks.push(chunk); }); process.stdin.once('error', deny); process.stdin.once('end', () => { if (settled) return; try { const raw = Buffer.concat(chunks).toString('utf8'); const payload = JSON.parse(raw); if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error(); if (!Array.isArray(payload.workspacePaths) || !payload.workspacePaths.length || payload.workspacePaths.length > 32) throw new Error(); const cwd = fs.realpathSync(process.cwd()); const roots = payload.workspacePaths.map(root => { if (typeof root !== 'string' || root.length > 32768 || !path.isAbsolute(root)) throw new Error(); const real = fs.realpathSync(root); if (!fs.statSync(real).isDirectory()) throw new Error(); return real; }); if (!roots.some(root => within(cwd, root))) throw new Error(); const workspaceGit = [cwd, ...roots].map(gitCommon).filter(Boolean); let ancestor = cwd; while (true) { if (fs.existsSync(path.join(ancestor, '.git'))) { roots.push(ancestor); break; } const parent = path.dirname(ancestor); if (parent === ancestor) break; ancestor = parent; } const home = os.homedir(); const candidates = [ process.env.ANTIGRAVITY_PLUGIN_ROOT, process.env.ECC_PLUGIN_ROOT, process.env.CLAUDE_PLUGIN_ROOT, path.join(home, '.gemini', 'config', 'plugins', 'ecc'), path.join(home, '.gemini', 'config', 'plugins', 'antigravity-suite'), path.join(home, '.claude', 'plugins', 'marketplaces', 'ecc'), path.join(home, '.claude', 'plugins', 'cache', 'ecc'), path.join(home, '.agents', 'plugins', 'ecc'), ]; for (const candidate of candidates) { if (typeof candidate !== 'string' || !path.isAbsolute(candidate)) continue; let bridge; try { const candidatePath = path.resolve(candidate); let prefix = path.parse(candidatePath).root; const components = path.relative(prefix, candidatePath).split(path.sep).filter(Boolean); const crossesWorkspace = components.some(component => { prefix = path.join(prefix, component); const real = fs.realpathSync(prefix); return roots.some(workspace => within(real, workspace)); }); if (crossesWorkspace) continue; const root = fs.realpathSync(candidatePath); bridge = fs.realpathSync(path.join(root, 'scripts', 'antigravity', 'hook-bridge.js')); if (!fs.statSync(bridge).isFile() || !within(bridge, root) || roots.some(workspace => within(bridge, workspace))) continue; const candidateGit = gitCommon(path.dirname(bridge)); if (candidateGit && workspaceGit.some(common => path.relative(common, candidateGit) === '')) continue; } catch { continue; } settled = true; clearTimeout(timer); const runtime = require(bridge); if (!runtime || runtime.protocol !== 'ecc.antigravity-cli.v1' || typeof runtime.main !== 'function') throw new Error(); Promise.resolve(runtime.main(raw)).catch(() => { processLine truncated
"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"
}
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env node
'use strict';
// Experimental CLI payload adapter. Canonical Antigravity hooks retain policy
// selection and all permission-decision translation.
const path = require('path');
const { spawnSync } = require('child_process');
const { readStdinRaw, resolveMaxStdin } = require('../hooks/hook-input');
const REPO_ROOT = path.resolve(__dirname, '..', '..');
const CANONICAL_HOOK_IDS = Object.freeze({
'config-protection': 'pre:config-protection',
'gateguard-fact-force': 'pre:edit-write:gateguard-fact-force',
'block-no-verify': 'pre:bash:dispatcher',
'pre-bash-commit-quality': 'pre:bash:dispatcher',
});
const KNOWN_HOOKS = Object.freeze(Object.fromEntries(Object.keys(CANONICAL_HOOK_IDS)
.map(name => [name, path.join(REPO_ROOT, 'scripts', 'hooks', `${name}.js`)])));
function getHookFlags() { return require('../lib/hook-flags'); }
function parseArgs(argv) {
let hookTarget = null;
for (let index = 0; index < argv.length; index += 1) {
if (argv[index] === '--hook') hookTarget = argv[++index];
else if (argv[index].startsWith('--hook=')) hookTarget = argv[index].slice(7);
}
return { hookTarget };
}
function resolveHookScript(hookTarget) {
return Object.hasOwn(KNOWN_HOOKS, hookTarget || '') ? KNOWN_HOOKS[hookTarget] : 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) {
process.stdout.write(JSON.stringify({ decision, ...(reason ? { reason } : {}) }) + '\n');
}
async function main(providedRaw) {
try {
const { hookTarget } = parseArgs(process.argv);
const flags = getHookFlags();
if (!flags.areHooksEnabled() || flags.isDryRun()) {
emitAntigravityDecision('allow');
return;
}
if (!Object.hasOwn(CANONICAL_HOOK_IDS, hookTarget || '')) {
emitAntigravityDecision('deny', 'Unsupported ECC safety hook');
return;
}
// Preserve old explicit alias opt-outs; the canonical child owns profiles
// and canonical hook IDs, including mandatory guards in minimal profiles.
if (flags.getDisabledHookIds().has(hookTarget)) {
emitAntigravityDecision('allow');
return;
}
const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES);
const input = typeof providedRaw === 'string'
? { raw: providedRaw, truncated: Buffer.byteLength(providedRaw) > maxStdin }
: await readStdinRaw(process.stdin, { maxStdin });
if (input.truncated) throw new Error('Incomplete hook input');
const payload = JSON.parse(input.raw);
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('Invalid hook input');
const normalized = normalizeAntigravityToClaude(payload);
if (!['Edit', 'Write', 'Read', 'Bash'].includes(normalized.tool_name)) throw new Error('Unknown native tool');
const target = normalized.tool_name === 'Bash' ? normalized.tool_input.command : normalized.tool_input.file_path;
if (typeof target !== 'string' || !target.trim()) throw new Error('Missing native tool arguments');
const result = spawnSync(process.execPath, [
path.join(REPO_ROOT, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
'--mode', 'pre-tool-use', '--hook', CANONICAL_HOOK_IDS[hookTarget],
], {
input: JSON.stringify(normalized),
encoding: 'utf8', timeout: 15000, maxBuffer: 1024 * 1024,
cwd: process.cwd(),
});
if (result.error || result.status !== 0) throw new Error('Canonical hook did not complete');
const decision = JSON.parse(result.stdout);
if (!decision || !['allow', 'deny', 'ask'].includes(decision.decision)) throw new Error('Unknown hook outcome');
emitAntigravityDecision(decision.decision, typeof decision.reason === 'string' ? decision.reason : undefined);
} catch {
emitAntigravityDecision('deny', 'ECC safety hook could not complete with verified input');
}
}
if (require.main === module) main();
module.exports = { protocol: 'ecc.antigravity-cli.v1', KNOWN_HOOKS, CANONICAL_HOOK_IDS, normalizeAntigravityToClaude, resolveHookScript, main, getHookFlags };
+150
View File
@@ -0,0 +1,150 @@
'use strict';
// This builtin-only bootstrap is embedded in trusted plugin manifests. It must
// validate input and workspace boundaries before importing any package code.
function bootstrap() {
const fs = require('fs');
const path = require('path');
const os = require('os');
const disabled = String(process.env.ECC_HOOKS_ENABLED || '').trim().toLowerCase();
if (['0', 'false', 'no', 'off'].includes(disabled) || process.env.ECC_DRY_RUN === '1') {
process.stdout.write(JSON.stringify({ decision: 'allow' }));
return;
}
const chunks = [];
let bytes = 0;
let settled = false;
const deny = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
process.stdin.destroy();
process.stdout.write(JSON.stringify({ decision: 'deny', reason: 'ECC could not bind a trusted external hook runtime' }));
};
const within = (file, root) => {
const relative = path.relative(root, file);
return relative === '' || (!path.isAbsolute(relative) && relative.split(path.sep)[0] !== '..');
};
const metadata = file => {
const handle = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0));
try {
const state = fs.fstatSync(handle);
if (!state.isFile() || state.size > 4096) throw new Error();
const buffer = Buffer.alloc(4097);
let length = 0;
while (length < buffer.length) {
const count = fs.readSync(handle, buffer, length, buffer.length - length, null);
if (!count) break;
length += count;
}
if (length > 4096) throw new Error();
return buffer.subarray(0, length).toString('utf8').trim();
} finally { fs.closeSync(handle); }
};
const gitCommon = directory => {
let ancestor = directory;
while (true) {
const marker = path.join(ancestor, '.git');
if (fs.existsSync(marker)) {
const state = fs.statSync(marker);
let git = marker;
if (!state.isDirectory()) {
const pointer = metadata(marker);
if (!pointer.startsWith('gitdir:')) throw new Error();
git = path.resolve(ancestor, pointer.slice(7).trim());
}
const common = path.join(git, 'commondir');
const real = fs.realpathSync(fs.existsSync(common) ? path.resolve(git, metadata(common)) : git);
if (!fs.statSync(real).isDirectory()) throw new Error();
return real;
}
const parent = path.dirname(ancestor);
if (parent === ancestor) return null;
ancestor = parent;
}
};
const timer = setTimeout(deny, 3000);
process.stdin.on('data', chunk => {
bytes += chunk.length;
if (bytes > 1048576) deny();
else if (!settled) chunks.push(chunk);
});
process.stdin.once('error', deny);
process.stdin.once('end', () => {
if (settled) return;
try {
const raw = Buffer.concat(chunks).toString('utf8');
const payload = JSON.parse(raw);
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error();
if (!Array.isArray(payload.workspacePaths) || !payload.workspacePaths.length || payload.workspacePaths.length > 32) throw new Error();
const cwd = fs.realpathSync(process.cwd());
const roots = payload.workspacePaths.map(root => {
if (typeof root !== 'string' || root.length > 32768 || !path.isAbsolute(root)) throw new Error();
const real = fs.realpathSync(root);
if (!fs.statSync(real).isDirectory()) throw new Error();
return real;
});
if (!roots.some(root => within(cwd, root))) throw new Error();
const workspaceGit = [cwd, ...roots].map(gitCommon).filter(Boolean);
let ancestor = cwd;
while (true) {
if (fs.existsSync(path.join(ancestor, '.git'))) { roots.push(ancestor); break; }
const parent = path.dirname(ancestor);
if (parent === ancestor) break;
ancestor = parent;
}
const home = os.homedir();
const candidates = [
process.env.ANTIGRAVITY_PLUGIN_ROOT, process.env.ECC_PLUGIN_ROOT, process.env.CLAUDE_PLUGIN_ROOT,
path.join(home, '.gemini', 'config', 'plugins', 'ecc'),
path.join(home, '.gemini', 'config', 'plugins', 'antigravity-suite'),
path.join(home, '.claude', 'plugins', 'marketplaces', 'ecc'),
path.join(home, '.claude', 'plugins', 'cache', 'ecc'),
path.join(home, '.agents', 'plugins', 'ecc'),
];
for (const candidate of candidates) {
if (typeof candidate !== 'string' || !path.isAbsolute(candidate)) continue;
let bridge;
try {
const candidatePath = path.resolve(candidate);
let prefix = path.parse(candidatePath).root;
const components = path.relative(prefix, candidatePath).split(path.sep).filter(Boolean);
const crossesWorkspace = components.some(component => {
prefix = path.join(prefix, component);
const real = fs.realpathSync(prefix);
return roots.some(workspace => within(real, workspace));
});
if (crossesWorkspace) continue;
const root = fs.realpathSync(candidatePath);
bridge = fs.realpathSync(path.join(root, 'scripts', 'antigravity', 'hook-bridge.js'));
if (!fs.statSync(bridge).isFile() || !within(bridge, root) || roots.some(workspace => within(bridge, workspace))) continue;
const candidateGit = gitCommon(path.dirname(bridge));
if (candidateGit && workspaceGit.some(common => path.relative(common, candidateGit) === '')) continue;
} catch { continue; }
settled = true;
clearTimeout(timer);
const runtime = require(bridge);
if (!runtime || runtime.protocol !== 'ecc.antigravity-cli.v1' || typeof runtime.main !== 'function') throw new Error();
Promise.resolve(runtime.main(raw)).catch(() => {
process.stdout.write(JSON.stringify({ decision: 'deny', reason: 'ECC safety runtime failed' }));
});
return;
}
deny();
} catch {
/* Re-enable the single denial if a bound runtime failed during import. */
settled = false;
deny();
}
});
}
function buildAntigravityCliHookCommand() {
const source = `(${bootstrap.toString()})()`.replace(/\s+/g, ' ');
// The shell wrapper contains only first-party constant code, with no shell
// substitutions or embedded caller data. Native payloads remain on stdin.
if (/["$`\\]/.test(source)) throw new Error('Bootstrap contains shell-sensitive source');
return `node -e "${source}" -- --hook config-protection`;
}
module.exports = { bootstrap, buildAntigravityCliHookCommand };
+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,
};
+196
View File
@@ -0,0 +1,196 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { randomUUID } = require('node:crypto');
const { buildAntigravityCliHookCommand } = require('../../scripts/lib/antigravity-cli-bootstrap');
const root = path.resolve(__dirname, '../..');
const bridge = path.join(root, 'scripts/antigravity/hook-bridge.js');
const runtimeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-test-home-'));
let passed = 0;
let failed = 0;
function test(name, run) {
try { run(); passed++; console.log(`PASS ${name}`); }
catch (error) { failed++; console.log(`FAIL ${name}: ${error.stack}`); }
}
function workspace(run) {
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-agy-boundary-'));
try { run(temporary); } finally { fs.rmSync(temporary, { recursive: true, force: true }); }
}
function result(command, args, input, cwd, extraEnv = {}, shell = false) {
const child = spawnSync(command, args, {
input, cwd, shell, encoding: 'utf8', timeout: 22000, maxBuffer: 2 * 1024 * 1024,
env: {
...process.env, HOME: runtimeHome, USERPROFILE: runtimeHome,
XDG_CONFIG_HOME: path.join(runtimeHome, 'config'), ECC_AGENT_DATA_HOME: path.join(runtimeHome, 'data'),
ECC_HOOK_CONFIG: path.join(runtimeHome, 'hooks.json'), CLAUDE_SESSION_ID: randomUUID(),
ECC_HOOKS_ENABLED: 'true', ECC_DRY_RUN: '0', ECC_HOOK_PROFILE: 'standard', ECC_DISABLED_HOOKS: '', ...extraEnv,
},
});
assert.equal(child.status, 0, child.stderr);
return JSON.parse(child.stdout);
}
function manifest(input, cwd, env = {}) {
const raw = JSON.stringify(input);
const generated = result(buildAntigravityCliHookCommand(), [], raw, cwd, env, true);
// Exercise the original function as a module too: generated Node source has
// no file identity for coverage and must keep the same boundary decisions.
const loaded = result(process.execPath, [
'-e', 'require(process.argv[1]).bootstrap()',
path.join(root, 'scripts/lib/antigravity-cli-bootstrap.js'), '--hook', 'config-protection',
], raw, cwd, env);
assert.deepEqual(loaded, generated, 'Module and published bootstrap must agree');
return generated;
}
function sentinel(directory, marker) {
const script = path.join(directory, 'scripts/antigravity/hook-bridge.js');
fs.mkdirSync(path.dirname(script), { recursive: true });
fs.writeFileSync(script, `require('fs').writeFileSync(${JSON.stringify(marker)}, 'executed'); module.exports={};`);
}
test('both published manifests use the same bounded first-party bootstrap', () => {
for (const file of ['hooks/antigravity-hooks.json', '.antigravity-plugin/hooks.json']) {
const manifest = JSON.parse(fs.readFileSync(path.join(root, file)));
assert.equal(manifest['ecc-guardrails'].PreToolUse[0].hooks[0].command, buildAntigravityCliHookCommand());
}
});
test('external canonical runtime preserves allow, deny and explicit bootstrap bypasses', () => workspace(temporary => {
fs.writeFileSync(path.join(temporary, 'app.js'), 'export default 1;');
fs.writeFileSync(path.join(temporary, 'eslint.config.js'), 'module.exports = [];');
for (const [file, expected] of [['app.js', 'allow'], ['eslint.config.js', 'deny']]) {
const payload = {
workspacePaths: [temporary],
toolCall: { name: 'edit_file', args: { Path: path.join(temporary, file) } },
};
assert.equal(manifest(payload, temporary, { ANTIGRAVITY_PLUGIN_ROOT: root }).decision, expected);
}
assert.equal(manifest({}, temporary, { ECC_HOOKS_ENABLED: 'false' }).decision, 'allow');
assert.equal(manifest({}, temporary, { ECC_DRY_RUN: '1' }).decision, 'allow');
}));
test('nested cwd cannot authorize a bridge anywhere inside the declared outer workspace', () => workspace(temporary => {
const nested = path.join(temporary, 'src'); fs.mkdirSync(nested);
const candidate = path.join(temporary, 'plugin'); const marker = path.join(temporary, 'executed');
sentinel(candidate, marker);
assert.equal(manifest({ workspacePaths: [temporary] }, nested, { ANTIGRAVITY_PLUGIN_ROOT: candidate }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
}));
test('secondary workspace roots and symlink aliases cannot authorize imports', () => workspace(temporary => {
const first = path.join(temporary, 'first'); const second = path.join(temporary, 'second');
fs.mkdirSync(first); fs.mkdirSync(second);
const candidate = path.join(second, 'plugin'); const marker = path.join(temporary, 'executed');
sentinel(candidate, marker);
assert.equal(manifest({ workspacePaths: [first, second] }, first, { ANTIGRAVITY_PLUGIN_ROOT: candidate }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
const alias = path.join(temporary, 'alias');
try { fs.symlinkSync(candidate, alias, process.platform === 'win32' ? 'junction' : 'dir'); }
catch (error) { if (process.platform === 'win32' && error.code === 'EPERM') return; throw error; }
assert.equal(manifest({ workspacePaths: [first, second] }, first, { ANTIGRAVITY_PLUGIN_ROOT: alias }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
}));
test('a workspace-owned root alias cannot grant authority to an outside target', () => workspace(temporary => {
const directory = path.join(temporary, 'workspace'); fs.mkdirSync(directory);
const candidate = path.join(temporary, 'external'); const marker = path.join(temporary, 'executed');
sentinel(candidate, marker);
const alias = path.join(directory, 'plugin');
try { fs.symlinkSync(candidate, alias, process.platform === 'win32' ? 'junction' : 'dir'); }
catch (error) { if (process.platform === 'win32' && error.code === 'EPERM') return; throw error; }
assert.equal(manifest({ workspacePaths: [directory] }, directory, { ANTIGRAVITY_PLUGIN_ROOT: alias }).decision, 'deny');
const ancestor = path.join(temporary, 'access');
fs.symlinkSync(directory, ancestor, process.platform === 'win32' ? 'junction' : 'dir');
assert.equal(manifest({ workspacePaths: [directory] }, directory, { ANTIGRAVITY_PLUGIN_ROOT: path.join(ancestor, 'plugin') }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
}));
test('enclosing Git roots and linked-worktree common directories remain excluded', () => workspace(temporary => {
const repository = path.join(temporary, 'repository'); const nested = path.join(repository, 'src');
const git = path.join(repository, '.git'); const linked = path.join(temporary, 'linked');
fs.mkdirSync(nested, { recursive: true }); fs.mkdirSync(git); fs.mkdirSync(linked);
const metadata = path.join(git, 'worktrees', 'linked'); fs.mkdirSync(metadata, { recursive: true });
fs.writeFileSync(path.join(metadata, 'commondir'), '../..');
fs.writeFileSync(path.join(linked, '.git'), `gitdir: ${metadata}`);
const marker = path.join(temporary, 'executed'); sentinel(linked, marker);
assert.equal(manifest({ workspacePaths: [nested] }, nested, { ANTIGRAVITY_PLUGIN_ROOT: linked }).decision, 'deny');
assert.equal(manifest({}, nested, { ANTIGRAVITY_PLUGIN_ROOT: linked }).decision, 'deny');
const other = path.join(temporary, 'other'); fs.mkdirSync(other);
assert.equal(manifest({ workspacePaths: [other, nested] }, other, { ANTIGRAVITY_PLUGIN_ROOT: linked }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
}));
test('invalid workspace metadata fails closed before loading candidate code', () => workspace(temporary => {
const candidate = path.join(temporary, 'plugin'); const marker = path.join(temporary, 'executed');
sentinel(candidate, marker);
for (const workspacePaths of [null, [], [3], ['relative'], Array(33).fill(temporary), [path.join(temporary, 'missing')]]) {
assert.equal(manifest({ workspacePaths }, temporary, { ANTIGRAVITY_PLUGIN_ROOT: candidate }).decision, 'deny');
}
assert.equal(fs.existsSync(marker), false);
}));
test('a Git identity pointing to a regular file cannot establish an import boundary', () => workspace(temporary => {
const directory = path.join(temporary, 'workspace'); fs.mkdirSync(directory);
const invalidGit = path.join(temporary, 'regular-file'); fs.writeFileSync(invalidGit, 'not a Git directory');
fs.writeFileSync(path.join(directory, '.git'), `gitdir: ${invalidGit}`);
const candidate = path.join(temporary, 'external'); const marker = path.join(temporary, 'executed');
sentinel(candidate, marker);
assert.equal(manifest({ workspacePaths: [directory] }, directory, { ANTIGRAVITY_PLUGIN_ROOT: candidate }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
}));
test('active bridge denies malformed, null, array, oversized and unknown-hook input', () => {
for (const raw of ['{', 'null', '[]', '3', 'x'.repeat(1024 * 1024 + 1)]) {
assert.equal(result(process.execPath, [bridge, '--hook', 'config-protection'], raw, root).decision, 'deny');
}
assert.equal(result(process.execPath, [bridge, '--hook', 'not-a-hook'], '{}', root).decision, 'deny');
});
test('oversized native envelopes cannot import even an external candidate', () => workspace(temporary => {
const directory = path.join(temporary, 'workspace'); fs.mkdirSync(directory);
const candidate = path.join(temporary, 'external'); const marker = path.join(temporary, 'executed');
sentinel(candidate, marker);
const payload = { workspacePaths: [directory], padding: 'x'.repeat(1024 * 1024) };
assert.equal(manifest(payload, directory, { ANTIGRAVITY_PLUGIN_ROOT: candidate }).decision, 'deny');
assert.equal(fs.existsSync(marker), false);
}));
test('canonical exit-zero nested permission denials remain denials', () => {
const payload = { toolCall: { name: 'run_command', args: { CommandLine: 'git push --force origin main' } } };
assert.equal(result(process.execPath, [bridge, '--hook', 'gateguard-fact-force'], JSON.stringify(payload), root).decision, 'deny');
});
test('canonical minimal-profile Bash guards stay active and explicit opt-outs stay explicit', () => {
const payload = JSON.stringify({ toolCall: { name: 'run_command', args: { CommandLine: 'git commit --no-verify' } } });
assert.equal(result(process.execPath, [bridge, '--hook', 'block-no-verify'], payload, root, { ECC_HOOK_PROFILE: 'minimal' }).decision, 'deny');
assert.equal(result(process.execPath, [bridge, '--hook', 'block-no-verify'], payload, root, { ECC_DISABLED_HOOKS: 'block-no-verify' }).decision, 'allow');
assert.equal(result(process.execPath, [bridge, '--hook', 'config-protection'], '{', root, { ECC_HOOKS_ENABLED: 'false' }).decision, 'allow');
assert.equal(result(process.execPath, [bridge, '--hook', 'config-protection'], '{', root, { ECC_DRY_RUN: '1' }).decision, 'allow');
});
test('canonical child errors, signals, unknown verdicts and timeout fail closed', () => workspace(temporary => {
const directory = path.join(temporary, 'scripts');
fs.mkdirSync(path.join(directory, 'antigravity'), { recursive: true });
fs.mkdirSync(path.join(directory, 'hooks')); fs.mkdirSync(path.join(directory, 'lib'));
fs.copyFileSync(bridge, path.join(directory, 'antigravity/hook-bridge.js'));
fs.copyFileSync(path.join(root, 'scripts/hooks/hook-input.js'), path.join(directory, 'hooks/hook-input.js'));
fs.writeFileSync(path.join(directory, 'lib/hook-flags.js'), 'module.exports={areHooksEnabled:()=>true,isDryRun:()=>false,getDisabledHookIds:()=>new Set()};');
const canonical = path.join(directory, 'hooks/antigravity-hook-bridge.js');
const payload = JSON.stringify({ toolCall: { name: 'edit_file', args: { Path: 'app.js' } } });
fs.writeFileSync(canonical, 'console.log(JSON.stringify({decision:"allow"}))');
assert.equal(result(process.execPath, [path.join(directory, 'antigravity/hook-bridge.js'), '--hook', 'config-protection'], payload, temporary).decision, 'allow');
for (const source of ['process.exit(1)', 'process.kill(process.pid,"SIGTERM")', 'console.log("{}")', 'process.stdout.write("x".repeat(2*1024*1024))', 'setInterval(()=>{},1000)']) {
fs.writeFileSync(canonical, source);
const started = Date.now();
assert.equal(result(process.execPath, [path.join(directory, 'antigravity/hook-bridge.js'), '--hook', 'config-protection'], payload, temporary).decision, 'deny');
if (source.startsWith('setInterval')) assert.ok(Date.now() - started >= 14000, 'The actual canonical child timeout must run');
}
}));
console.log(`Passed: ${passed}`);
console.log(`Failed: ${failed}`);
fs.rmSync(runtimeHome, { recursive: true, force: true });
process.exitCode = failed ? 1 : 0;
+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 return a structured safety verdict');
// 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 return a structured safety verdict');
assert.strictEqual(fs.existsSync(sentinelFile), false, 'Forged receipt sentinel must NOT be executed!');
const decision = JSON.parse(result.stdout.trim());
assert.strictEqual(decision.decision, 'deny');
} 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, 'deny');
} 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');
@@ -127,8 +127,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",