chore: import upstream snapshot with attribution
CI / Test (ubuntu-latest, Node 18.x, bun) (push) Failing after 15m1s
CI / Test (ubuntu-latest, Node 18.x, npm) (push) Failing after 15m1s
CI / Test (ubuntu-latest, Node 18.x, pnpm) (push) Failing after 15m1s
CI / Test (ubuntu-latest, Node 18.x, yarn) (push) Failing after 15m1s
CI / Test (ubuntu-latest, Node 20.x, bun) (push) Failing after 17m13s
CI / Test (ubuntu-latest, Node 20.x, npm) (push) Failing after 18m42s
CI / Test (ubuntu-latest, Node 20.x, pnpm) (push) Failing after 15m0s
CI / Test (ubuntu-latest, Node 20.x, yarn) (push) Failing after 49m44s
CI / Test (ubuntu-latest, Node 22.x, bun) (push) Failing after 51m55s
CI / Test (ubuntu-latest, Node 22.x, pnpm) (push) Failing after 21m57s
CI / Test (ubuntu-latest, Node 22.x, npm) (push) Failing after 37m39s
CI / Test (ubuntu-latest, Node 22.x, yarn) (push) Failing after 34m7s
CI / Validate Components (push) Failing after 37m15s
CI / Python Tests (push) Failing after 10m1s
CI / Security Scan (push) Failing after 10m1s
CI / Lint (push) Failing after 17m12s
CI / Coverage (push) Failing after 20m19s
CI / Test (macos-latest, Node 18.x, bun) (push) Has been cancelled
CI / Test (macos-latest, Node 18.x, npm) (push) Has been cancelled
CI / Test (macos-latest, Node 18.x, pnpm) (push) Has been cancelled
CI / Test (macos-latest, Node 18.x, yarn) (push) Has been cancelled
CI / Test (windows-latest, Node 18.x, npm) (push) Has been cancelled
CI / Test (windows-latest, Node 18.x, pnpm) (push) Has been cancelled
CI / Test (windows-latest, Node 18.x, yarn) (push) Has been cancelled
CI / Test (macos-latest, Node 20.x, bun) (push) Has been cancelled
CI / Test (macos-latest, Node 20.x, npm) (push) Has been cancelled
CI / Test (macos-latest, Node 20.x, pnpm) (push) Has been cancelled
CI / Test (macos-latest, Node 20.x, yarn) (push) Has been cancelled
CI / Test (windows-latest, Node 20.x, npm) (push) Has been cancelled
CI / Test (windows-latest, Node 20.x, pnpm) (push) Has been cancelled
CI / Test (windows-latest, Node 20.x, yarn) (push) Has been cancelled
CI / Test (macos-latest, Node 22.x, bun) (push) Has been cancelled
CI / Test (macos-latest, Node 22.x, npm) (push) Has been cancelled
CI / Test (macos-latest, Node 22.x, pnpm) (push) Has been cancelled
CI / Test (macos-latest, Node 22.x, yarn) (push) Has been cancelled
CI / Test (windows-latest, Node 22.x, npm) (push) Has been cancelled
CI / Test (windows-latest, Node 22.x, pnpm) (push) Has been cancelled
CI / Test (windows-latest, Node 22.x, yarn) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 11:55:55 +08:00
commit d48cda4081
3322 changed files with 668744 additions and 0 deletions
+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env bash
set -euo pipefail
# ECC Codex global regression sanity check.
# Validates that global ~/.codex state matches expected ECC integration.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CODEX_HOME="${CODEX_HOME:-$HOME/.codex}"
# Use rg if available, otherwise fall back to grep -E.
# All patterns in this script must be POSIX ERE compatible.
if command -v rg >/dev/null 2>&1; then
search_file() { rg -n "$1" "$2" >/dev/null 2>&1; }
else
search_file() { grep -En "$1" "$2" >/dev/null 2>&1; }
fi
CONFIG_FILE="$CODEX_HOME/config.toml"
AGENTS_FILE="$CODEX_HOME/AGENTS.md"
PROMPTS_DIR="$CODEX_HOME/prompts"
SKILLS_DIR="${AGENTS_HOME:-$HOME/.agents}/skills"
HOOKS_DIR_EXPECT="${ECC_GLOBAL_HOOKS_DIR:-$CODEX_HOME/git-hooks}"
failures=0
warnings=0
checks=0
ok() {
checks=$((checks + 1))
printf '[OK] %s\n' "$*"
}
warn() {
checks=$((checks + 1))
warnings=$((warnings + 1))
printf '[WARN] %s\n' "$*"
}
fail() {
checks=$((checks + 1))
failures=$((failures + 1))
printf '[FAIL] %s\n' "$*"
}
require_file() {
local file="$1"
local label="$2"
if [[ -f "$file" ]]; then
ok "$label exists ($file)"
else
fail "$label missing ($file)"
fi
}
check_config_pattern() {
local pattern="$1"
local label="$2"
if search_file "$pattern" "$CONFIG_FILE"; then
ok "$label"
else
fail "$label"
fi
}
check_config_absent() {
local pattern="$1"
local label="$2"
if search_file "$pattern" "$CONFIG_FILE"; then
fail "$label"
else
ok "$label"
fi
}
printf 'ECC GLOBAL SANITY CHECK\n'
printf 'Repo: %s\n' "$REPO_ROOT"
printf 'Codex home: %s\n\n' "$CODEX_HOME"
require_file "$CONFIG_FILE" "Global config.toml"
require_file "$AGENTS_FILE" "Global AGENTS.md"
if [[ -f "$AGENTS_FILE" ]]; then
if search_file '^# Everything Claude Code \(ECC\)' "$AGENTS_FILE"; then
ok "AGENTS contains ECC root instructions"
else
fail "AGENTS missing ECC root instructions"
fi
if search_file '^# Codex Supplement \(From ECC \.codex/AGENTS\.md\)' "$AGENTS_FILE"; then
ok "AGENTS contains ECC Codex supplement"
else
fail "AGENTS missing ECC Codex supplement"
fi
fi
if [[ -f "$CONFIG_FILE" ]]; then
check_config_pattern '^multi_agent[[:space:]]*=[[:space:]]*true' "multi_agent is enabled"
check_config_absent '^[[:space:]]*collab[[:space:]]*=' "deprecated collab flag is absent"
# persistent_instructions is recommended but optional; warn instead of fail
# so users who rely on AGENTS.md alone are not blocked (#967).
if search_file '^[[:space:]]*persistent_instructions[[:space:]]*=' "$CONFIG_FILE"; then
ok "persistent_instructions is configured"
else
warn "persistent_instructions is not set (recommended but optional)"
fi
check_config_pattern '^\[profiles\.strict\]' "profiles.strict exists"
check_config_pattern '^\[profiles\.yolo\]' "profiles.yolo exists"
# Current default connector set (docs/MCP-CONNECTOR-POLICY.md): exactly
# one connector. Former defaults (github, memory, sequential-thinking,
# context7, exa, ...) are opt-in user choices, so they are not required.
for section in \
'mcp_servers.chrome-devtools'
do
if search_file "^\[$section\]" "$CONFIG_FILE"; then
ok "MCP section [$section] exists"
else
fail "MCP section [$section] missing"
fi
done
# ECC <= 2.0.0 emitted a url-only exa entry that Codex's stdio-only
# schema rejects, breaking the whole config (#2224). Flag it so users
# re-run the sync (which repairs it) or remove it manually.
if search_file '^\[mcp_servers\.exa\]' "$CONFIG_FILE"; then
exa_block="$(awk '/^\[mcp_servers\.exa\]/{flag=1;next}/^\[/{flag=0}flag' "$CONFIG_FILE")"
if printf '%s\n' "$exa_block" | grep -Eq '^[[:space:]]*url[[:space:]]*=' \
&& ! printf '%s\n' "$exa_block" | grep -Eq '^[[:space:]]*command[[:space:]]*='; then
fail "MCP section [mcp_servers.exa] uses a url key, which Codex rejects for stdio servers — re-run ecc-sync-codex to repair (#2224)"
else
ok "MCP section [mcp_servers.exa] uses the stdio form"
fi
fi
fi
declare -a required_skills=(
api-design
article-writing
backend-patterns
coding-standards
content-engine
e2e-testing
eval-harness
frontend-patterns
frontend-slides
investor-materials
investor-outreach
market-research
security-review
strategic-compact
tdd-workflow
verification-loop
)
if [[ -d "$SKILLS_DIR" ]]; then
missing_skills=0
for skill in "${required_skills[@]}"; do
if [[ -d "$SKILLS_DIR/$skill" ]]; then
:
else
printf ' - missing skill: %s\n' "$skill"
missing_skills=$((missing_skills + 1))
fi
done
if [[ "$missing_skills" -eq 0 ]]; then
ok "All 16 ECC skills are present in $SKILLS_DIR"
else
warn "$missing_skills ECC skills missing from $SKILLS_DIR (install via ECC installer or npx skills)"
fi
else
warn "Skills directory missing ($SKILLS_DIR) — install via ECC installer or npx skills"
fi
if [[ -f "$PROMPTS_DIR/ecc-prompts-manifest.txt" ]]; then
ok "Command prompts manifest exists"
else
fail "Command prompts manifest missing"
fi
if [[ -f "$PROMPTS_DIR/ecc-extension-prompts-manifest.txt" ]]; then
ok "Extension prompts manifest exists"
else
fail "Extension prompts manifest missing"
fi
command_prompts_count="$(find "$PROMPTS_DIR" -maxdepth 1 -type f -name 'ecc-*.md' 2>/dev/null | wc -l | tr -d ' ')"
if [[ "$command_prompts_count" -ge 43 ]]; then
ok "ECC prompts count is $command_prompts_count (expected >= 43)"
else
fail "ECC prompts count is $command_prompts_count (expected >= 43)"
fi
hooks_path="$(git config --global --get core.hooksPath || true)"
if [[ -n "$hooks_path" ]]; then
if [[ "$hooks_path" == "$HOOKS_DIR_EXPECT" ]]; then
ok "Global hooksPath is set to $HOOKS_DIR_EXPECT"
else
warn "Global hooksPath is $hooks_path (expected $HOOKS_DIR_EXPECT)"
fi
else
fail "Global hooksPath is not configured"
fi
if [[ -x "$HOOKS_DIR_EXPECT/pre-commit" ]]; then
ok "Global pre-commit hook is installed and executable"
else
fail "Global pre-commit hook missing or not executable"
fi
if [[ -x "$HOOKS_DIR_EXPECT/pre-push" ]]; then
ok "Global pre-push hook is installed and executable"
else
fail "Global pre-push hook missing or not executable"
fi
if command -v ecc-sync-codex >/dev/null 2>&1; then
ok "ecc-sync-codex command is in PATH"
else
warn "ecc-sync-codex is not in PATH"
fi
if command -v ecc-install-git-hooks >/dev/null 2>&1; then
ok "ecc-install-git-hooks command is in PATH"
else
warn "ecc-install-git-hooks is not in PATH"
fi
if command -v ecc-check-codex >/dev/null 2>&1; then
ok "ecc-check-codex command is in PATH"
else
warn "ecc-check-codex is not in PATH (this is expected before alias setup)"
fi
printf '\nSummary: checks=%d, warnings=%d, failures=%d\n' "$checks" "$warnings" "$failures"
if [[ "$failures" -eq 0 ]]; then
printf 'ECC GLOBAL SANITY: PASS\n'
else
printf 'ECC GLOBAL SANITY: FAIL\n'
exit 1
fi
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env node
'use strict';
/**
* Verify that the installed Codex plugin cache can resolve every file path
* referenced by the cached plugin manifest.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const REPO_ROOT = path.join(__dirname, '..', '..');
const PACKAGE_JSON = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'package.json'), 'utf8'));
function usage() {
console.log([
'Usage: check-plugin-cache.js [options]',
'',
'Options:',
' --codex-home <dir> Override CODEX_HOME (default: $CODEX_HOME or ~/.codex)',
' --plugin-dir <dir> Check a specific installed plugin cache directory',
' --marketplace <name> Marketplace cache name (default: ecc)',
' --plugin <name> Plugin cache name (default: ecc)',
' --version <version> Plugin version (default: package.json version)',
' --help Show this help text',
].join('\n'));
}
function validateCacheSegment(flag, value) {
if (
typeof value !== 'string' ||
value.trim() === '' ||
value.includes('\0') ||
value.includes('..') ||
value.includes('/') ||
value.includes('\\') ||
path.isAbsolute(value) ||
path.win32.isAbsolute(value)
) {
throw new Error(`Invalid ${flag}: expected a single cache path segment`);
}
return value;
}
function parseArgs(argv) {
const defaults = {
marketplace: 'ecc',
plugin: 'ecc',
version: PACKAGE_JSON.version,
codexHome: process.env.CODEX_HOME || path.join(os.homedir(), '.codex'),
pluginDir: null,
};
const optionKeys = {
'--codex-home': 'codexHome',
'--plugin-dir': 'pluginDir',
'--marketplace': 'marketplace',
'--plugin': 'plugin',
'--version': 'version',
};
let parsed = {};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === '--help' || arg === '-h') {
parsed = { ...parsed, help: true };
continue;
}
const key = optionKeys[arg];
if (!key) {
throw new Error(`Unknown argument: ${arg}`);
}
const value = argv[index + 1];
if (!value || value.startsWith('--')) {
throw new Error(`Missing value for ${arg}`);
}
index += 1;
parsed = { ...parsed, [key]: value };
}
const options = { ...defaults, ...parsed };
return {
...options,
marketplace: validateCacheSegment('--marketplace', options.marketplace),
plugin: validateCacheSegment('--plugin', options.plugin),
version: validateCacheSegment('--version', options.version),
codexHome: path.resolve(options.codexHome),
pluginDir: options.pluginDir ? path.resolve(options.pluginDir) : null,
};
}
function log(message) {
console.log(`[ecc-codex] ${message}`);
}
function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (error) {
throw new Error(`Failed to read ${filePath}: ${error.message}`);
}
}
function pluginCacheDir(options) {
if (options.pluginDir) {
return options.pluginDir;
}
return path.join(
options.codexHome,
'plugins',
'cache',
options.marketplace,
options.plugin,
options.version
);
}
function listInstalledVersions(options) {
const versionsRoot = path.join(
options.codexHome,
'plugins',
'cache',
options.marketplace,
options.plugin
);
try {
return fs.readdirSync(versionsRoot, { withFileTypes: true })
.filter(entry => entry.isDirectory())
.map(entry => entry.name)
.sort();
} catch {
return [];
}
}
function manifestPathFor(pluginDir) {
return path.join(pluginDir, '.codex-plugin', 'plugin.json');
}
function collectManifestRefs(manifest) {
const refs = [];
if (typeof manifest.skills === 'string') {
refs.push({ label: 'skills', ref: manifest.skills, kind: 'directory' });
}
if (typeof manifest.mcpServers === 'string') {
refs.push({ label: 'mcpServers', ref: manifest.mcpServers, kind: 'file' });
}
if (manifest.interface && typeof manifest.interface.composerIcon === 'string') {
refs.push({
label: 'interface.composerIcon',
ref: manifest.interface.composerIcon,
kind: 'file',
});
}
if (manifest.interface && typeof manifest.interface.logo === 'string') {
refs.push({ label: 'interface.logo', ref: manifest.interface.logo, kind: 'file' });
}
return refs;
}
function pathExists(target, kind) {
try {
const stat = fs.statSync(target);
return kind === 'directory' ? stat.isDirectory() : stat.isFile();
} catch {
return false;
}
}
function checkCache(options) {
const cacheDir = pluginCacheDir(options);
const manifestPath = manifestPathFor(cacheDir);
log('Codex plugin cache check');
log(`Codex home: ${options.codexHome}`);
log(`Plugin cache: ${cacheDir}`);
if (!fs.existsSync(manifestPath)) {
const versions = listInstalledVersions(options);
log(`[FAIL] Cached plugin manifest missing: ${manifestPath}`);
if (versions.length > 0) {
log(`Installed versions found: ${versions.join(', ')}`);
log(`Re-run with --version <version> if you want to inspect a different cache entry.`);
} else {
log(`No installed cache entries found for ${options.marketplace}/${options.plugin}.`);
if (options.marketplace === 'ecc' && options.plugin === 'ecc') {
log('Run: codex plugin marketplace add affaan-m/ECC');
} else {
log('Install the requested plugin into the Codex plugin cache.');
}
log('Then run: codex plugin list');
}
return 1;
}
const manifest = readJson(manifestPath);
const refs = collectManifestRefs(manifest);
let failures = 0;
log(`Manifest: ${manifestPath}`);
for (const entry of refs) {
const target = path.resolve(cacheDir, entry.ref);
const relativeTarget = path.relative(cacheDir, target);
if (relativeTarget.startsWith('..') || path.isAbsolute(relativeTarget)) {
failures += 1;
log(`[FAIL] ${entry.label} escapes cache boundary`);
continue;
}
if (pathExists(target, entry.kind)) {
log(`[OK] ${entry.label} -> ${target}`);
} else {
failures += 1;
log(`[FAIL] ${entry.label} missing -> ${target}`);
}
}
if (refs.length === 0) {
log('[WARN] Cached manifest has no string path references to verify.');
}
if (failures > 0) {
log(`${failures} cached manifest reference(s) do not resolve.`);
log('codex plugin list only confirms marketplace registration; it is not proof of runtime skill loading.');
const syncScript = path.join(REPO_ROOT, 'scripts', 'sync-ecc-to-codex.sh');
if (fs.existsSync(syncScript)) {
log('Use the supported sync path until the cache contains the referenced files:');
log('npm install && bash scripts/sync-ecc-to-codex.sh');
} else {
log('Use the supported manual sync workflow from your ECC installation.');
}
return 1;
}
log('All cached manifest references resolve.');
return 0;
}
function main() {
let options;
try {
options = parseArgs(process.argv.slice(2));
} catch (error) {
console.error(`[ecc-codex] ${error.message}`);
usage();
process.exit(1);
}
if (options.help) {
usage();
process.exit(0);
}
try {
process.exit(checkCache(options));
} catch (error) {
console.error(`[ecc-codex] ${error.message}`);
process.exit(1);
}
}
main();
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
set -euo pipefail
# Install ECC git safety hooks globally via core.hooksPath.
# Usage:
# ./scripts/codex/install-global-git-hooks.sh
# ./scripts/codex/install-global-git-hooks.sh --dry-run
MODE="apply"
if [[ "${1:-}" == "--dry-run" ]]; then
MODE="dry-run"
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SOURCE_DIR="$REPO_ROOT/scripts/codex-git-hooks"
DEST_DIR="${ECC_GLOBAL_HOOKS_DIR:-$HOME/.codex/git-hooks}"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="$HOME/.codex/backups/git-hooks-$STAMP"
log() {
printf '[ecc-hooks] %s\n' "$*"
}
run_or_echo() {
if [[ "$MODE" == "dry-run" ]]; then
printf '[dry-run]'
printf ' %q' "$@"
printf '\n'
else
"$@"
fi
}
if [[ ! -d "$SOURCE_DIR" ]]; then
log "Missing source hooks directory: $SOURCE_DIR"
exit 1
fi
log "Mode: $MODE"
log "Source hooks: $SOURCE_DIR"
log "Global hooks destination: $DEST_DIR"
if [[ -d "$DEST_DIR" ]]; then
log "Backing up existing hooks directory to $BACKUP_DIR"
run_or_echo mkdir -p "$BACKUP_DIR"
run_or_echo cp -R "$DEST_DIR" "$BACKUP_DIR/hooks"
fi
run_or_echo mkdir -p "$DEST_DIR"
run_or_echo cp "$SOURCE_DIR/pre-commit" "$DEST_DIR/pre-commit"
run_or_echo cp "$SOURCE_DIR/pre-push" "$DEST_DIR/pre-push"
run_or_echo chmod +x "$DEST_DIR/pre-commit" "$DEST_DIR/pre-push"
if [[ "$MODE" == "apply" ]]; then
prev_hooks_path="$(git config --global core.hooksPath || true)"
if [[ -n "$prev_hooks_path" ]]; then
log "Previous global hooksPath: $prev_hooks_path"
fi
fi
run_or_echo git config --global core.hooksPath "$DEST_DIR"
log "Installed ECC global git hooks."
log "Disable per repo by creating .ecc-hooks-disable in project root."
log "Temporary bypass: ECC_SKIP_PRECOMMIT=1 or ECC_SKIP_PREPUSH=1"
+317
View File
@@ -0,0 +1,317 @@
#!/usr/bin/env node
'use strict';
/**
* Merge the non-MCP Codex baseline from `.codex/config.toml` into a target
* `config.toml` without overwriting existing user choices.
*
* Strategy: add-only.
* - Missing root keys are inserted before the first TOML table.
* - Missing table keys are appended to existing tables.
* - Missing tables are appended to the end of the file.
*/
const fs = require('fs');
const path = require('path');
let TOML;
try {
TOML = require('@iarna/toml');
} catch {
console.error('[ecc-codex] Missing dependency: @iarna/toml');
console.error('[ecc-codex] Run: npm install (from the ECC repo root)');
process.exit(1);
}
const ROOT_KEYS = ['approval_policy', 'sandbox_mode', 'web_search', 'notify', 'persistent_instructions'];
const TABLE_PATHS = [
'features',
'profiles.strict',
'profiles.yolo',
'agents',
'agents.explorer',
'agents.reviewer',
'agents.docs_researcher',
];
const TOML_HEADER_RE = /^[ \t]*(?:\[[^[\]\n][^\]\n]*\]|\[\[[^[\]\n][^\]\n]*\]\])[ \t]*(?:#.*)?$/m;
function log(message) {
console.log(`[ecc-codex] ${message}`);
}
function warn(message) {
console.warn(`[ecc-codex] WARNING: ${message}`);
}
function getNested(obj, pathParts) {
let current = obj;
for (const part of pathParts) {
if (!current || typeof current !== 'object' || !(part in current)) {
return undefined;
}
current = current[part];
}
return current;
}
function setNested(obj, pathParts, value) {
let current = obj;
for (let i = 0; i < pathParts.length - 1; i += 1) {
const part = pathParts[i];
if (!current[part] || typeof current[part] !== 'object' || Array.isArray(current[part])) {
current[part] = {};
}
current = current[part];
}
current[pathParts[pathParts.length - 1]] = value;
}
function findFirstTableIndex(raw) {
const match = TOML_HEADER_RE.exec(raw);
return match ? match.index : -1;
}
function findTableRange(raw, tablePath) {
const escaped = tablePath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const headerPattern = new RegExp(`^[ \\t]*\\[${escaped}\\][ \\t]*(?:#.*)?$`, 'm');
const match = headerPattern.exec(raw);
if (!match) {
return null;
}
const headerEnd = raw.indexOf('\n', match.index);
const bodyStart = headerEnd === -1 ? raw.length : headerEnd + 1;
const nextHeaderRel = raw.slice(bodyStart).search(TOML_HEADER_RE);
const bodyEnd = nextHeaderRel === -1 ? raw.length : bodyStart + nextHeaderRel;
return { bodyStart, bodyEnd };
}
function ensureTrailingNewline(text) {
return text.endsWith('\n') ? text : `${text}\n`;
}
function insertBeforeFirstTable(raw, block) {
const normalizedBlock = ensureTrailingNewline(block.trimEnd());
const firstTableIndex = findFirstTableIndex(raw);
if (firstTableIndex === -1) {
const prefix = raw.trimEnd();
return prefix ? `${prefix}\n${normalizedBlock}` : normalizedBlock;
}
const before = raw.slice(0, firstTableIndex).trimEnd();
const after = raw.slice(firstTableIndex).replace(/^\n+/, '');
return `${before}\n\n${normalizedBlock}\n${after}`;
}
function appendBlock(raw, block) {
const prefix = raw.trimEnd();
const normalizedBlock = block.trimEnd();
return prefix ? `${prefix}\n\n${normalizedBlock}\n` : `${normalizedBlock}\n`;
}
function stringifyValue(value) {
return TOML.stringify({ value }).trim().replace(/^value = /, '');
}
function updateInlineTableKeys(raw, tablePath, missingKeys) {
const pathParts = tablePath.split('.');
if (pathParts.length < 2) {
return null;
}
const parentPath = pathParts.slice(0, -1).join('.');
const parentRange = findTableRange(raw, parentPath);
if (!parentRange) {
return null;
}
const tableKey = pathParts[pathParts.length - 1];
const escapedKey = tableKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const body = raw.slice(parentRange.bodyStart, parentRange.bodyEnd);
const lines = body.split('\n');
for (let index = 0; index < lines.length; index += 1) {
const inlinePattern = new RegExp(`^(\\s*${escapedKey}\\s*=\\s*\\{)(.*?)(\\}\\s*(?:#.*)?)$`);
const match = inlinePattern.exec(lines[index]);
if (!match) {
continue;
}
const additions = Object.entries(missingKeys)
.map(([key, value]) => `${key} = ${stringifyValue(value)}`)
.join(', ');
const existingEntries = match[2].trim();
const nextEntries = existingEntries ? `${existingEntries}, ${additions}` : additions;
lines[index] = `${match[1]}${nextEntries}${match[3]}`;
return `${raw.slice(0, parentRange.bodyStart)}${lines.join('\n')}${raw.slice(parentRange.bodyEnd)}`;
}
return null;
}
function appendImplicitTable(raw, tablePath, missingKeys) {
const candidate = appendBlock(raw, stringifyTable(tablePath, missingKeys));
try {
TOML.parse(candidate);
return candidate;
} catch {
return null;
}
}
function appendToTable(raw, tablePath, block, missingKeys = null) {
const range = findTableRange(raw, tablePath);
if (!range) {
if (missingKeys) {
const inlineUpdated = updateInlineTableKeys(raw, tablePath, missingKeys);
if (inlineUpdated) {
return inlineUpdated;
}
const appendedTable = appendImplicitTable(raw, tablePath, missingKeys);
if (appendedTable) {
return appendedTable;
}
}
warn(`Skipping missing keys for [${tablePath}] because it has no standalone header and could not be safely updated`);
return raw;
}
const before = raw.slice(0, range.bodyEnd).trimEnd();
const after = raw.slice(range.bodyEnd).replace(/^\n*/, '\n');
return `${before}\n${block.trimEnd()}\n${after}`;
}
function stringifyRootKeys(keys) {
return TOML.stringify(keys).trim();
}
function stringifyTable(tablePath, value) {
const scalarOnly = {};
for (const [key, entryValue] of Object.entries(value)) {
if (entryValue && typeof entryValue === 'object' && !Array.isArray(entryValue)) {
continue;
}
scalarOnly[key] = entryValue;
}
const snippet = {};
setNested(snippet, tablePath.split('.'), scalarOnly);
return TOML.stringify(snippet).trim();
}
function stringifyTableKeys(tableValue) {
const lines = [];
for (const [key, value] of Object.entries(tableValue)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
continue;
}
lines.push(TOML.stringify({ [key]: value }).trim());
}
return lines.join('\n');
}
function main() {
const args = process.argv.slice(2);
const configPath = args.find(arg => !arg.startsWith('-'));
const dryRun = args.includes('--dry-run');
if (!configPath) {
console.error('Usage: merge-codex-config.js <config.toml> [--dry-run]');
process.exit(1);
}
const referencePath = path.join(__dirname, '..', '..', '.codex', 'config.toml');
if (!fs.existsSync(referencePath)) {
console.error(`[ecc-codex] Reference config not found: ${referencePath}`);
process.exit(1);
}
if (!fs.existsSync(configPath)) {
console.error(`[ecc-codex] Config file not found: ${configPath}`);
process.exit(1);
}
const raw = fs.readFileSync(configPath, 'utf8');
const referenceRaw = fs.readFileSync(referencePath, 'utf8');
let targetConfig;
let referenceConfig;
try {
targetConfig = TOML.parse(raw);
referenceConfig = TOML.parse(referenceRaw);
} catch (error) {
console.error(`[ecc-codex] Failed to parse TOML: ${error.message}`);
process.exit(1);
}
const missingRootKeys = {};
for (const key of ROOT_KEYS) {
if (referenceConfig[key] !== undefined && targetConfig[key] === undefined) {
missingRootKeys[key] = referenceConfig[key];
}
}
const missingTables = [];
const missingTableKeys = [];
for (const tablePath of TABLE_PATHS) {
const pathParts = tablePath.split('.');
const referenceValue = getNested(referenceConfig, pathParts);
if (referenceValue === undefined) {
continue;
}
const targetValue = getNested(targetConfig, pathParts);
if (targetValue === undefined) {
missingTables.push(tablePath);
continue;
}
const missingKeys = {};
for (const [key, value] of Object.entries(referenceValue)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
continue;
}
if (targetValue[key] === undefined) {
missingKeys[key] = value;
}
}
if (Object.keys(missingKeys).length > 0) {
missingTableKeys.push({ tablePath, missingKeys });
}
}
if (
Object.keys(missingRootKeys).length === 0 &&
missingTables.length === 0 &&
missingTableKeys.length === 0
) {
log('All baseline Codex settings already present. Nothing to do.');
return;
}
let nextRaw = raw;
if (Object.keys(missingRootKeys).length > 0) {
log(` [add-root] ${Object.keys(missingRootKeys).join(', ')}`);
nextRaw = insertBeforeFirstTable(nextRaw, stringifyRootKeys(missingRootKeys));
}
for (const { tablePath, missingKeys } of missingTableKeys) {
log(` [add-keys] [${tablePath}] -> ${Object.keys(missingKeys).join(', ')}`);
nextRaw = appendToTable(nextRaw, tablePath, stringifyTableKeys(missingKeys), missingKeys);
}
for (const tablePath of missingTables) {
log(` [add-table] [${tablePath}]`);
nextRaw = appendBlock(nextRaw, stringifyTable(tablePath, getNested(referenceConfig, tablePath.split('.'))));
}
if (dryRun) {
log('Dry run — would write the merged Codex baseline.');
return;
}
fs.writeFileSync(configPath, nextRaw, 'utf8');
log('Done. Baseline Codex settings merged.');
}
main();
+352
View File
@@ -0,0 +1,352 @@
#!/usr/bin/env node
'use strict';
/**
* Merge ECC-recommended MCP servers into a Codex config.toml.
*
* Strategy: ADD-ONLY by default.
* - Parse the TOML to detect which mcp_servers.* sections exist.
* - Append raw TOML text for any missing servers (preserves existing file byte-for-byte).
* - Log warnings when an existing server's config differs from the ECC recommendation.
* - With --update-mcp, also replace existing ECC-managed servers.
*
* Uses the repo's package-manager abstraction (scripts/lib/package-manager.js)
* so MCP launcher commands respect the user's configured package manager.
*
* Usage:
* node merge-mcp-config.js <config.toml> [--dry-run] [--update-mcp]
*/
const fs = require('fs');
const path = require('path');
const { parseDisabledMcpServers } = require('../lib/mcp-config');
let TOML;
try {
TOML = require('@iarna/toml');
} catch {
console.error('[ecc-mcp] Missing dependency: @iarna/toml');
console.error('[ecc-mcp] Run: npm install (from the ECC repo root)');
process.exit(1);
}
// ---------------------------------------------------------------------------
// Package manager detection
// ---------------------------------------------------------------------------
let pmConfig;
try {
const { getPackageManager } = require(path.join(__dirname, '..', 'lib', 'package-manager.js'));
pmConfig = getPackageManager();
} catch {
// Fallback: if package-manager.js isn't available, default to npx
pmConfig = { name: 'npm', config: { name: 'npm', execCmd: 'npx' } };
}
// Yarn 1.x doesn't support `yarn dlx` — fall back to npx for classic Yarn.
let resolvedExecCmd = pmConfig.config.execCmd;
if (pmConfig.name === 'yarn' && resolvedExecCmd === 'yarn dlx') {
try {
const { execFileSync } = require('child_process');
const ver = execFileSync('yarn', ['--version'], { encoding: 'utf8', timeout: 5000 }).trim();
if (ver.startsWith('1.')) {
resolvedExecCmd = 'npx';
}
} catch {
// Can't detect version — keep yarn dlx and let it fail visibly
}
}
const PM_NAME = pmConfig.config.name || pmConfig.name;
const PM_EXEC = resolvedExecCmd; // e.g. "pnpm dlx", "npx", "bunx", "yarn dlx"
const PM_EXEC_PARTS = PM_EXEC.split(/\s+/); // ["pnpm", "dlx"] or ["npx"] or ["bunx"]
// ---------------------------------------------------------------------------
// ECC-recommended MCP servers
// ---------------------------------------------------------------------------
/**
* Build a server spec with the detected package manager.
* Returns { fields, toml } where fields is for drift detection and
* toml is the raw text appended to the file.
*
* Codex's [mcp_servers.*] TOML schema is stdio-only (command/args) —
* never emit a `url` key here. The http/url form is valid only for
* Claude Code's .mcp.json (#2224).
*/
function dlxServer(name, pkg, extraFields, extraToml) {
const args = [...PM_EXEC_PARTS.slice(1), pkg];
const fields = { command: PM_EXEC_PARTS[0], args, ...extraFields };
const argsStr = JSON.stringify(args).replace(/,/g, ', ');
let toml = `[mcp_servers.${name}]\ncommand = "${PM_EXEC_PARTS[0]}"\nargs = ${argsStr}`;
if (extraToml) toml += '\n' + extraToml;
return { fields, toml };
}
/** Each entry: key = section name under mcp_servers, value = { toml, fields } */
const DEFAULT_MCP_STARTUP_TIMEOUT_SEC = 30;
const DEFAULT_MCP_STARTUP_TIMEOUT_TOML = `startup_timeout_sec = ${DEFAULT_MCP_STARTUP_TIMEOUT_SEC}`;
// Current default connector set (docs/MCP-CONNECTOR-POLICY.md): exactly one
// connector. The former defaults (supabase, playwright, context7, exa,
// github, memory, sequential-thinking) were retired in the June 2026 audit
// and must not be re-emitted; they remain opt-in via
// mcp-configs/mcp-servers.json. Existing user-managed entries are never
// touched by the merge (add-only), except the known-invalid repair below.
const ECC_SERVERS = {
'chrome-devtools': dlxServer('chrome-devtools', 'chrome-devtools-mcp@latest', { startup_timeout_sec: DEFAULT_MCP_STARTUP_TIMEOUT_SEC }, DEFAULT_MCP_STARTUP_TIMEOUT_TOML)
};
// ECC <= 2.0.0 emitted [mcp_servers.exa] with a `url` key. Codex rejects
// `url` for stdio servers, which makes the *entire* config.toml fail to
// load (#2224). Repair exactly that ECC-emitted form on every merge so
// re-running the installer fixes broken configs instead of preserving
// them. A user-managed stdio exa entry (command/args) is left untouched.
const RETIRED_INVALID_URL_SERVERS = {
exa: 'https://mcp.exa.ai/mcp'
};
// Legacy section names that should be treated as an existing ECC server.
// e.g. older configs shipped [mcp_servers.context7-mcp] instead of
// [mcp_servers.context7]. Empty since the June 2026 default-set reduction.
const LEGACY_ALIASES = {};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function log(msg) {
console.log(`[ecc-mcp] ${msg}`);
}
function warn(msg) {
console.warn(`[ecc-mcp] WARNING: ${msg}`);
}
/** Shallow-compare two objects (one level deep, arrays by JSON). */
function configDiffers(existing, recommended) {
for (const key of Object.keys(recommended)) {
const a = existing[key];
const b = recommended[key];
if (Array.isArray(b)) {
if (JSON.stringify(a) !== JSON.stringify(b)) return true;
} else if (a !== b) {
return true;
}
}
return false;
}
/**
* Remove a TOML section and its key-value pairs from raw text.
* Matches the section header even if followed by inline comments or whitespace
* (e.g. `[mcp_servers.github] # comment`).
* Returns the text with the section removed.
*/
function removeSectionFromText(text, sectionHeader) {
const escaped = sectionHeader.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const headerPattern = new RegExp(`^${escaped}(\\s*(#.*)?)?$`);
const lines = text.split('\n');
const result = [];
let skipping = false;
for (const line of lines) {
const trimmed = line.replace(/\r$/, '');
if (headerPattern.test(trimmed)) {
skipping = true;
continue;
}
if (skipping && /^\[/.test(trimmed)) {
skipping = false;
}
if (!skipping) {
result.push(line);
}
}
return result.join('\n');
}
/**
* Collect all TOML sub-section headers for a given server name.
* @iarna/toml nests subtables, so `[mcp_servers.supabase.env]` appears as
* `parsed.mcp_servers.supabase.env` (nested), NOT as a flat dotted key.
* Walk the nested object to find sub-objects that represent TOML sub-tables.
*/
function findSubSections(serverObj, prefix) {
const sections = [];
if (!serverObj || typeof serverObj !== 'object') return sections;
for (const key of Object.keys(serverObj)) {
const val = serverObj[key];
if (val && typeof val === 'object' && !Array.isArray(val)) {
const subPath = `${prefix}.${key}`;
sections.push(subPath);
sections.push(...findSubSections(val, subPath));
}
}
return sections;
}
/**
* Remove a server and all its sub-sections from raw TOML text.
* Uses findSubSections to walk the parsed nested object (not flat keys).
*/
function removeServerFromText(raw, serverName, existing) {
let result = removeSectionFromText(raw, `[mcp_servers.${serverName}]`);
const serverObj = existing[serverName];
if (serverObj) {
for (const sub of findSubSections(serverObj, serverName)) {
result = removeSectionFromText(result, `[mcp_servers.${sub}]`);
}
}
return result;
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
function main() {
const args = process.argv.slice(2);
const configPath = args.find(a => !a.startsWith('-'));
const dryRun = args.includes('--dry-run');
const updateMcp = args.includes('--update-mcp');
const disabledServers = new Set(parseDisabledMcpServers(process.env.ECC_DISABLED_MCPS));
if (!configPath) {
console.error('Usage: merge-mcp-config.js <config.toml> [--dry-run] [--update-mcp]');
process.exit(1);
}
if (!fs.existsSync(configPath)) {
console.error(`[ecc-mcp] Config file not found: ${configPath}`);
process.exit(1);
}
log(`Package manager: ${PM_NAME} (exec: ${PM_EXEC})`);
if (disabledServers.size > 0) {
log(`Disabled via ECC_DISABLED_MCPS: ${[...disabledServers].join(', ')}`);
}
let raw = fs.readFileSync(configPath, 'utf8');
let parsed;
try {
parsed = TOML.parse(raw);
} catch (err) {
console.error(`[ecc-mcp] Failed to parse ${configPath}: ${err.message}`);
process.exit(1);
}
const existing = parsed.mcp_servers || {};
const toAppend = [];
const toRemoveLog = [];
// Repair schema-invalid entries emitted by earlier ECC versions (#2224).
for (const [name, invalidUrl] of Object.entries(RETIRED_INVALID_URL_SERVERS)) {
const entry = existing[name];
const isBrokenEccForm =
entry &&
typeof entry.url === 'string' &&
entry.url === invalidUrl &&
typeof entry.command !== 'string';
if (isBrokenEccForm) {
toRemoveLog.push(`mcp_servers.${name} (invalid url entry from earlier ECC versions)`);
raw = removeServerFromText(raw, name, existing);
log(` [repair] mcp_servers.${name} — url is not valid for Codex stdio servers, removing`);
}
}
for (const [name, spec] of Object.entries(ECC_SERVERS)) {
const entry = existing[name];
const aliases = LEGACY_ALIASES[name] || [];
const legacyName = aliases.find(a => existing[a] && typeof existing[a].command === 'string');
// Prefer canonical entry over legacy alias
const hasCanonical = entry && typeof entry.command === 'string';
const resolvedEntry = hasCanonical ? entry : legacyName ? existing[legacyName] : null;
// Recognize url-form entries as existing so they are never duplicated.
// (Codex itself rejects url-form stdio servers; ECC only ever emits
// command/args, but a user-managed entry must still count as present.)
const urlEntry = !resolvedEntry && entry && typeof entry.url === 'string' ? entry : null;
const finalEntry = resolvedEntry || urlEntry;
const resolvedLabel = hasCanonical ? name : legacyName || name;
if (disabledServers.has(name)) {
if (finalEntry) {
toRemoveLog.push(`mcp_servers.${resolvedLabel} (disabled)`);
raw = removeServerFromText(raw, resolvedLabel, existing);
if (resolvedLabel !== name) {
raw = removeServerFromText(raw, name, existing);
}
}
log(` [skip] mcp_servers.${name} (disabled)`);
continue;
}
if (finalEntry) {
if (updateMcp) {
// --update-mcp: remove existing section (and legacy alias), will re-add below
toRemoveLog.push(`mcp_servers.${resolvedLabel}`);
raw = removeServerFromText(raw, resolvedLabel, existing);
if (resolvedLabel !== name) {
raw = removeServerFromText(raw, name, existing);
}
if (legacyName && hasCanonical) {
toRemoveLog.push(`mcp_servers.${legacyName}`);
raw = removeServerFromText(raw, legacyName, existing);
}
toAppend.push(spec.toml);
} else {
// Add-only mode: skip, but warn about drift
if (legacyName && !hasCanonical) {
warn(`mcp_servers.${legacyName} is a legacy name for ${name} (run with --update-mcp to migrate)`);
} else if (configDiffers(finalEntry, spec.fields)) {
warn(`mcp_servers.${name} differs from ECC recommendation (run with --update-mcp to refresh)`);
} else {
log(` [ok] mcp_servers.${name}`);
}
}
} else {
log(` [add] mcp_servers.${name}`);
toAppend.push(spec.toml);
}
}
const hasRemovals = toRemoveLog.length > 0;
if (toAppend.length === 0 && !hasRemovals) {
log('All ECC MCP servers already present. Nothing to do.');
return;
}
const appendText = '\n' + toAppend.join('\n\n') + '\n';
if (dryRun) {
if (toRemoveLog.length > 0) {
log('Dry run — would remove:');
for (const label of toRemoveLog) log(` [remove] ${label}`);
}
if (toAppend.length > 0) {
log('Dry run — would append:');
console.log(appendText);
}
return;
}
// Write: for add-only, append to preserve existing content byte-for-byte.
// For --update-mcp, we modified `raw` above, so write the full file + appended sections.
if (updateMcp || hasRemovals) {
for (const label of toRemoveLog) log(` [update] ${label}`);
const cleaned = raw.replace(/\n+$/, '\n');
fs.writeFileSync(configPath, cleaned + (toAppend.length > 0 ? appendText : ''), 'utf8');
} else {
fs.appendFileSync(configPath, appendText, 'utf8');
}
if (hasRemovals && toAppend.length === 0) {
log(`Done. Removed ${toRemoveLog.length} server section(s).`);
return;
}
log(`Done. ${toAppend.length} server(s) ${updateMcp ? 'updated' : 'added'}.`);
}
main();