feat: initial commit for Paralax creative engineering system
This commit is contained in:
121
.agents/hooks/README.md
Normal file
121
.agents/hooks/README.md
Normal file
@@ -0,0 +1,121 @@
|
||||
# AG Kit — Antigravity Native Integration
|
||||
|
||||
AG Kit now treats Google Antigravity as its primary runtime. The integration is intentionally built from Antigravity's workspace-native conventions instead of a cross-runtime abstraction.
|
||||
|
||||
## What is active
|
||||
|
||||
| Phase | Native surface | AG Kit implementation |
|
||||
| --- | --- | --- |
|
||||
| 1. Discovery | `.agents/rules/`, `.agents/skills/`, `.agents/workflows/` | Doctor validates discovery paths and required frontmatter |
|
||||
| 2. MCP | `.agents/mcp_config.json` | Workspace validation plus explicit, backup-aware sync helper |
|
||||
| 3. Hooks | `.agents/hooks.json` | `PreToolUse` gate for clearly destructive `run_command` calls |
|
||||
| 4. Orchestration | workflows, specialist definitions, Antigravity subagents | Validates `/coordinate`, `/orchestrate`, core roles, and routing skills |
|
||||
| 5. Plugin | Antigravity CLI plugin import | Deterministic local plugin bundle builder |
|
||||
| 6. Validation | CI and smoke tests | Doctor, hook regression tests, MCP tests, and plugin build tests |
|
||||
|
||||
## Quick verification
|
||||
|
||||
```bash
|
||||
node .agents/hooks/antigravity-doctor.mjs
|
||||
node --test .agents/hooks/tests/antigravity.test.mjs
|
||||
```
|
||||
|
||||
The doctor checks the installed workspace without changing files. Use `--json` for machine-readable output and `--strict` to treat unresolved configuration placeholders as failures.
|
||||
|
||||
## Native safety hook
|
||||
|
||||
Antigravity reads `.agents/hooks.json`. AG Kit registers one native hook:
|
||||
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "run_command",
|
||||
"command": "node .agents/hooks/validate-tool-call.mjs",
|
||||
"timeout": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The policy blocks only high-confidence destructive operations such as deleting a filesystem root, formatting a drive, or overwriting a raw disk. It deliberately allows normal cleanup such as deleting `dist/` or `node_modules/`.
|
||||
|
||||
The hook is not a sandbox and does not replace Antigravity's permission settings. Invalid or unknown payload shapes fail open with a warning to prevent a runtime-wide lockout after upstream payload changes.
|
||||
|
||||
## MCP setup
|
||||
|
||||
Antigravity CLI supports workspace MCP configuration at `.agents/mcp_config.json`. Antigravity IDE and the wider suite may also use a shared global configuration.
|
||||
|
||||
Inspect the merge plan:
|
||||
|
||||
```bash
|
||||
node .agents/hooks/sync-mcp.mjs --check
|
||||
node .agents/hooks/sync-mcp.mjs --print
|
||||
```
|
||||
|
||||
Apply only after replacing placeholders such as `YOUR_API_KEY`:
|
||||
|
||||
```bash
|
||||
node .agents/hooks/sync-mcp.mjs --apply --target suite
|
||||
node .agents/hooks/sync-mcp.mjs --apply --target cli
|
||||
```
|
||||
|
||||
The helper never overwrites an existing server with the same name unless `--force` is supplied. It creates a timestamped backup before writing.
|
||||
|
||||
## Orchestration
|
||||
|
||||
AG Kit uses the existing Antigravity-native workflows:
|
||||
|
||||
- `/coordinate` for parallel read/research and synthesis;
|
||||
- `/orchestrate` for plan approval followed by specialist implementation;
|
||||
- `.agents/agent/*.md` as role definitions;
|
||||
- `coordinator-mode`, `parallel-agents`, `intelligent-routing`, and `verify-changes` as orchestration skills.
|
||||
|
||||
Antigravity's `/agents` and `/tasks` views remain the runtime source of truth for active work. AG Kit does not create a second scheduler.
|
||||
|
||||
## Build a plugin bundle
|
||||
|
||||
```bash
|
||||
node .agents/hooks/build-plugin.mjs
|
||||
# or
|
||||
npm run build:antigravity-plugin
|
||||
```
|
||||
|
||||
The generated `dist/antigravity-plugin/` contains:
|
||||
|
||||
- a `gemini-extension.json` compatible manifest used by Antigravity CLI's plugin importer;
|
||||
- packaged skills and specialist definitions;
|
||||
- workflows converted into namespaced command TOML files;
|
||||
- rules, native hooks, and an MCP example;
|
||||
- `PLUGIN_CONTENTS.json` with deterministic SHA-256 inventory data.
|
||||
|
||||
Install the local build after reviewing it:
|
||||
|
||||
```bash
|
||||
agy plugin install ./dist/antigravity-plugin
|
||||
agy plugin list
|
||||
```
|
||||
|
||||
## Security boundaries
|
||||
|
||||
- No MCP configuration is copied to the home directory without explicit `--apply`.
|
||||
- Placeholder credentials block MCP application.
|
||||
- The plugin builder does not include secrets from environment variables or home-directory configuration.
|
||||
- The hook only reads one tool payload from stdin and performs no network calls.
|
||||
- AG Kit does not weaken Antigravity permission prompts or workspace trust controls.
|
||||
|
||||
## Release and operations
|
||||
|
||||
- [Root README](../../README.md) — installation and production quick start.
|
||||
- [Migration guide](../../MIGRATION.md) — upgrade and rollback from earlier AG Kit versions.
|
||||
- [Production checklist](../../PRODUCTION_CHECKLIST.md) — automated and hands-on release gates.
|
||||
- [Security policy](../../SECURITY.md) — threat model, incident handling, and hook recovery.
|
||||
|
||||
## Primary Antigravity references
|
||||
|
||||
- Workspace rules and workflows: <https://codelabs.developers.google.com/antigravity-ide>
|
||||
- Workspace skills: <https://codelabs.developers.google.com/antigravity-skills>
|
||||
- Workspace MCP: <https://codelabs.developers.google.com/antigravity-cli>
|
||||
- Native `PreToolUse` hooks: <https://codelabs.developers.google.com/secure-agentic-coding>
|
||||
- Plugin installation: <https://codelabs.developers.google.com/antigravity-cli-plugins> and <https://codelabs.developers.google.com/antigravity-conductor>
|
||||
20
.agents/hooks/antigravity-contract.schema.json
Normal file
20
.agents/hooks/antigravity-contract.schema.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://ag-kit.dev/schemas/antigravity-contract.schema.json",
|
||||
"title": "AG Kit Antigravity Runtime Contract",
|
||||
"type": "object",
|
||||
"required": ["schemaVersion", "runtime", "requiredCliCommands", "phases"],
|
||||
"properties": {
|
||||
"$schema": {"type": "string"},
|
||||
"schemaVersion": {"const": "1.0.0"},
|
||||
"runtime": {"const": "antigravity"},
|
||||
"requiredCliCommands": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"uniqueItems": true,
|
||||
"items": {"enum": ["changelog", "plugin", "plugins", "update"]}
|
||||
},
|
||||
"phases": {"type": "object"}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
281
.agents/hooks/antigravity-doctor.mjs
Normal file
281
.agents/hooks/antigravity-doctor.mjs
Normal file
@@ -0,0 +1,281 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {root: process.cwd(), json: false, strict: false};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--root') options.root = path.resolve(argv[++i]);
|
||||
else if (arg === '--json') options.json = true;
|
||||
else if (arg === '--strict') options.strict = true;
|
||||
else if (arg === '--help') options.help = true;
|
||||
else throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function readJson(file) {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
function frontmatter(file) {
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
if (!text.startsWith('---\n')) return null;
|
||||
const end = text.indexOf('\n---\n', 4);
|
||||
if (end < 0) return null;
|
||||
const data = {};
|
||||
for (const line of text.slice(4, end).split(/\r?\n/)) {
|
||||
const match = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
|
||||
if (!match) continue;
|
||||
data[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, '');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function markdownFiles(dir) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs.readdirSync(dir)
|
||||
.filter(name => name.endsWith('.md'))
|
||||
.map(name => path.join(dir, name))
|
||||
.sort();
|
||||
}
|
||||
|
||||
function skillFiles(dir) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs.readdirSync(dir, {withFileTypes: true})
|
||||
.filter(entry => entry.isDirectory())
|
||||
.map(entry => path.join(dir, entry.name, 'SKILL.md'))
|
||||
.filter(file => fs.existsSync(file))
|
||||
.sort();
|
||||
}
|
||||
|
||||
function add(report, severity, phase, code, file, message) {
|
||||
report.findings.push({severity, phase, code, file, message});
|
||||
}
|
||||
|
||||
function relative(root, file) {
|
||||
return path.relative(root, file).split(path.sep).join('/');
|
||||
}
|
||||
|
||||
function checkDiscovery(root, report) {
|
||||
const agentsRoot = path.join(root, '.agents');
|
||||
const groups = [
|
||||
['rules', markdownFiles(path.join(agentsRoot, 'rules')), ['trigger']],
|
||||
['workflows', markdownFiles(path.join(agentsRoot, 'workflows')), ['description']],
|
||||
['skills', skillFiles(path.join(agentsRoot, 'skills')), ['description']]
|
||||
];
|
||||
|
||||
for (const [kind, files, required] of groups) {
|
||||
report.counts[kind] = files.length;
|
||||
if (files.length === 0) {
|
||||
add(report, 'error', 'discovery', `${kind}.missing`, `.agents/${kind}`, `No Antigravity ${kind} were discovered.`);
|
||||
continue;
|
||||
}
|
||||
for (const file of files) {
|
||||
const meta = frontmatter(file);
|
||||
if (!meta) {
|
||||
add(report, 'error', 'discovery', `${kind}.frontmatter`, relative(root, file), 'Missing YAML frontmatter.');
|
||||
continue;
|
||||
}
|
||||
for (const field of required) {
|
||||
if (!meta[field]) add(report, 'error', 'discovery', `${kind}.required`, relative(root, file), `Missing frontmatter field: ${field}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function walkStrings(value, callback) {
|
||||
if (typeof value === 'string') callback(value);
|
||||
else if (Array.isArray(value)) value.forEach(item => walkStrings(item, callback));
|
||||
else if (value && typeof value === 'object') Object.values(value).forEach(item => walkStrings(item, callback));
|
||||
}
|
||||
|
||||
function checkMcp(root, report) {
|
||||
const file = path.join(root, '.agents', 'mcp_config.json');
|
||||
if (!fs.existsSync(file)) {
|
||||
add(report, 'error', 'mcp', 'mcp.missing', '.agents/mcp_config.json', 'Workspace MCP configuration is missing.');
|
||||
return;
|
||||
}
|
||||
let config;
|
||||
try {
|
||||
config = readJson(file);
|
||||
} catch (error) {
|
||||
add(report, 'error', 'mcp', 'mcp.invalid_json', '.agents/mcp_config.json', error.message);
|
||||
return;
|
||||
}
|
||||
if (!config.mcpServers || typeof config.mcpServers !== 'object' || Array.isArray(config.mcpServers)) {
|
||||
add(report, 'error', 'mcp', 'mcp.servers', '.agents/mcp_config.json', 'mcpServers must be an object.');
|
||||
return;
|
||||
}
|
||||
report.counts.mcpServers = Object.keys(config.mcpServers).length;
|
||||
for (const [name, server] of Object.entries(config.mcpServers)) {
|
||||
const valid = server && typeof server === 'object' && (
|
||||
typeof server.command === 'string' || typeof server.serverURL === 'string' || typeof server.url === 'string'
|
||||
);
|
||||
if (!valid) add(report, 'error', 'mcp', 'mcp.server_shape', `.agents/mcp_config.json#${name}`, 'Server needs command, serverURL, or url.');
|
||||
walkStrings(server, value => {
|
||||
if (/YOUR_[A-Z0-9_]+|CHANGE_ME|<[^>]+>/.test(value)) {
|
||||
add(report, 'warning', 'mcp', 'mcp.placeholder', `.agents/mcp_config.json#${name}`, 'Server contains an unresolved placeholder; configure it before enabling the server.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function localCommandPath(command) {
|
||||
const match = command.match(/(?:^|\s)(\.agents[/\\][^\s"']+)/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
function checkHooks(root, report) {
|
||||
const file = path.join(root, '.agents', 'hooks.json');
|
||||
if (!fs.existsSync(file)) {
|
||||
add(report, 'error', 'hooks', 'hooks.missing', '.agents/hooks.json', 'Native Antigravity hooks configuration is missing.');
|
||||
return;
|
||||
}
|
||||
let config;
|
||||
try {
|
||||
config = readJson(file);
|
||||
} catch (error) {
|
||||
add(report, 'error', 'hooks', 'hooks.invalid_json', '.agents/hooks.json', error.message);
|
||||
return;
|
||||
}
|
||||
if (typeof config.enabled !== 'boolean') add(report, 'error', 'hooks', 'hooks.enabled', '.agents/hooks.json', 'enabled must be boolean.');
|
||||
const events = ['PreToolUse', 'PostToolUse', 'PreInvocation', 'PostInvocation', 'Stop'];
|
||||
let total = 0;
|
||||
for (const event of events) {
|
||||
if (config[event] === undefined) continue;
|
||||
if (!Array.isArray(config[event])) {
|
||||
add(report, 'error', 'hooks', 'hooks.event_shape', `.agents/hooks.json#${event}`, `${event} must be an array.`);
|
||||
continue;
|
||||
}
|
||||
for (const [index, hook] of config[event].entries()) {
|
||||
total += 1;
|
||||
const ref = `.agents/hooks.json#${event}[${index}]`;
|
||||
if (!hook || typeof hook !== 'object') {
|
||||
add(report, 'error', 'hooks', 'hooks.hook_shape', ref, 'Hook must be an object.');
|
||||
continue;
|
||||
}
|
||||
if (typeof hook.matcher !== 'string' || !hook.matcher.trim()) add(report, 'error', 'hooks', 'hooks.matcher', ref, 'matcher is required.');
|
||||
if (typeof hook.command !== 'string' || !hook.command.trim()) add(report, 'error', 'hooks', 'hooks.command', ref, 'command is required.');
|
||||
if (!Number.isInteger(hook.timeout) || hook.timeout < 1 || hook.timeout > 300) add(report, 'error', 'hooks', 'hooks.timeout', ref, 'timeout must be an integer from 1 to 300 seconds.');
|
||||
const localPath = typeof hook.command === 'string' ? localCommandPath(hook.command) : null;
|
||||
if (localPath && !fs.existsSync(path.join(root, localPath))) add(report, 'error', 'hooks', 'hooks.command_missing', ref, `Local hook target does not exist: ${localPath}`);
|
||||
}
|
||||
}
|
||||
report.counts.hooks = total;
|
||||
if (total === 0) add(report, 'warning', 'hooks', 'hooks.empty', '.agents/hooks.json', 'No native hooks are registered.');
|
||||
}
|
||||
|
||||
function checkOrchestration(root, report, contract) {
|
||||
const cfg = contract?.phases?.orchestration ?? {};
|
||||
const groups = [
|
||||
['workflow', cfg.workflows ?? [], name => path.join(root, '.agents', 'workflows', `${name}.md`)],
|
||||
['agent', cfg.agents ?? [], name => path.join(root, '.agents', 'agent', `${name}.md`)],
|
||||
['skill', cfg.skills ?? [], name => path.join(root, '.agents', 'skills', name, 'SKILL.md')]
|
||||
];
|
||||
for (const [kind, names, resolve] of groups) {
|
||||
for (const name of names) {
|
||||
const file = resolve(name);
|
||||
if (!fs.existsSync(file)) add(report, 'error', 'orchestration', `orchestration.${kind}_missing`, relative(root, file), `Required Antigravity ${kind} is missing.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkPlugin(root, report) {
|
||||
const files = [
|
||||
'.agents/hooks/build-plugin.mjs',
|
||||
'.agents/hooks/plugin/GEMINI.md',
|
||||
'.agents/hooks/plugin/gemini-extension.template.json'
|
||||
];
|
||||
for (const file of files) {
|
||||
if (!fs.existsSync(path.join(root, file))) add(report, 'error', 'plugin', 'plugin.file_missing', file, 'Plugin packaging input is missing.');
|
||||
}
|
||||
}
|
||||
|
||||
function checkValidation(root, report) {
|
||||
const requiredFiles = [
|
||||
'.agents/hooks/tests/antigravity.test.mjs',
|
||||
'MIGRATION.md',
|
||||
'SECURITY.md'
|
||||
];
|
||||
for (const file of requiredFiles) {
|
||||
if (!fs.existsSync(path.join(root, file))) add(report, 'error', 'validation', 'validation.file_missing', file, 'Production validation or operator documentation is missing.');
|
||||
}
|
||||
|
||||
const versionFiles = [
|
||||
['.agents/VERSION', value => value.trim()],
|
||||
['package.json', value => JSON.parse(value).version],
|
||||
['cli/package.json', value => JSON.parse(value).version],
|
||||
['web/package.json', value => JSON.parse(value).version]
|
||||
];
|
||||
const versions = [];
|
||||
for (const [file, parse] of versionFiles) {
|
||||
const target = path.join(root, file);
|
||||
if (!fs.existsSync(target)) {
|
||||
add(report, 'error', 'validation', 'validation.version_missing', file, 'Version source is missing.');
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
versions.push([file, parse(fs.readFileSync(target, 'utf8'))]);
|
||||
} catch (error) {
|
||||
add(report, 'error', 'validation', 'validation.version_invalid', file, error.message);
|
||||
}
|
||||
}
|
||||
const unique = new Set(versions.map(([, value]) => value));
|
||||
if (unique.size > 1) add(report, 'error', 'validation', 'validation.version_mismatch', 'VERSION', `Release versions are not synchronized: ${versions.map(([file, value]) => `${file}=${value}`).join(', ')}`);
|
||||
report.counts.releaseVersions = Object.fromEntries(versions);
|
||||
}
|
||||
|
||||
export function diagnose(root) {
|
||||
const report = {runtime: 'antigravity', root, passed: true, counts: {}, phases: {}, findings: []};
|
||||
const contractFile = path.join(root, '.agents', 'antigravity.json');
|
||||
let contract;
|
||||
try {
|
||||
contract = readJson(contractFile);
|
||||
if (contract.runtime !== 'antigravity') add(report, 'error', 'discovery', 'contract.runtime', '.agents/antigravity.json', 'runtime must be antigravity.');
|
||||
} catch (error) {
|
||||
add(report, 'error', 'discovery', 'contract.invalid', '.agents/antigravity.json', error.message);
|
||||
}
|
||||
|
||||
checkDiscovery(root, report);
|
||||
checkMcp(root, report);
|
||||
checkHooks(root, report);
|
||||
checkOrchestration(root, report, contract);
|
||||
checkPlugin(root, report);
|
||||
checkValidation(root, report);
|
||||
|
||||
for (const phase of ['discovery', 'mcp', 'hooks', 'orchestration', 'plugin', 'validation']) {
|
||||
report.phases[phase] = !report.findings.some(item => item.phase === phase && item.severity === 'error');
|
||||
}
|
||||
report.passed = !report.findings.some(item => item.severity === 'error');
|
||||
return report;
|
||||
}
|
||||
|
||||
function printHuman(report) {
|
||||
console.log(`AG Kit Antigravity doctor: ${report.root}`);
|
||||
for (const [phase, passed] of Object.entries(report.phases)) console.log(`${passed ? '[PASS]' : '[FAIL]'} ${phase}`);
|
||||
for (const item of report.findings) console.log(`[${item.severity.toUpperCase()}] ${item.file} ${item.code} - ${item.message}`);
|
||||
console.log(`Counts: ${JSON.stringify(report.counts)}`);
|
||||
console.log(report.passed ? '[PASS] Antigravity contract is ready.' : '[FAIL] Antigravity contract has blocking findings.');
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
try {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
console.log('Usage: node .agents/hooks/antigravity-doctor.mjs [--root PATH] [--json] [--strict]');
|
||||
process.exit(0);
|
||||
}
|
||||
const report = diagnose(options.root);
|
||||
if (options.json) console.log(JSON.stringify(report, null, 2));
|
||||
else printHuman(report);
|
||||
const hasWarnings = report.findings.some(item => item.severity === 'warning');
|
||||
process.exitCode = report.passed && !(options.strict && hasWarnings) ? 0 : 1;
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 2;
|
||||
}
|
||||
}
|
||||
44
.agents/hooks/antigravity-hooks.schema.json
Normal file
44
.agents/hooks/antigravity-hooks.schema.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://ag-kit.dev/schemas/antigravity-hooks.schema.json",
|
||||
"title": "AG Kit Antigravity Native Hooks",
|
||||
"type": "object",
|
||||
"required": ["enabled"],
|
||||
"properties": {
|
||||
"$schema": {"type": "string"},
|
||||
"enabled": {"type": "boolean"},
|
||||
"PreToolUse": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/$defs/hook"}
|
||||
},
|
||||
"PostToolUse": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/$defs/hook"}
|
||||
},
|
||||
"PreInvocation": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/$defs/hook"}
|
||||
},
|
||||
"PostInvocation": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/$defs/hook"}
|
||||
},
|
||||
"Stop": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/$defs/hook"}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"hook": {
|
||||
"type": "object",
|
||||
"required": ["matcher", "command", "timeout"],
|
||||
"properties": {
|
||||
"matcher": {"type": "string", "minLength": 1},
|
||||
"command": {"type": "string", "minLength": 1},
|
||||
"timeout": {"type": "integer", "minimum": 1, "maximum": 300}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
130
.agents/hooks/build-plugin.mjs
Normal file
130
.agents/hooks/build-plugin.mjs
Normal file
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {root: process.cwd(), output: null};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
if (argv[i] === '--root') options.root = path.resolve(argv[++i]);
|
||||
else if (argv[i] === '--output') options.output = path.resolve(argv[++i]);
|
||||
else throw new Error(`Unknown argument: ${argv[i]}`);
|
||||
}
|
||||
options.output ??= path.join(options.root, 'dist', 'antigravity-plugin');
|
||||
return options;
|
||||
}
|
||||
|
||||
function copyTree(source, destination) {
|
||||
if (!fs.existsSync(source)) return 0;
|
||||
fs.cpSync(source, destination, {recursive: true});
|
||||
let count = 0;
|
||||
const visit = dir => {
|
||||
for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) visit(full);
|
||||
else count += 1;
|
||||
}
|
||||
};
|
||||
visit(source);
|
||||
return count;
|
||||
}
|
||||
|
||||
function frontmatterDescription(text) {
|
||||
if (!text.startsWith('---\n')) return '';
|
||||
const end = text.indexOf('\n---\n', 4);
|
||||
if (end < 0) return '';
|
||||
const line = text.slice(4, end).split(/\r?\n/).find(item => item.startsWith('description:'));
|
||||
return line ? line.slice('description:'.length).trim().replace(/^['"]|['"]$/g, '') : '';
|
||||
}
|
||||
|
||||
function tomlString(value) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function tomlMultiline(value) {
|
||||
return `'''\n${value.replace(/'''/g, "'\\''")}\n'''`;
|
||||
}
|
||||
|
||||
function convertWorkflows(root, output) {
|
||||
const source = path.join(root, '.agents', 'workflows');
|
||||
const destination = path.join(output, 'commands', 'ag-kit');
|
||||
fs.mkdirSync(destination, {recursive: true});
|
||||
let count = 0;
|
||||
for (const name of fs.readdirSync(source).filter(item => item.endsWith('.md')).sort()) {
|
||||
const text = fs.readFileSync(path.join(source, name), 'utf8');
|
||||
const commandName = name.replace(/\.md$/, '');
|
||||
const description = frontmatterDescription(text) || `Run AG Kit workflow ${commandName}`;
|
||||
const prompt = `${text}\n\nUser arguments: {{args}}`;
|
||||
fs.writeFileSync(
|
||||
path.join(destination, `${commandName}.toml`),
|
||||
`description = ${tomlString(description)}\nprompt = ${tomlMultiline(prompt)}\n`,
|
||||
'utf8'
|
||||
);
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function sha256(file) {
|
||||
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
function inventory(output) {
|
||||
const files = [];
|
||||
const visit = dir => {
|
||||
for (const entry of fs.readdirSync(dir, {withFileTypes: true}).sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) visit(full);
|
||||
else files.push({path: path.relative(output, full).split(path.sep).join('/'), sha256: sha256(full)});
|
||||
}
|
||||
};
|
||||
visit(output);
|
||||
return files;
|
||||
}
|
||||
|
||||
export function buildPlugin(root, output) {
|
||||
fs.rmSync(output, {recursive: true, force: true});
|
||||
fs.mkdirSync(output, {recursive: true});
|
||||
|
||||
const version = fs.readFileSync(path.join(root, '.agents', 'VERSION'), 'utf8').trim();
|
||||
const template = JSON.parse(fs.readFileSync(path.join(root, '.agents', 'hooks', 'plugin', 'gemini-extension.template.json'), 'utf8'));
|
||||
template.version = version;
|
||||
fs.writeFileSync(path.join(output, 'gemini-extension.json'), `${JSON.stringify(template, null, 2)}\n`, 'utf8');
|
||||
fs.copyFileSync(path.join(root, '.agents', 'hooks', 'plugin', 'GEMINI.md'), path.join(output, 'GEMINI.md'));
|
||||
|
||||
const counts = {
|
||||
skills: copyTree(path.join(root, '.agents', 'skills'), path.join(output, 'skills')),
|
||||
agents: copyTree(path.join(root, '.agents', 'agent'), path.join(output, 'agents')),
|
||||
rules: copyTree(path.join(root, '.agents', 'rules'), path.join(output, 'rules')),
|
||||
workflows: convertWorkflows(root, output)
|
||||
};
|
||||
|
||||
fs.mkdirSync(path.join(output, 'hooks'), {recursive: true});
|
||||
fs.copyFileSync(path.join(root, '.agents', 'hooks.json'), path.join(output, 'hooks', 'hooks.json'));
|
||||
fs.copyFileSync(path.join(root, '.agents', 'hooks', 'validate-tool-call.mjs'), path.join(output, 'hooks', 'validate-tool-call.mjs'));
|
||||
fs.copyFileSync(path.join(root, '.agents', 'mcp_config.json'), path.join(output, 'mcp_config.example.json'));
|
||||
|
||||
const manifest = {
|
||||
name: 'ag-kit',
|
||||
version,
|
||||
runtime: 'antigravity',
|
||||
counts,
|
||||
files: inventory(output)
|
||||
};
|
||||
fs.writeFileSync(path.join(output, 'PLUGIN_CONTENTS.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
||||
return manifest;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
try {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const manifest = buildPlugin(options.root, options.output);
|
||||
console.log(`Built Antigravity plugin: ${options.output}`);
|
||||
console.log(JSON.stringify(manifest.counts));
|
||||
} catch (error) {
|
||||
console.error(`Plugin build failed: ${error.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
13
.agents/hooks/plugin/GEMINI.md
Normal file
13
.agents/hooks/plugin/GEMINI.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# AG Kit for Google Antigravity
|
||||
|
||||
Use the packaged AG Kit components as follows:
|
||||
|
||||
1. Treat `rules/` as persistent engineering constraints.
|
||||
2. Discover `skills/*/SKILL.md` progressively and load only relevant skills.
|
||||
3. Use `commands/ag-kit/` for repeatable slash-command workflows.
|
||||
4. Use `agents/` as specialist role definitions when delegating with Antigravity subagents.
|
||||
5. Preserve user approval checkpoints in planning, deployment, destructive operations, and security-sensitive work.
|
||||
6. The bundled MCP file is an example only. Never activate placeholder credentials.
|
||||
7. The bundled `PreToolUse` hook blocks only clearly destructive root-disk operations and does not replace Antigravity's native permission controls.
|
||||
|
||||
Prefer the `orchestrate` or `coordinate` command for complex multi-domain work. Use at least three independent specialists only when their tasks can be separated cleanly, then synthesize and verify the result.
|
||||
6
.agents/hooks/plugin/gemini-extension.template.json
Normal file
6
.agents/hooks/plugin/gemini-extension.template.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "ag-kit",
|
||||
"version": "0.0.0",
|
||||
"description": "Antigravity-first agent engineering kit with rules, skills, workflows, orchestration, MCP guidance, and safety hooks.",
|
||||
"contextFileName": "GEMINI.md"
|
||||
}
|
||||
101
.agents/hooks/sync-mcp.mjs
Executable file
101
.agents/hooks/sync-mcp.mjs
Executable file
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {root: process.cwd(), apply: false, print: false, force: false, target: 'suite'};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--root') options.root = path.resolve(argv[++i]);
|
||||
else if (arg === '--apply') options.apply = true;
|
||||
else if (arg === '--print') options.print = true;
|
||||
else if (arg === '--force') options.force = true;
|
||||
else if (arg === '--target') options.target = argv[++i];
|
||||
else if (arg === '--check') { /* default */ }
|
||||
else throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
if (!['suite', 'cli'].includes(options.target)) throw new Error('--target must be suite or cli');
|
||||
return options;
|
||||
}
|
||||
|
||||
function readJson(file, fallback = null) {
|
||||
if (!fs.existsSync(file)) return fallback;
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
function containsPlaceholder(value) {
|
||||
let found = false;
|
||||
const walk = item => {
|
||||
if (typeof item === 'string' && /YOUR_[A-Z0-9_]+|CHANGE_ME|<[^>]+>/.test(item)) found = true;
|
||||
else if (Array.isArray(item)) item.forEach(walk);
|
||||
else if (item && typeof item === 'object') Object.values(item).forEach(walk);
|
||||
};
|
||||
walk(value);
|
||||
return found;
|
||||
}
|
||||
|
||||
function mergeServers(existing, workspace, force) {
|
||||
const result = structuredClone(existing ?? {mcpServers: {}});
|
||||
if (!result.mcpServers || typeof result.mcpServers !== 'object') result.mcpServers = {};
|
||||
const conflicts = [];
|
||||
for (const [name, server] of Object.entries(workspace.mcpServers ?? {})) {
|
||||
if (Object.hasOwn(result.mcpServers, name) && !force) {
|
||||
conflicts.push(name);
|
||||
continue;
|
||||
}
|
||||
result.mcpServers[name] = server;
|
||||
}
|
||||
return {result, conflicts};
|
||||
}
|
||||
|
||||
function targetPath(target) {
|
||||
return target === 'suite'
|
||||
? path.join(os.homedir(), '.gemini', 'config', 'mcp_config.json')
|
||||
: path.join(os.homedir(), '.gemini', 'antigravity-cli', 'mcp_config.json');
|
||||
}
|
||||
|
||||
function backup(file) {
|
||||
if (!fs.existsSync(file)) return null;
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const backupFile = `${file}.ag-kit-backup-${stamp}`;
|
||||
fs.copyFileSync(file, backupFile);
|
||||
return backupFile;
|
||||
}
|
||||
|
||||
export function planSync({root, target = 'suite', force = false}) {
|
||||
const source = path.join(root, '.agents', 'mcp_config.json');
|
||||
const workspace = readJson(source);
|
||||
if (!workspace || typeof workspace.mcpServers !== 'object') throw new Error('Invalid workspace .agents/mcp_config.json');
|
||||
const destination = targetPath(target);
|
||||
const existing = readJson(destination, {mcpServers: {}});
|
||||
const {result, conflicts} = mergeServers(existing, workspace, force);
|
||||
return {source, destination, workspace, merged: result, conflicts, placeholders: containsPlaceholder(workspace)};
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
try {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const plan = planSync(options);
|
||||
console.log(`Source: ${plan.source}`);
|
||||
console.log(`Target: ${plan.destination}`);
|
||||
console.log(`Servers: ${Object.keys(plan.workspace.mcpServers).join(', ') || '(none)'}`);
|
||||
if (plan.conflicts.length) console.log(`Conflicts kept unchanged: ${plan.conflicts.join(', ')}`);
|
||||
if (plan.placeholders) console.log('Warning: unresolved placeholders detected; --apply is blocked until they are configured.');
|
||||
if (options.print) console.log(JSON.stringify(plan.merged, null, 2));
|
||||
if (options.apply) {
|
||||
if (plan.placeholders) throw new Error('Refusing to apply MCP configuration with unresolved placeholders.');
|
||||
fs.mkdirSync(path.dirname(plan.destination), {recursive: true});
|
||||
const backupFile = backup(plan.destination);
|
||||
fs.writeFileSync(plan.destination, `${JSON.stringify(plan.merged, null, 2)}\n`, 'utf8');
|
||||
console.log(`Applied MCP configuration.${backupFile ? ` Backup: ${backupFile}` : ''}`);
|
||||
} else {
|
||||
console.log('Check only. Use --apply after reviewing the plan.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`MCP sync failed: ${error.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
80
.agents/hooks/tests/antigravity.test.mjs
Normal file
80
.agents/hooks/tests/antigravity.test.mjs
Normal file
@@ -0,0 +1,80 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import test from 'node:test';
|
||||
|
||||
import {diagnose} from '../antigravity-doctor.mjs';
|
||||
import {buildPlugin} from '../build-plugin.mjs';
|
||||
import {evaluateCommand, extractCommand} from '../validate-tool-call.mjs';
|
||||
import {planSync} from '../sync-mcp.mjs';
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '../../..');
|
||||
|
||||
test('extracts Antigravity CommandLine payload', () => {
|
||||
assert.equal(extractCommand({tool_args: {CommandLine: 'npm test'}}), 'npm test');
|
||||
});
|
||||
|
||||
test('allows normal project cleanup', () => {
|
||||
assert.equal(evaluateCommand('rm -rf ./dist').allowed, true);
|
||||
assert.equal(evaluateCommand('rm -rf node_modules').allowed, true);
|
||||
});
|
||||
|
||||
test('blocks destructive root and disk commands', () => {
|
||||
assert.equal(evaluateCommand('sudo rm -rf /').allowed, false);
|
||||
assert.equal(evaluateCommand('mkfs.ext4 /dev/sda1').allowed, false);
|
||||
assert.equal(evaluateCommand('dd if=/dev/zero of=/dev/sda').allowed, false);
|
||||
assert.equal(evaluateCommand('format C:').allowed, false);
|
||||
});
|
||||
|
||||
test('hook process returns non-zero for blocked command', () => {
|
||||
const result = spawnSync(process.execPath, [path.join(root, '.agents/hooks/validate-tool-call.mjs')], {
|
||||
input: JSON.stringify({tool_args: {CommandLine: 'rm -rf /'}}),
|
||||
encoding: 'utf8'
|
||||
});
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /BLOCKED by AG Kit/);
|
||||
});
|
||||
|
||||
test('doctor recognizes all six implementation phases', () => {
|
||||
const report = diagnose(root);
|
||||
assert.equal(report.runtime, 'antigravity');
|
||||
assert.equal(report.phases.discovery, true);
|
||||
assert.equal(report.phases.mcp, true);
|
||||
assert.equal(report.phases.hooks, true);
|
||||
assert.equal(report.phases.orchestration, true);
|
||||
assert.equal(report.phases.plugin, true);
|
||||
assert.equal(report.phases.validation, true);
|
||||
assert.equal(report.passed, true);
|
||||
});
|
||||
|
||||
test('runtime contract uses documented CLI capabilities instead of an invented version floor', () => {
|
||||
const contract = JSON.parse(fs.readFileSync(path.join(root, '.agents/antigravity.json'), 'utf8'));
|
||||
assert.equal('minimumCliVersion' in contract, false);
|
||||
assert.deepEqual(contract.requiredCliCommands, ['changelog', 'plugin', 'update']);
|
||||
});
|
||||
|
||||
test('MCP sync detects placeholders and plans without writing', () => {
|
||||
const plan = planSync({root, target: 'suite', force: false});
|
||||
assert.equal(plan.placeholders, true);
|
||||
assert.ok(Object.keys(plan.workspace.mcpServers).length > 0);
|
||||
});
|
||||
|
||||
test('plugin builder creates manifest, commands, skills, and hook', () => {
|
||||
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-kit-plugin-'));
|
||||
const output = path.join(temporary, 'plugin');
|
||||
const manifest = buildPlugin(root, output);
|
||||
assert.equal(manifest.runtime, 'antigravity');
|
||||
assert.ok(manifest.counts.skills > 0);
|
||||
assert.ok(manifest.counts.workflows > 0);
|
||||
assert.ok(fs.existsSync(path.join(output, 'gemini-extension.json')));
|
||||
assert.ok(fs.existsSync(path.join(output, 'commands/ag-kit/orchestrate.toml')));
|
||||
assert.ok(fs.existsSync(path.join(output, 'hooks/hooks.json')));
|
||||
assert.ok(fs.existsSync(path.join(output, 'PLUGIN_CONTENTS.json')));
|
||||
const firstInventory = fs.readFileSync(path.join(output, 'PLUGIN_CONTENTS.json'), 'utf8');
|
||||
buildPlugin(root, output);
|
||||
const secondInventory = fs.readFileSync(path.join(output, 'PLUGIN_CONTENTS.json'), 'utf8');
|
||||
assert.equal(secondInventory, firstInventory);
|
||||
fs.rmSync(temporary, {recursive: true, force: true});
|
||||
});
|
||||
111
.agents/hooks/validate-tool-call.mjs
Executable file
111
.agents/hooks/validate-tool-call.mjs
Executable file
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import process from 'node:process';
|
||||
|
||||
const BLOCK_RULES = [
|
||||
{
|
||||
id: 'unix-root-delete',
|
||||
pattern: /(?:^|[;&|]\s*)(?:sudo\s+)?rm\s+(?:-[A-Za-z]*r[A-Za-z]*f[A-Za-z]*|-[A-Za-z]*f[A-Za-z]*r[A-Za-z]*)\s+(?:--\s+)?\/(?:\*|\s|$)/i,
|
||||
message: 'recursive deletion of the filesystem root'
|
||||
},
|
||||
{
|
||||
id: 'filesystem-format',
|
||||
pattern: /(?:^|[;&|]\s*)(?:sudo\s+)?mkfs(?:\.[A-Za-z0-9_-]+)?\b/i,
|
||||
message: 'filesystem formatting command'
|
||||
},
|
||||
{
|
||||
id: 'raw-disk-overwrite',
|
||||
pattern: /\bdd\b[^\n]*\bof=\/dev\/(?:sd|nvme|vd|xvd)[A-Za-z0-9_-]*/i,
|
||||
message: 'raw disk overwrite'
|
||||
},
|
||||
{
|
||||
id: 'windows-drive-format',
|
||||
pattern: /(?:^|[;&|]\s*)format(?:\.com)?\s+[A-Za-z]:/i,
|
||||
message: 'Windows drive format'
|
||||
},
|
||||
{
|
||||
id: 'windows-root-delete',
|
||||
pattern: /remove-item\b[^\n]*-(?:recurse|r)\b[^\n]*-(?:force|fo)\b[^\n]*(?:[A-Za-z]:\\(?:\s|$)|[A-Za-z]:\\\*)/i,
|
||||
message: 'recursive deletion of a Windows drive root'
|
||||
}
|
||||
];
|
||||
|
||||
function readStdin() {
|
||||
return new Promise((resolve, reject) => {
|
||||
let input = '';
|
||||
process.stdin.setEncoding('utf8');
|
||||
process.stdin.on('data', chunk => {
|
||||
input += chunk;
|
||||
if (input.length > 1024 * 1024) {
|
||||
reject(new Error('hook payload exceeds 1 MiB'));
|
||||
}
|
||||
});
|
||||
process.stdin.on('end', () => resolve(input));
|
||||
process.stdin.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function firstString(...values) {
|
||||
for (const value of values) {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function extractCommand(payload) {
|
||||
const args = payload?.tool_args ?? payload?.toolArgs ?? payload?.arguments ?? {};
|
||||
return firstString(
|
||||
args.CommandLine,
|
||||
args.commandLine,
|
||||
args.command,
|
||||
args.cmd,
|
||||
payload?.command,
|
||||
payload?.cmd
|
||||
);
|
||||
}
|
||||
|
||||
export function evaluateCommand(command) {
|
||||
for (const rule of BLOCK_RULES) {
|
||||
if (rule.pattern.test(command)) {
|
||||
return {allowed: false, rule: rule.id, reason: rule.message};
|
||||
}
|
||||
}
|
||||
return {allowed: true, rule: null, reason: 'no destructive command pattern matched'};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let raw;
|
||||
try {
|
||||
raw = await readStdin();
|
||||
} catch (error) {
|
||||
console.error(`AG Kit hook warning: ${error.message}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(raw || '{}');
|
||||
} catch {
|
||||
console.error('AG Kit hook warning: Antigravity sent invalid JSON; allowing the call to avoid a runtime-wide lockout.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
const command = extractCommand(payload);
|
||||
if (!command) {
|
||||
console.log('AG Kit hook: no command payload detected; allowed.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = evaluateCommand(command);
|
||||
if (!result.allowed) {
|
||||
console.error(`BLOCKED by AG Kit (${result.rule}): ${result.reason}.`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
console.log('APPROVED by AG Kit: command passed the destructive-operation gate.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
process.exitCode = await main();
|
||||
}
|
||||
Reference in New Issue
Block a user