mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 00:05:27 +00:00
fix(antigravity): resolve PR review comments on hooks bridge, mcp runtime, and quoting
This commit is contained in:
1 parent
689160048a
commit
aa457babfc
14 files changed
+507
-73
No files matched your search
@@ -153,8 +153,9 @@ node "$EccRoot\scripts\uninstall.js" --target antigravity --dry-run
|
||||
## Tier 1 Native Plugin and Global Installation (`antigravity-home`)
|
||||
|
||||
Antigravity supports global plugins located in `~/.gemini/config/plugins/<name>/`. Installing ECC as a native Antigravity plugin enables:
|
||||
|
||||
1. **Global Scope**: ECC rules, skills, agents, workflows, and memory MCP are active across all projects automatically, without requiring a `.agents/` folder in every repository.
|
||||
2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards) and `Stop` hooks using Antigravity's protojson protocol (`{ decision, reason }`).
|
||||
2. **Lifecycle Hooks (`hooks.json`)**: Full support for `PreToolUse` (command security gates, file modification guards) `PostToolUse` edit tracking, and `Stop` formatting and diagnostics using Antigravity's protojson protocol (`{ decision, reason }`).
|
||||
3. **Shared Memory Vault (`mcp_config.json`)**: Direct integration with `ecc-memory-mcp` across all Antigravity sessions.
|
||||
4. **Native Plugin Manifest (`plugin.json`)**: Declares the ECC plugin metadata.
|
||||
|
||||
@@ -171,17 +172,25 @@ PowerShell:
|
||||
& "$EccRoot\install.ps1" --target antigravity-home --profile core --enable-hooks
|
||||
```
|
||||
|
||||
The installer copies the memory server and its runtime dependencies into the
|
||||
managed target. Generated hook and MCP commands use absolute installed paths,
|
||||
so they also work when Antigravity runs from another workspace.
|
||||
|
||||
Project-local hooks use the same runtime; select `--profile core --enable-hooks`
|
||||
with `--target antigravity`. Use `--no-hooks` to omit automatic hooks.
|
||||
|
||||
### Global Plugin Structure
|
||||
|
||||
```text
|
||||
~/.gemini/config/plugins/ecc/
|
||||
├── plugin.json # Antigravity plugin manifest
|
||||
├── hooks.json # PreToolUse and Stop lifecycle hooks
|
||||
├── hooks.json # PreToolUse, PostToolUse, and Stop hooks
|
||||
├── mcp_config.json # Shared ECC Memory Vault MCP server
|
||||
├── rules/ # Rules applied to all workspaces
|
||||
├── workflows/ # Global slash workflows
|
||||
├── skills/ # Global Agent Skills
|
||||
└── scripts/hooks/ # Antigravity hook bridge
|
||||
├── scripts/ # Hook bridge and memory runtime
|
||||
└── node_modules/ # Memory server dependencies
|
||||
```
|
||||
|
||||
## Official Antigravity references
|
||||
@@ -190,6 +199,7 @@ PowerShell:
|
||||
- [Rules and workflows](https://antigravity.google/docs/rules-workflows)
|
||||
- [Custom agents and subagents](https://antigravity.google/docs/subagents)
|
||||
- [Plugins](https://antigravity.google/docs/plugins)
|
||||
- [Lifecycle hooks](https://antigravity.google/docs/hooks)
|
||||
|
||||
See [CONTRIBUTING.md](../CONTRIBUTING.md) for ECC contribution guidance and
|
||||
[SELECTIVE-INSTALL-ARCHITECTURE.md](SELECTIVE-INSTALL-ARCHITECTURE.md) for the
|
||||
|
||||
@@ -103,6 +103,7 @@
|
||||
"cursor",
|
||||
"opencode",
|
||||
"codebuddy",
|
||||
"antigravity",
|
||||
"antigravity-home"
|
||||
],
|
||||
"dependencies": [],
|
||||
|
||||
@@ -14,7 +14,7 @@ const { spawnSync } = require('child_process');
|
||||
const { runPreBash } = require('./bash-hook-dispatcher');
|
||||
const { run: runGateGuard } = require('./gateguard-fact-force');
|
||||
const { run: runDocFileWarning } = require('./doc-file-warning');
|
||||
const { run: runStopFormatTypecheck } = require('./stop-format-typecheck');
|
||||
const { run: runPostEditAccumulator } = require('./post-edit-accumulator');
|
||||
const { readStdinRaw, resolveMaxStdin } = require('./hook-input');
|
||||
|
||||
function parseArgs(argv) {
|
||||
@@ -53,13 +53,22 @@ function adaptAntigravityInputToEcc(antigravityData) {
|
||||
};
|
||||
|
||||
return {
|
||||
tool_name: toolName,
|
||||
tool_name: ({ run_command: 'Bash', write_to_file: 'Write', replace_file_content: 'Edit', multi_replace_file_content: 'Edit' })[toolName] || toolName,
|
||||
tool_input: toolInput,
|
||||
session_id: antigravityData.conversationId || antigravityData.session_id || '',
|
||||
cwd: args.Cwd || antigravityData.cwd || antigravityData.workspacePaths?.[0] || '',
|
||||
conversation_id: antigravityData.conversationId || '',
|
||||
workspace_paths: antigravityData.workspacePaths || [],
|
||||
};
|
||||
}
|
||||
|
||||
function writeFailure(mode, reason) {
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: mode === 'pre-tool-use' ? 'deny' : 'allow',
|
||||
...(mode === 'pre-tool-use' ? { reason } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv);
|
||||
const maxStdin = resolveMaxStdin(process.env.ECC_HOOK_INPUT_MAX_BYTES);
|
||||
@@ -67,19 +76,21 @@ async function main() {
|
||||
let raw = '';
|
||||
try {
|
||||
const inputResult = await readStdinRaw(process.stdin, { maxStdin });
|
||||
if (inputResult.truncated) throw new Error('Incomplete hook input');
|
||||
raw = inputResult.raw;
|
||||
} catch (_err) {
|
||||
// If stdin read fails, fail open safely
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
writeFailure(options.mode, 'ECC hook input could not be read completely');
|
||||
return;
|
||||
}
|
||||
|
||||
let antigravityPayload = {};
|
||||
try {
|
||||
antigravityPayload = raw.trim() ? JSON.parse(raw) : {};
|
||||
antigravityPayload = JSON.parse(raw);
|
||||
if (!antigravityPayload || typeof antigravityPayload !== 'object' || Array.isArray(antigravityPayload)) {
|
||||
throw new Error('Invalid hook input');
|
||||
}
|
||||
} catch (_parseErr) {
|
||||
// Malformed JSON on stdin
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
writeFailure(options.mode, 'ECC hook input must be a valid JSON object');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -97,45 +108,65 @@ async function main() {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, 'config-protection.js')], {
|
||||
input: eccJsonString,
|
||||
encoding: 'utf8',
|
||||
timeout: 4000,
|
||||
});
|
||||
result = {
|
||||
exitCode: child.status || 0,
|
||||
exitCode: child.error || child.status === null ? 2 : child.status,
|
||||
stderr: child.stderr || '',
|
||||
};
|
||||
} else if (options.hook === 'pre:write:doc-file-warning') {
|
||||
result = runDocFileWarning(eccJsonString);
|
||||
}
|
||||
|
||||
if (result && (result.exitCode === 2 || result.denied || result.blocked)) {
|
||||
const reason = result.stderr || result.reason || 'Blocked by ECC safety hook';
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: 'deny',
|
||||
reason: reason.replace(/\r?\n/g, ' ').trim(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
const output = result && (result.stdout || result.output);
|
||||
const hookOutput = output ? JSON.parse(output).hookSpecificOutput : null;
|
||||
const denied = result && ((result.exitCode !== undefined && result.exitCode !== 0) || result.denied || result.blocked)
|
||||
|| hookOutput?.permissionDecision === 'deny';
|
||||
const context = result?.additionalContext || hookOutput?.additionalContext;
|
||||
const reason = denied
|
||||
? hookOutput?.permissionDecisionReason || result.stderr || result.reason || 'Blocked by ECC safety hook'
|
||||
: Array.isArray(context) ? context.join(' ') : context;
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: denied ? 'deny' : 'allow',
|
||||
...(reason ? { reason: String(reason).replace(/\r?\n/g, ' ').trim() } : {}),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
// Both accumulator and batch formatter use the same session-scoped temp file.
|
||||
if (eccPayload.session_id) process.env.CLAUDE_SESSION_ID = String(eccPayload.session_id);
|
||||
|
||||
if (options.mode === 'post-tool-use') {
|
||||
if (options.hook === 'post:edit:accumulator' && !antigravityPayload.error) {
|
||||
runPostEditAccumulator(eccJsonString);
|
||||
}
|
||||
process.stdout.write(JSON.stringify({}));
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.mode === 'stop') {
|
||||
if (antigravityPayload.fullyIdle === false) {
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
let stopResult = { exitCode: 0, stderr: '' };
|
||||
|
||||
if (options.hook === 'stop:format-typecheck') {
|
||||
stopResult = runStopFormatTypecheck(eccJsonString);
|
||||
} else if (options.hook === 'stop:check-console-log') {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, 'check-console-log.js')], {
|
||||
const stopScript = {
|
||||
'stop:format-typecheck': 'stop-format-typecheck.js',
|
||||
'stop:check-console-log': 'check-console-log.js',
|
||||
}[options.hook];
|
||||
if (stopScript) {
|
||||
const child = spawnSync(process.execPath, [path.join(__dirname, stopScript)], {
|
||||
input: eccJsonString,
|
||||
encoding: 'utf8',
|
||||
timeout: options.hook === 'stop:format-typecheck' ? 280000 : 25000,
|
||||
});
|
||||
stopResult = {
|
||||
exitCode: child.status || 0,
|
||||
stderr: child.stderr || '',
|
||||
stderr: child.stderr || (child.error ? 'ECC stop hook failed: ' + child.error.message : ''),
|
||||
};
|
||||
}
|
||||
|
||||
if (stopResult && stopResult.exitCode !== 0 && stopResult.stderr) {
|
||||
if (stopResult && stopResult.stderr) {
|
||||
process.stdout.write(JSON.stringify({
|
||||
decision: 'continue',
|
||||
reason: stopResult.stderr.replace(/\r?\n/g, ' ').trim(),
|
||||
@@ -143,7 +174,7 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(JSON.stringify({}));
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -153,7 +184,7 @@ async function main() {
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch(() => {
|
||||
process.stdout.write(JSON.stringify({ decision: 'allow' }));
|
||||
writeFailure(parseArgs(process.argv).mode, 'ECC safety hook failed unexpectedly');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { shellQuote } = require('./control-pane/actions');
|
||||
|
||||
/**
|
||||
* Antigravity Hooks Generator
|
||||
*
|
||||
@@ -10,7 +13,19 @@
|
||||
|
||||
function buildAntigravityHooksConfig(options = {}) {
|
||||
const profile = options.profile || 'standard';
|
||||
const bridgeScript = options.bridgeScript || 'scripts/hooks/antigravity-hook-bridge.js';
|
||||
const { bridgeScript } = options;
|
||||
if (typeof bridgeScript !== 'string' || !path.isAbsolute(bridgeScript) || bridgeScript.includes('\0')) {
|
||||
throw new Error('bridgeScript must be an absolute path');
|
||||
}
|
||||
let quotedBridgeScript;
|
||||
if (process.platform === 'win32') {
|
||||
if (/[%"!$`\r\n]/.test(bridgeScript)) {
|
||||
throw new Error('bridgeScript contains unsafe shell expansion characters');
|
||||
}
|
||||
quotedBridgeScript = bridgeScript.includes(' ') ? `"${bridgeScript}"` : bridgeScript;
|
||||
} else {
|
||||
quotedBridgeScript = shellQuote(bridgeScript);
|
||||
}
|
||||
|
||||
const preToolUseHandlers = [
|
||||
{
|
||||
@@ -18,22 +33,22 @@ function buildAntigravityHooksConfig(options = {}) {
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${bridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`,
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:bash:dispatcher`,
|
||||
timeout: 15,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
matcher: 'write_to_file|replace_file_content',
|
||||
matcher: 'write_to_file|replace_file_content|multi_replace_file_content',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${bridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`,
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:edit-write:gateguard-fact-force`,
|
||||
timeout: 10,
|
||||
},
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${bridgeScript} --mode pre-tool-use --hook pre:config-protection`,
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:config-protection`,
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
@@ -46,7 +61,7 @@ function buildAntigravityHooksConfig(options = {}) {
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${bridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`,
|
||||
command: `node ${quotedBridgeScript} --mode pre-tool-use --hook pre:write:doc-file-warning`,
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
@@ -56,12 +71,12 @@ function buildAntigravityHooksConfig(options = {}) {
|
||||
const stopHandlers = [
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${bridgeScript} --mode stop --hook stop:format-typecheck`,
|
||||
timeout: 120,
|
||||
command: `node ${quotedBridgeScript} --mode stop --hook stop:format-typecheck`,
|
||||
timeout: 300,
|
||||
},
|
||||
{
|
||||
type: 'command',
|
||||
command: `node ${bridgeScript} --mode stop --hook stop:check-console-log`,
|
||||
command: `node ${quotedBridgeScript} --mode stop --hook stop:check-console-log`,
|
||||
timeout: 30,
|
||||
},
|
||||
];
|
||||
@@ -69,6 +84,14 @@ function buildAntigravityHooksConfig(options = {}) {
|
||||
return {
|
||||
'ecc-guard': {
|
||||
PreToolUse: preToolUseHandlers,
|
||||
PostToolUse: [{
|
||||
matcher: 'write_to_file|replace_file_content|multi_replace_file_content',
|
||||
hooks: [{
|
||||
type: 'command',
|
||||
command: `node ${quotedBridgeScript} --mode post-tool-use --hook post:edit:accumulator`,
|
||||
timeout: 10,
|
||||
}],
|
||||
}],
|
||||
Stop: stopHandlers,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createManagedScaffoldOperation } = require('./install-targets/helpers');
|
||||
|
||||
/**
|
||||
* Antigravity MCP Configuration Generator
|
||||
*
|
||||
@@ -8,7 +12,10 @@
|
||||
*/
|
||||
|
||||
function buildAntigravityMcpConfig(options = {}) {
|
||||
const memoryScript = options.memoryScript || 'scripts/memory-mcp.mjs';
|
||||
const { memoryScript } = options;
|
||||
if (typeof memoryScript !== 'string' || !path.isAbsolute(memoryScript) || memoryScript.includes('\0')) {
|
||||
throw new Error('memoryScript must be an absolute path');
|
||||
}
|
||||
|
||||
return {
|
||||
mcpServers: {
|
||||
@@ -23,6 +30,41 @@ function buildAntigravityMcpConfig(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function planAntigravityMemoryRuntime(moduleId, repoRoot, targetRoot) {
|
||||
const sourcePaths = [
|
||||
'package.json',
|
||||
'scripts/memory-mcp.mjs',
|
||||
'scripts/lib/missing-dependency.js',
|
||||
'scripts/lib/memory-vault.js',
|
||||
'scripts/lib/memory-vault-format.js',
|
||||
'scripts/lib/path-safety.js',
|
||||
];
|
||||
const operations = sourcePaths.map(sourcePath => createManagedScaffoldOperation(
|
||||
moduleId, sourcePath, path.join(targetRoot, sourcePath), 'preserve-relative-path'
|
||||
));
|
||||
function addDependency(name, fromRoot, destinationRoot, ancestors = []) {
|
||||
let manifestPath;
|
||||
try {
|
||||
manifestPath = require.resolve(`${name}/package.json`, { paths: [fromRoot] });
|
||||
} catch (error) {
|
||||
throw new Error(`Cannot install Antigravity memory dependency ${name}. Run npm install in ${repoRoot}: ${error.message}`);
|
||||
}
|
||||
if (ancestors.includes(manifestPath)) return;
|
||||
const packageRoot = path.dirname(manifestPath);
|
||||
const destinationPath = path.join(destinationRoot, 'node_modules', name);
|
||||
operations.push(createManagedScaffoldOperation(
|
||||
moduleId, path.relative(repoRoot, packageRoot), destinationPath, 'preserve-relative-path'
|
||||
));
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
for (const dependency of Object.keys(manifest.dependencies || {})) {
|
||||
addDependency(dependency, packageRoot, destinationPath, [...ancestors, manifestPath]);
|
||||
}
|
||||
}
|
||||
addDependency('ajv', repoRoot, targetRoot);
|
||||
return operations;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildAntigravityMcpConfig,
|
||||
planAntigravityMemoryRuntime,
|
||||
};
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
function buildAntigravityPluginManifest(options = {}) {
|
||||
const version = options.version || '2.2.2';
|
||||
const version = options.version || require('../../package.json').version;
|
||||
return {
|
||||
name: 'ecc',
|
||||
description: 'ECC - The Agent Harness Operating System for Antigravity',
|
||||
|
||||
@@ -658,6 +658,7 @@ function setupClaudePlugin(options = {}, dependencies = {}) {
|
||||
spawnSync: dependencies.spawnSync,
|
||||
});
|
||||
const action = ensurePluginAtScope({
|
||||
hookConfiguration: hookOptions(hooks),
|
||||
hooks,
|
||||
installed: inventory.installed,
|
||||
projectRoot: paths.projectRoot,
|
||||
|
||||
@@ -13,7 +13,7 @@ const {
|
||||
normalizeRelativePath,
|
||||
} = require('./helpers');
|
||||
const { buildAntigravityHooksConfig } = require('../antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig } = require('../antigravity-mcp');
|
||||
const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../antigravity-plugin');
|
||||
|
||||
function readJsonObject(filePath, label) {
|
||||
@@ -131,6 +131,7 @@ module.exports = createInstallTargetAdapter({
|
||||
&& normalizedSourcePath === 'hooks'
|
||||
) {
|
||||
return [
|
||||
createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
@@ -141,6 +142,7 @@ module.exports = createInstallTargetAdapter({
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityHooksConfig({
|
||||
profile: input.hookProfile || 'standard',
|
||||
bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
|
||||
}),
|
||||
}),
|
||||
];
|
||||
@@ -153,7 +155,9 @@ module.exports = createInstallTargetAdapter({
|
||||
const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json')))
|
||||
? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json')
|
||||
: { mcpServers: {} };
|
||||
const antigravityMcp = buildAntigravityMcpConfig();
|
||||
const antigravityMcp = buildAntigravityMcpConfig({
|
||||
memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
});
|
||||
const mergedMcp = {
|
||||
mcpServers: {
|
||||
...(baseMcp.mcpServers || {}),
|
||||
@@ -185,14 +189,7 @@ module.exports = createInstallTargetAdapter({
|
||||
];
|
||||
|
||||
if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) {
|
||||
operations.push(
|
||||
createManagedScaffoldOperation(
|
||||
module.id,
|
||||
'scripts/memory-mcp.mjs',
|
||||
path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
'preserve-relative-path'
|
||||
)
|
||||
);
|
||||
operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot));
|
||||
}
|
||||
|
||||
return operations;
|
||||
|
||||
@@ -9,7 +9,7 @@ const {
|
||||
normalizeRelativePath,
|
||||
} = require('./helpers');
|
||||
const { buildAntigravityHooksConfig } = require('../antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig } = require('../antigravity-mcp');
|
||||
const { buildAntigravityMcpConfig, planAntigravityMemoryRuntime } = require('../antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../antigravity-plugin');
|
||||
|
||||
const SUPPORTED_SOURCE_PREFIXES = [
|
||||
@@ -149,6 +149,7 @@ module.exports = createInstallTargetAdapter({
|
||||
&& normalizedSourcePath === 'hooks'
|
||||
) {
|
||||
return [
|
||||
createManagedScaffoldOperation(module.id, 'package.json', path.join(targetRoot, 'package.json'), 'preserve-relative-path'),
|
||||
createManagedOperation({
|
||||
kind: 'merge-json',
|
||||
moduleId: module.id,
|
||||
@@ -159,6 +160,7 @@ module.exports = createInstallTargetAdapter({
|
||||
scaffoldOnly: false,
|
||||
mergePayload: buildAntigravityHooksConfig({
|
||||
profile: input.hookProfile || 'standard',
|
||||
bridgeScript: path.join(targetRoot, 'scripts', 'hooks', 'antigravity-hook-bridge.js'),
|
||||
}),
|
||||
}),
|
||||
];
|
||||
@@ -171,7 +173,9 @@ module.exports = createInstallTargetAdapter({
|
||||
const baseMcp = (repoRoot && fs.existsSync(path.join(repoRoot, '.mcp.json')))
|
||||
? readJsonObject(path.join(repoRoot, '.mcp.json'), '.mcp.json')
|
||||
: { mcpServers: {} };
|
||||
const antigravityMcp = buildAntigravityMcpConfig();
|
||||
const antigravityMcp = buildAntigravityMcpConfig({
|
||||
memoryScript: path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
});
|
||||
const mergedMcp = {
|
||||
mcpServers: {
|
||||
...(baseMcp.mcpServers || {}),
|
||||
@@ -203,14 +207,7 @@ module.exports = createInstallTargetAdapter({
|
||||
];
|
||||
|
||||
if (repoRoot && fs.existsSync(path.join(repoRoot, 'scripts', 'memory-mcp.mjs'))) {
|
||||
operations.push(
|
||||
createManagedScaffoldOperation(
|
||||
module.id,
|
||||
'scripts/memory-mcp.mjs',
|
||||
path.join(targetRoot, 'scripts', 'memory-mcp.mjs'),
|
||||
'preserve-relative-path'
|
||||
)
|
||||
);
|
||||
operations.push(...planAntigravityMemoryRuntime(module.id, repoRoot, targetRoot));
|
||||
}
|
||||
|
||||
return operations;
|
||||
|
||||
@@ -10,7 +10,7 @@ const { adaptAntigravityInputToEcc } = require('../../scripts/hooks/antigravity-
|
||||
const { buildAntigravityHooksConfig } = require('../../scripts/lib/antigravity-hooks');
|
||||
const { buildAntigravityMcpConfig } = require('../../scripts/lib/antigravity-mcp');
|
||||
const { buildAntigravityPluginManifest } = require('../../scripts/lib/antigravity-plugin');
|
||||
const { getInstallTargetAdapter, listInstallTargetAdapters } = require('../../scripts/lib/install-targets/registry');
|
||||
const { getInstallTargetAdapter } = require('../../scripts/lib/install-targets/registry');
|
||||
const { resolveInstallPlan } = require('../../scripts/lib/install-manifests');
|
||||
const { resolveEccRoot } = require('../../scripts/lib/resolve-ecc-root');
|
||||
|
||||
@@ -57,7 +57,7 @@ function runTests() {
|
||||
};
|
||||
|
||||
const adapted = adaptAntigravityInputToEcc(rawInput);
|
||||
assert.strictEqual(adapted.tool_name, 'run_command');
|
||||
assert.strictEqual(adapted.tool_name, 'Bash');
|
||||
assert.strictEqual(adapted.tool_input.command, 'npm test');
|
||||
assert.strictEqual(adapted.tool_input.CommandLine, 'npm test');
|
||||
assert.strictEqual(adapted.conversation_id, 'conv-1234');
|
||||
@@ -75,7 +75,7 @@ function runTests() {
|
||||
},
|
||||
};
|
||||
const adaptedWrite = adaptAntigravityInputToEcc(writeInput);
|
||||
assert.strictEqual(adaptedWrite.tool_name, 'write_to_file');
|
||||
assert.strictEqual(adaptedWrite.tool_name, 'Write');
|
||||
assert.strictEqual(adaptedWrite.tool_input.file_path, '/workspace/app/src/index.js');
|
||||
|
||||
const replaceInput = {
|
||||
@@ -89,7 +89,7 @@ function runTests() {
|
||||
},
|
||||
};
|
||||
const adaptedReplace = adaptAntigravityInputToEcc(replaceInput);
|
||||
assert.strictEqual(adaptedReplace.tool_name, 'replace_file_content');
|
||||
assert.strictEqual(adaptedReplace.tool_name, 'Edit');
|
||||
assert.strictEqual(adaptedReplace.tool_input.file_path, '/workspace/app/src/index.js');
|
||||
});
|
||||
|
||||
@@ -104,12 +104,14 @@ function runTests() {
|
||||
});
|
||||
|
||||
test('buildAntigravityHooksConfig generates valid Antigravity hooks specification', () => {
|
||||
const config = buildAntigravityHooksConfig({ profile: 'standard' });
|
||||
const config = buildAntigravityHooksConfig({ profile: 'standard', bridgeScript: path.resolve('scripts/hooks/antigravity-hook-bridge.js') });
|
||||
assert.ok(config['ecc-guard'], 'Should have ecc-guard hook entry');
|
||||
const guard = config['ecc-guard'];
|
||||
|
||||
assert.ok(Array.isArray(guard.PreToolUse), 'PreToolUse should be an array');
|
||||
assert.ok(Array.isArray(guard.Stop), 'Stop should be an array');
|
||||
assert.ok(guard.PostToolUse.some(entry => entry.matcher.includes('multi_replace_file_content') && entry.hooks.some(hook => hook.command.includes('post:edit:accumulator'))));
|
||||
assert.ok(guard.Stop.find(hook => hook.command.includes('stop:format-typecheck')).timeout >= 270);
|
||||
|
||||
const commandMatcher = guard.PreToolUse.find(entry => entry.matcher === 'run_command');
|
||||
assert.ok(commandMatcher, 'Should have run_command matcher in PreToolUse');
|
||||
@@ -118,7 +120,7 @@ function runTests() {
|
||||
'Should invoke pre:bash:dispatcher on run_command'
|
||||
);
|
||||
|
||||
const editMatcher = guard.PreToolUse.find(entry => entry.matcher === 'write_to_file|replace_file_content');
|
||||
const editMatcher = guard.PreToolUse.find(entry => entry.matcher === 'write_to_file|replace_file_content|multi_replace_file_content');
|
||||
assert.ok(editMatcher, 'Should have write_to_file|replace_file_content matcher');
|
||||
assert.ok(
|
||||
editMatcher.hooks.some(h => h.command.includes('pre:edit-write:gateguard-fact-force')),
|
||||
@@ -127,7 +129,7 @@ function runTests() {
|
||||
});
|
||||
|
||||
test('buildAntigravityMcpConfig generates valid stdio MCP configuration for ecc-memory', () => {
|
||||
const config = buildAntigravityMcpConfig();
|
||||
const config = buildAntigravityMcpConfig({ memoryScript: path.resolve('scripts/memory-mcp.mjs') });
|
||||
assert.ok(config.mcpServers, 'Should declare mcpServers');
|
||||
assert.ok(config.mcpServers['ecc-memory'], 'Should declare ecc-memory server');
|
||||
const memoryServer = config.mcpServers['ecc-memory'];
|
||||
@@ -142,6 +144,146 @@ function runTests() {
|
||||
assert.ok(manifest.description.includes('Antigravity'));
|
||||
});
|
||||
|
||||
test('generators reject missing, relative, and malformed executable paths', () => {
|
||||
for (const value of [undefined, '', 'relative/script.js', 7, '/tmp/bad\0path']) {
|
||||
assert.throws(() => buildAntigravityHooksConfig({ bridgeScript: value }), /absolute path/);
|
||||
assert.throws(() => buildAntigravityMcpConfig({ memoryScript: value }), /absolute path/);
|
||||
}
|
||||
assert.strictEqual(buildAntigravityPluginManifest().version, require('../../package.json').version);
|
||||
});
|
||||
|
||||
test('hook commands preserve shell metacharacters in the installed path', () => {
|
||||
const dir = createTempDir("ecc space ' $HOME `echo x` ");
|
||||
try {
|
||||
const script = path.join(dir, 'bridge.js');
|
||||
fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))');
|
||||
const config = buildAntigravityHooksConfig({ bridgeScript: script });
|
||||
const command = config['ecc-guard'].PreToolUse[0].hooks[0].command;
|
||||
const run = spawnSync(command, { shell: true, encoding: 'utf8' });
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.deepStrictEqual(JSON.parse(run.stdout), ['--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher']);
|
||||
} finally {
|
||||
cleanup(dir);
|
||||
}
|
||||
});
|
||||
|
||||
for (const target of ['antigravity', 'antigravity-home']) {
|
||||
test(`${target} installed memory server starts outside the source checkout`, () => {
|
||||
const root = createTempDir('ecc-memory-install-');
|
||||
try {
|
||||
const projectRoot = path.join(root, 'project');
|
||||
fs.mkdirSync(projectRoot);
|
||||
fs.writeFileSync(path.join(projectRoot, 'package.json'), '{"type":"module"}');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const plan = createManifestInstallPlan({ moduleIds: ['platform-configs'], target, homeDir: root, projectRoot });
|
||||
applyInstallPlan(plan);
|
||||
const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'mcp_config.json'), 'utf8'));
|
||||
const server = config.mcpServers['ecc-memory'];
|
||||
assert.strictEqual(server.args[0], path.join(plan.targetRoot, 'scripts', 'memory-mcp.mjs'));
|
||||
const run = spawnSync(process.execPath, server.args, {
|
||||
cwd: root,
|
||||
env: { ...process.env, ...server.env, NODE_PATH: '' },
|
||||
input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }) + '\n',
|
||||
encoding: 'utf8',
|
||||
timeout: 10000,
|
||||
});
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.strictEqual(JSON.parse(run.stdout.trim()).id, 1);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('project hooks install and run with explicit consent in an ESM project', () => {
|
||||
const root = createTempDir('ecc-project-hooks-');
|
||||
try {
|
||||
fs.writeFileSync(path.join(root, 'package.json'), '{"type":"module"}');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const { withHookConsent } = require('../../scripts/lib/install/hook-consent');
|
||||
const plan = withHookConsent(createManifestInstallPlan({ moduleIds: ['hooks-runtime'], target: 'antigravity', projectRoot: root }), 'enabled');
|
||||
applyInstallPlan(plan);
|
||||
const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'hooks.json'), 'utf8'));
|
||||
const run = spawnSync(config['ecc-guard'].PreToolUse[0].hooks[0].command, {
|
||||
cwd: root,
|
||||
shell: true,
|
||||
env: { ...process.env, GATEGUARD_BASH_ROUTINE_DISABLED: '1' },
|
||||
input: JSON.stringify({ workspacePaths: [root], toolCall: { name: 'run_command', args: { CommandLine: 'pwd' } } }),
|
||||
encoding: 'utf8',
|
||||
timeout: 10000,
|
||||
});
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.strictEqual(JSON.parse(run.stdout).decision, 'allow', run.stdout);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('memory runtime installs from npm-hoisted dependencies', () => {
|
||||
const root = createTempDir('ecc-hoisted-memory-');
|
||||
try {
|
||||
const sourceRoot = path.join(root, 'node_modules', 'ecc-universal');
|
||||
const repoRoot = path.resolve(__dirname, '../..');
|
||||
for (const relative of ['package.json', 'scripts/memory-mcp.mjs', 'scripts/lib/missing-dependency.js', 'scripts/lib/memory-vault.js', 'scripts/lib/memory-vault-format.js', 'scripts/lib/path-safety.js']) {
|
||||
const destination = path.join(sourceRoot, relative);
|
||||
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
||||
fs.copyFileSync(path.join(repoRoot, relative), destination);
|
||||
}
|
||||
const ajvManifest = require('ajv/package.json');
|
||||
for (const name of ['ajv', ...Object.keys(ajvManifest.dependencies)]) {
|
||||
fs.cpSync(path.dirname(require.resolve(`${name}/package.json`)), path.join(root, 'node_modules', name), { recursive: true });
|
||||
}
|
||||
fs.cpSync(path.join(repoRoot, 'manifests'), path.join(sourceRoot, 'manifests'), { recursive: true });
|
||||
const projectRoot = path.join(root, 'app');
|
||||
const { createManifestInstallPlan } = require('../../scripts/lib/install/plan');
|
||||
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
|
||||
const plan = createManifestInstallPlan({ sourceRoot, moduleIds: ['platform-configs'], target: 'antigravity', projectRoot });
|
||||
applyInstallPlan(plan);
|
||||
fs.rmSync(path.join(root, 'node_modules'), { recursive: true });
|
||||
const run = spawnSync(process.execPath, [path.join(plan.targetRoot, 'scripts/memory-mcp.mjs')], {
|
||||
cwd: root,
|
||||
env: { ...process.env, ECC_MEMORY_HARNESS: 'antigravity', NODE_PATH: '' },
|
||||
input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }) + '\n',
|
||||
encoding: 'utf8',
|
||||
timeout: 10000,
|
||||
});
|
||||
assert.strictEqual(run.status, 0, run.stderr);
|
||||
assert.strictEqual(JSON.parse(run.stdout.trim()).id, 1);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('missing memory dependencies give installation instructions', () => {
|
||||
const root = createTempDir('ecc-missing-memory-dependency-');
|
||||
try {
|
||||
const ajvRoot = path.join(root, 'node_modules', 'ajv');
|
||||
fs.mkdirSync(ajvRoot, { recursive: true });
|
||||
fs.writeFileSync(path.join(ajvRoot, 'package.json'), JSON.stringify({ dependencies: { 'ecc-test-nonexistent-dependency': '1.0.0' } }));
|
||||
const { planAntigravityMemoryRuntime } = require('../../scripts/lib/antigravity-mcp');
|
||||
assert.throws(() => planAntigravityMemoryRuntime('platform-configs', root, path.join(root, 'target')), /Run npm install/);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('Windows hook commands quote spaces and reject shell expansion characters', () => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(process, 'platform');
|
||||
try {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32' });
|
||||
const bridgeScript = path.resolve('folder with spaces/bridge.js');
|
||||
const config = buildAntigravityHooksConfig({ bridgeScript });
|
||||
assert.ok(config['ecc-guard'].PreToolUse[0].hooks[0].command.startsWith(`node "${bridgeScript}" `));
|
||||
for (const character of ['"', '%', '!', '$', '`', '\r', '\n']) {
|
||||
assert.throws(() => buildAntigravityHooksConfig({ bridgeScript: bridgeScript + character }), /shell/);
|
||||
}
|
||||
} finally {
|
||||
Object.defineProperty(process, 'platform', descriptor);
|
||||
}
|
||||
});
|
||||
|
||||
test('antigravity-home adapter resolves root to ~/.gemini/config/plugins/ecc', () => {
|
||||
const homeDir = '/home/testuser';
|
||||
const adapter = getInstallTargetAdapter('antigravity-home');
|
||||
@@ -163,7 +305,6 @@ function runTests() {
|
||||
target: 'antigravity-home',
|
||||
homeDir,
|
||||
projectRoot,
|
||||
enableHooks: true,
|
||||
});
|
||||
|
||||
assert.strictEqual(plan.targetAdapterId, 'antigravity-home');
|
||||
@@ -230,7 +371,7 @@ function runTests() {
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'echo "hello from safe command"',
|
||||
CommandLine: 'pwd',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -269,6 +410,72 @@ function runTests() {
|
||||
assert.match(output.reason, /no-verify/i);
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge returns deny for GateGuard write_to_file on first touch', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const root = createTempDir('ecc-bridge-deny-');
|
||||
try {
|
||||
const targetFile = path.join(root, 'index.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: path.basename(root),
|
||||
workspacePaths: [root],
|
||||
toolCall: {
|
||||
name: 'write_to_file',
|
||||
args: {
|
||||
TargetFile: targetFile,
|
||||
CodeContent: 'console.log("hello");',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:edit-write:gateguard-fact-force'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
GATEGUARD_STATE_DIR: root,
|
||||
GATEGUARD_DISABLED: '0',
|
||||
GATEGUARD_EXEMPT_PATHS: '',
|
||||
GATEGUARD_EXEMPT_GLOBS: '',
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'deny');
|
||||
assert.ok(output.reason);
|
||||
} finally {
|
||||
cleanup(root);
|
||||
}
|
||||
});
|
||||
|
||||
test('antigravity-hook-bridge returns deny for oversized input in pre-tool-use', () => {
|
||||
const bridgePath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'antigravity-hook-bridge.js');
|
||||
const input = JSON.stringify({
|
||||
conversationId: 'test-oversized',
|
||||
workspacePaths: ['/tmp'],
|
||||
toolCall: {
|
||||
name: 'run_command',
|
||||
args: {
|
||||
CommandLine: 'echo ' + 'x'.repeat(100),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const run = spawnSync(process.execPath, [bridgePath, '--mode', 'pre-tool-use', '--hook', 'pre:bash:dispatcher'], {
|
||||
input,
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
ECC_HOOK_INPUT_MAX_BYTES: '10',
|
||||
},
|
||||
});
|
||||
|
||||
assert.strictEqual(run.status, 0);
|
||||
const output = JSON.parse(run.stdout);
|
||||
assert.strictEqual(output.decision, 'deny');
|
||||
assert.match(output.reason, /completely|input/i);
|
||||
});
|
||||
|
||||
test('antigravity-project plans mcp_config.json when platform configs are selected', () => {
|
||||
const projectRoot = createTempDir('antigravity-proj-mcp-');
|
||||
try {
|
||||
@@ -305,7 +512,7 @@ function runTests() {
|
||||
projectRoot: projectDir,
|
||||
}), 'enabled');
|
||||
|
||||
const result = applyInstallPlan(plan);
|
||||
applyInstallPlan(plan);
|
||||
const pluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'ecc');
|
||||
|
||||
assert.ok(fs.existsSync(path.join(pluginDir, 'plugin.json')), 'plugin.json should exist');
|
||||
@@ -326,6 +533,8 @@ function runTests() {
|
||||
|
||||
const mcpConfig = JSON.parse(fs.readFileSync(path.join(pluginDir, 'mcp_config.json'), 'utf8'));
|
||||
assert.ok(mcpConfig.mcpServers['ecc-memory']);
|
||||
const hookCommand = hooksJson['ecc-guard'].PreToolUse[0].hooks[0].command;
|
||||
assert.ok(hookCommand.includes(path.join(pluginDir, 'scripts', 'hooks', 'antigravity-hook-bridge.js')));
|
||||
} finally {
|
||||
cleanup(homeDir);
|
||||
cleanup(projectDir);
|
||||
|
||||
@@ -294,6 +294,8 @@ test('fresh install uses supported Claude arguments and follows the verification
|
||||
[
|
||||
'plugin', 'install', 'ecc@ecc',
|
||||
'--scope', 'project',
|
||||
'--config', 'hooks_enabled=true',
|
||||
'--config', 'hook_profile=strict',
|
||||
],
|
||||
['plugin', 'list', '--json'],
|
||||
]);
|
||||
@@ -324,6 +326,19 @@ test('fresh installs support all Claude scopes while hook preferences stay user-
|
||||
}
|
||||
});
|
||||
|
||||
test('fresh installs pass disabled hooks to the provider before activation', () => {
|
||||
withFixture({}, fixture => {
|
||||
setupClaudePlugin(setupOptions(fixture, { scope: 'user', hooks: 'off' }));
|
||||
const install = readCalls(fixture).find(argv => argv[1] === 'install');
|
||||
assert.deepStrictEqual(install, [
|
||||
'plugin', 'install', 'ecc@ecc', '--scope', 'user',
|
||||
'--config', 'hooks_enabled=false', '--config', 'hook_profile=standard',
|
||||
]);
|
||||
const settings = JSON.parse(fs.readFileSync(fixture.settingsPath, 'utf8'));
|
||||
assert.strictEqual(settings.pluginConfigs['ecc@ecc'].options.hooks_enabled, false);
|
||||
});
|
||||
});
|
||||
|
||||
test('same-scope repeat setup updates ECC and changes durable user hook preferences', () => {
|
||||
withFixture({
|
||||
plugins: [installedPlugin('local')],
|
||||
@@ -722,6 +737,8 @@ test('provider failures stop later operations and leave settings untouched', ()
|
||||
const installArgv = [
|
||||
'plugin', 'install', 'ecc@ecc',
|
||||
'--scope', 'user',
|
||||
'--config', 'hooks_enabled=true',
|
||||
'--config', 'hook_profile=standard',
|
||||
];
|
||||
withFixture({
|
||||
failures: [{
|
||||
|
||||
@@ -280,12 +280,14 @@ function runTests() {
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
'commands-core',
|
||||
'hooks-runtime',
|
||||
'platform-configs',
|
||||
'skill-unified-memory',
|
||||
'workflow-quality'
|
||||
]
|
||||
);
|
||||
assert.ok(plan.skippedModuleIds.includes('hooks-runtime'));
|
||||
assert.ok(!plan.skippedModuleIds.includes('hooks-runtime'));
|
||||
assert.ok(plan.operations.some(operation => operation.destinationPath === path.join(projectRoot, '.agents', 'hooks.json')));
|
||||
assert.ok(!plan.skippedModuleIds.includes('platform-configs'));
|
||||
assert.ok(!plan.skippedModuleIds.includes('workflow-quality'));
|
||||
assert.strictEqual(plan.targetAdapterId, 'antigravity-project');
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const os = require('os');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { adaptAntigravityInputToEcc } = require('../../scripts/hooks/antigravity-hook-bridge');
|
||||
|
||||
const bridgePath = path.resolve(__dirname, '../../scripts/hooks/antigravity-hook-bridge.js');
|
||||
async function invoke({ hook = 'pre:edit-write:gateguard-fact-force', mode = 'pre-tool-use', raw = '{}', truncated = false, result = {}, child, readError = false, hookError = false } = {}) {
|
||||
let output = '';
|
||||
let spawnOptions;
|
||||
let hookCalls = 0;
|
||||
const module = { exports: {} };
|
||||
const run = () => { hookCalls += 1; if (hookError) throw new Error('hook failed'); return result; };
|
||||
const imports = {
|
||||
path,
|
||||
child_process: { spawnSync: (_file, _args, options) => { spawnOptions = options; return child; } },
|
||||
'./bash-hook-dispatcher': { runPreBash: run },
|
||||
'./gateguard-fact-force': { run },
|
||||
'./doc-file-warning': { run },
|
||||
'./post-edit-accumulator': { run },
|
||||
'./stop-format-typecheck': { run },
|
||||
'./hook-input': {
|
||||
resolveMaxStdin: () => 1024,
|
||||
readStdinRaw: async () => { if (readError) throw new Error('read failed'); return { raw, truncated }; },
|
||||
},
|
||||
};
|
||||
const requireStub = name => imports[name];
|
||||
requireStub.main = module;
|
||||
vm.runInNewContext(fs.readFileSync(bridgePath, 'utf8'), {
|
||||
require: requireStub, module, __dirname: path.dirname(bridgePath),
|
||||
process: { argv: ['node', bridgePath, '--mode', mode, '--hook', hook], env: {}, execPath: process.execPath, stdin: {}, stdout: { write: text => { output += text; } } },
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
return { response: JSON.parse(output), spawnOptions, hookCalls };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
for (const [native, expected] of [['run_command', 'Bash'], ['write_to_file', 'Write'], ['replace_file_content', 'Edit'], ['multi_replace_file_content', 'Edit']]) {
|
||||
const input = adaptAntigravityInputToEcc({ toolCall: { name: native, args: { CommandLine: 'echo ok', TargetFile: '/tmp/code.js' } } });
|
||||
assert.strictEqual(input.tool_name, expected);
|
||||
assert.strictEqual(input.tool_input.command, 'echo ok');
|
||||
assert.strictEqual(input.tool_input.file_path, '/tmp/code.js');
|
||||
}
|
||||
const session = adaptAntigravityInputToEcc({ conversationId: 'session-a', workspacePaths: ['/workspace/app'] });
|
||||
assert.strictEqual(session.session_id, 'session-a');
|
||||
assert.strictEqual(session.cwd, '/workspace/app');
|
||||
const denial = { hookSpecificOutput: { permissionDecision: 'deny', permissionDecisionReason: 'Inspect first\nThen retry' } };
|
||||
assert.deepStrictEqual((await invoke({ result: { exitCode: 0, stdout: JSON.stringify(denial) } })).response, { decision: 'deny', reason: 'Inspect first Then retry' });
|
||||
assert.strictEqual((await invoke({ hook: 'pre:bash:dispatcher', result: { exitCode: 0, output: JSON.stringify(denial) } })).response.decision, 'deny');
|
||||
assert.match((await invoke({ hook: 'pre:write:doc-file-warning', result: { exitCode: 0, additionalContext: ['warning one', 'warning two'] } })).response.reason, /warning one.*warning two/);
|
||||
for (const failure of [{ raw: '{' }, { raw: '' }, { raw: 'null' }, { raw: '[]' }, { truncated: true }, { readError: true }, { hookError: true }]) {
|
||||
assert.strictEqual((await invoke(failure)).response.decision, 'deny', JSON.stringify(failure));
|
||||
}
|
||||
for (const child of [{ status: null, error: new Error('timed out') }, { status: 1, stderr: 'failed' }, { status: 2, stderr: 'blocked' }]) {
|
||||
const result = await invoke({ hook: 'pre:config-protection', child });
|
||||
assert.strictEqual(result.response.decision, 'deny');
|
||||
assert.ok(result.spawnOptions.timeout > 0 && result.spawnOptions.timeout <= 10000);
|
||||
}
|
||||
assert.strictEqual((await invoke({ hook: 'pre:config-protection', child: { status: 0, stderr: '' } })).response.decision, 'allow');
|
||||
assert.strictEqual((await invoke({ result: '{}' })).response.decision, 'allow');
|
||||
assert.strictEqual((await invoke({ mode: 'stop', raw: '{' })).response.decision, 'allow');
|
||||
assert.strictEqual((await invoke({ mode: 'post-tool-use', hook: 'post:edit:accumulator' })).hookCalls, 1);
|
||||
assert.strictEqual((await invoke({ mode: 'post-tool-use', hook: 'post:edit:accumulator', raw: JSON.stringify({ error: 'write failed' }) })).hookCalls, 0);
|
||||
assert.deepStrictEqual((await invoke({ mode: 'stop', hook: 'stop:format-typecheck', raw: JSON.stringify({ fullyIdle: false }) })).response, { decision: 'allow' });
|
||||
assert.deepStrictEqual((await invoke({ mode: 'stop', hook: 'stop:format-typecheck', child: { status: 0, stderr: '' } })).response, { decision: 'allow' });
|
||||
for (const hook of ['stop:check-console-log', 'stop:format-typecheck']) {
|
||||
const stop = await invoke({ mode: 'stop', hook, child: { status: 0, stderr: 'Remove console.log' } });
|
||||
assert.deepStrictEqual(stop.response, { decision: 'continue', reason: 'Remove console.log' });
|
||||
}
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-bridge-'));
|
||||
const conversationId = path.basename(root);
|
||||
const accumulator = path.join(os.tmpdir(), `ecc-edited-${conversationId}.txt`);
|
||||
const target = path.join(root, 'component.js');
|
||||
const payload = { conversationId, workspacePaths: [root], toolCall: { name: 'multi_replace_file_content', args: { TargetFile: target } } };
|
||||
const cli = (mode, hook, input = payload, extraEnv = {}) => {
|
||||
const child = spawnSync(process.execPath, [bridgePath, '--mode', mode, '--hook', hook], {
|
||||
input: JSON.stringify(input), encoding: 'utf8',
|
||||
env: { ...process.env, GATEGUARD_STATE_DIR: root, GATEGUARD_DISABLED: '0', GATEGUARD_EXEMPT_PATHS: '', ...extraEnv },
|
||||
});
|
||||
assert.strictEqual(child.status, 0, child.stderr);
|
||||
return JSON.parse(child.stdout);
|
||||
};
|
||||
try {
|
||||
assert.strictEqual(cli('pre-tool-use', 'pre:edit-write:gateguard-fact-force').decision, 'deny');
|
||||
const warning = cli('pre-tool-use', 'pre:write:doc-file-warning', { toolCall: { name: 'write_to_file', args: { TargetFile: path.join(root, 'NOTES.md') } } });
|
||||
assert.match(warning.reason, /Ad-hoc documentation/);
|
||||
assert.strictEqual(cli('pre-tool-use', 'pre:config-protection', payload, { ECC_HOOK_INPUT_MAX_BYTES: '2' }).decision, 'deny');
|
||||
cli('post-tool-use', 'post:edit:accumulator');
|
||||
assert.strictEqual(fs.readFileSync(accumulator, 'utf8').trim(), target);
|
||||
cli('stop', 'stop:format-typecheck', { conversationId });
|
||||
assert.ok(!fs.existsSync(accumulator) || fs.readFileSync(accumulator, 'utf8') === '');
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
fs.rmSync(accumulator, { force: true });
|
||||
}
|
||||
console.log('antigravity-hook-bridge regression checks passed');
|
||||
}
|
||||
main().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -891,7 +891,7 @@ function runTests() {
|
||||
const projectDir = createTempDir('install-apply-project-');
|
||||
|
||||
try {
|
||||
const result = run(['--target', 'antigravity', '--profile', 'core'], { cwd: projectDir, homeDir });
|
||||
const result = run(['--target', 'antigravity', '--profile', 'core', '--enable-hooks'], { cwd: projectDir, homeDir });
|
||||
assert.strictEqual(result.code, 0, result.stderr);
|
||||
|
||||
assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'rules', 'common-coding-style.md')));
|
||||
@@ -902,6 +902,7 @@ function runTests() {
|
||||
assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'agents', 'architect.md')));
|
||||
assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'workflows', 'plan.md')));
|
||||
assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'skills', 'tdd-workflow', 'SKILL.md')));
|
||||
assert.ok(fs.existsSync(path.join(projectDir, '.agents', 'hooks.json')), 'hooks.json should exist');
|
||||
|
||||
const state = readJson(path.join(projectDir, '.agents', 'ecc-install-state.json'));
|
||||
assert.strictEqual(state.request.profile, 'core');
|
||||
@@ -912,12 +913,13 @@ function runTests() {
|
||||
'rules-core',
|
||||
'agents-core',
|
||||
'commands-core',
|
||||
'hooks-runtime',
|
||||
'platform-configs',
|
||||
'skill-unified-memory',
|
||||
'workflow-quality'
|
||||
]
|
||||
);
|
||||
assert.ok(state.resolution.skippedModules.includes('hooks-runtime'));
|
||||
assert.ok(!state.resolution.skippedModules.includes('hooks-runtime'));
|
||||
assert.ok(!state.resolution.skippedModules.includes('workflow-quality'));
|
||||
assert.ok(!state.resolution.skippedModules.includes('platform-configs'));
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user