Merge remote-tracking branch 'origin/main' into pr/2856

# Conflicts:
#	manifests/context-packs/skill-triggers@1.json
This commit is contained in:
Misty-Star committed 2026-11-02 16:00:47 +08:00
commit 34c20e751b
266 files changed
+17164 -805

No files matched your search

+10 -5
View File
@@ -148,6 +148,9 @@ function collectManifestRefs(manifest) {
if (typeof manifest.mcpServers === 'string') {
refs.push({ label: 'mcpServers', ref: manifest.mcpServers, kind: 'file' });
}
if (typeof manifest.hooks === 'string') {
refs.push({ label: 'hooks', ref: manifest.hooks, kind: 'file' });
}
if (manifest.interface && typeof manifest.interface.composerIcon === 'string') {
refs.push({
label: 'interface.composerIcon',
@@ -224,13 +227,15 @@ function checkCache(options) {
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');
log('Refresh the native marketplace and re-add the plugin using the same CODEX_HOME as the affected session:');
if (options.marketplace === 'ecc' && options.plugin === 'ecc') {
log('codex plugin marketplace upgrade ecc');
log('codex plugin add ecc@ecc');
} else {
log('Use the supported manual sync workflow from your ECC installation.');
log('Follow the requested plugin marketplace instructions to refresh and re-add that native plugin.');
}
log('Restart Codex, confirm the active plugin root with codex plugin list --json, and re-run this checker with --plugin-dir ACTIVE_ROOT (or --version ACTIVE_VERSION).');
log('See .codex-plugin/README.md for native cache recovery and runtime dependency instructions.');
return 1;
}
+22 -1
View File
@@ -21,6 +21,7 @@
const fs = require('fs');
const path = require('path');
const http = require('http');
const { spawn } = require('child_process');
const {
LOOPBACK_HOSTNAMES,
buildAllowedHostnames,
@@ -30,6 +31,7 @@ const {
const { normalizeAgentTools } = require('./lib/agent-tools');
const { readHooksConfig } = require('./lib/hooks-config');
const { getClaudeDir } = require('./lib/utils');
const { openBrowser } = require('./lib/platform-launch');
const DEFAULT_HOST = '127.0.0.1';
@@ -1073,6 +1075,25 @@ function listenDashboardServer(
return dashboardServer.listen(port, resolvedHost, onListening);
}
// Best-effort auto-open. openBrowser() handles the launcher's async 'error'
// event so a missing xdg-open/open leaves the server running; the wrapped
// spawn surfaces that failure so headless users know why no browser opened.
function openDashboardInBrowser(url) {
let reported = false;
const reportFailure = (reason) => {
if (reported) return;
reported = true;
console.error(`[ECC] Could not open a browser automatically (${reason}); open ${url} manually.`);
};
const result = openBrowser(url, process.platform, (command, args, options) => {
const child = spawn(command, args, options);
child.once('error', err => reportFailure(err && err.code ? err.code : 'spawn-error'));
return child;
});
if (!result.opened) reportFailure(result.reason);
return result;
}
const server = createDashboardServer();
if (require.main === module) {
@@ -1080,7 +1101,7 @@ if (require.main === module) {
const displayHost = HOST.includes(':') ? `[${HOST}]` : HOST;
const dashboardUrl = `http://${displayHost}:${PORT}`;
console.log(`\n ECC Capabilities → ${dashboardUrl}\n`);
try { const { spawn } = require('child_process'); const p = process.platform; const c = p === 'darwin' ? 'open' : p === 'win32' ? 'start' : 'xdg-open'; if (c === 'start') spawn('cmd', ['/c', 'start', dashboardUrl], { stdio: 'ignore' }); else spawn(c, [dashboardUrl], { stdio: 'ignore' }); } catch { /* best-effort auto-open */ }
openDashboardInBrowser(dashboardUrl);
} });
}
+112 -14
View File
@@ -7,8 +7,11 @@ const { normalizeAgentTools } = require('./lib/agent-tools');
const TOOL_NAME_MAP = new Map([
['Read', 'read_file'],
['ReadFile', 'read_file'],
['NotebookRead', 'read_file'],
['Write', 'write_file'],
['Edit', 'replace'],
['MultiEdit', 'replace'],
['Bash', 'run_shell_command'],
['Grep', 'grep_search'],
['Glob', 'glob'],
@@ -33,7 +36,17 @@ function parseArgs(argv) {
return { help: true };
}
const positional = argv.filter(arg => !arg.startsWith('-'));
const positional = [];
for (const arg of argv) {
if (arg.startsWith('-')) {
// Reject rather than ignore. This script rewrites files in place, so
// silently discarding an unrecognized flag would let `--dry-run` — or any
// mistyped option — modify every installed agent and still exit 0.
throw new Error(`Unknown option: ${arg}`);
}
positional.push(arg);
}
if (positional.length > 1) {
throw new Error('Expected at most one agents directory argument');
}
@@ -54,13 +67,59 @@ function ensureDirectory(dirPath) {
}
}
function stripUnquotedYamlComment(value) {
let quote = null;
let escaped = false;
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (quote === '"') {
if (escaped) {
escaped = false;
} else if (character === '\\') {
escaped = true;
} else if (character === '"') {
quote = null;
}
continue;
}
if (quote === "'") {
if (character === "'") {
if (value[index + 1] === "'") {
index += 1;
} else {
quote = null;
}
}
continue;
}
if (character === '"' || character === "'") {
quote = character;
continue;
}
if (character === '#' && (index === 0 || /\s/.test(value[index - 1]))) {
return value.slice(0, index).trim();
}
}
return value.trim();
}
function parseToolList(line) {
const match = line.match(/^\s*tools\s*:\s*(.*)$/);
if (!match) {
return null;
}
return normalizeAgentTools(match[1]);
const rawValue = stripUnquotedYamlComment(match[1]);
return {
isEmptyScalar: rawValue === '',
tools: normalizeAgentTools(rawValue),
};
}
function adaptToolName(toolName) {
@@ -85,22 +144,51 @@ function formatToolLine(tools) {
}
function adaptFrontmatter(text) {
const match = text.match(/^---\n([\s\S]*?)\n---(\n|$)/);
// Match both LF and CRLF frontmatter delimiters while keeping the body slice
// completely untouched so mixed line endings in the body are preserved verbatim.
const match = text.match(/^---(\r?\n)([\s\S]*?)\r?\n---(\r?\n|$)/);
if (!match) {
return { text, changed: false };
}
const headerEol = match[1];
const trailingFenceEol = match[3];
const originalBody = text.slice(match[0].length);
let changed = false;
const updatedLines = [];
const lines = match[2].replace(/\r\n/g, '\n').split('\n');
for (const line of match[1].split('\n')) {
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
if (/^\s*color\s*:/.test(line)) {
changed = true;
continue;
}
const tools = parseToolList(line);
if (tools) {
const parsedTools = parseToolList(line);
let tools = parsedTools ? parsedTools.tools : null;
if (parsedTools && parsedTools.isEmptyScalar) {
const sequenceItems = [];
let lookahead = index;
while (lookahead + 1 < lines.length && /^(?:\s*#|\s*$|(?:\s*-\s+.*))/.test(lines[lookahead + 1])) {
lookahead += 1;
const itemMatch = lines[lookahead].match(/^\s*-\s+(.*)$/);
if (itemMatch) {
const cleanedItem = stripUnquotedYamlComment(itemMatch[1]);
if (cleanedItem) {
sequenceItems.push(cleanedItem);
}
}
}
if (sequenceItems.length > 0) {
index = lookahead;
changed = true;
tools = normalizeAgentTools(sequenceItems);
}
}
if (tools && tools.length > 0) {
const adaptedTools = [];
const seen = new Set();
@@ -127,8 +215,10 @@ function adaptFrontmatter(text) {
return { text, changed: false };
}
const adaptedHeader = `---${headerEol}${updatedLines.join(headerEol)}${headerEol}---${trailingFenceEol}`;
return {
text: `---\n${updatedLines.join('\n')}\n---${match[2]}${text.slice(match[0].length)}`,
text: `${adaptedHeader}${originalBody}`,
changed: true,
};
}
@@ -139,15 +229,19 @@ function adaptAgents(dirPath) {
let updated = 0;
let unchanged = 0;
for (const entry of fs.readdirSync(dirPath, { withFileTypes: true })) {
const prepared = [];
for (const entry of fs.readdirSync(dirPath, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
if (!entry.isFile() || !entry.name.endsWith('.md')) {
continue;
}
const filePath = path.join(dirPath, entry.name);
const filePath = path.join(dirPath, path.basename(entry.name));
const original = fs.readFileSync(filePath, 'utf8');
const adapted = adaptFrontmatter(original);
prepared.push({ filePath, adapted });
}
for (const { filePath, adapted } of prepared) {
if (adapted.changed) {
fs.writeFileSync(filePath, adapted.text);
updated += 1;
@@ -170,9 +264,13 @@ function main() {
console.log(`Updated ${result.updated} agent file(s); ${result.unchanged} already compatible`);
}
try {
main();
} catch (error) {
console.error(error.message);
process.exit(1);
if (require.main === module) {
try {
main();
} catch (error) {
console.error(error.message);
process.exit(1);
}
}
module.exports = { adaptFrontmatter };
+14 -16
View File
@@ -2,6 +2,7 @@
'use strict';
const { isHookEnabled } = require('../lib/hook-flags');
const { readStdinRaw } = require('./hook-input');
const {
buildPreToolUseAdditionalContext,
combineAdditionalContext,
@@ -72,21 +73,6 @@ const POST_BASH_HOOKS = [
},
];
function readStdinRaw() {
return new Promise(resolve => {
let raw = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => {
if (raw.length < MAX_STDIN) {
const remaining = MAX_STDIN - raw.length;
raw += chunk.substring(0, remaining);
}
});
process.stdin.on('end', () => resolve(raw));
process.stdin.on('error', () => resolve(raw));
});
}
function normalizeHookResult(previousRaw, output) {
if (typeof output === 'string' || Buffer.isBuffer(output)) {
return {
@@ -183,7 +169,19 @@ function runPostBash(rawInput) {
async function main() {
const mode = process.argv[2];
const raw = await readStdinRaw();
// The shared reader also settles on close and on an idle deadline, so a
// parent that never closes stdin cannot hang the dispatcher (#3665).
const { raw, truncated } = await readStdinRaw(process.stdin, { maxStdin: MAX_STDIN });
if (truncated) {
// Safety hooks cannot inspect a partial request, so pre-Bash fails closed.
// Post-Bash has nothing left to block and must not echo a partial payload.
const blocking = mode !== 'post';
process.stderr.write(
`[Hook] incomplete stdin for bash-hook-dispatcher ${blocking ? 'pre' : 'post'}; ` +
(blocking ? 'blocking because safety checks require the complete request\n' : 'skipping post-Bash hooks\n')
);
process.exit(blocking ? 2 : 0);
}
const result = mode === 'post'
? runPostBash(raw)
+23 -4
View File
@@ -157,9 +157,28 @@ function run(inputOrRaw, options = {}) {
}
const input = parseInput(inputOrRaw);
const filePath = input?.tool_input?.file_path || input?.tool_input?.file || '';
if (!filePath) return { exitCode: 0 };
for (const filePath of targetPaths(input?.tool_input)) {
const blocked = checkTarget(filePath);
if (blocked) return blocked;
}
return { exitCode: 0 };
}
/**
* Every path the tool call would write. A MultiEdit entry may carry its own
* `file_path`; one without falls back to the top-level path, the same rule
* GateGuard applies (#3761). Checking only the top-level path let a batch
* edit an existing config through `edits[].file_path`.
*/
function targetPaths(toolInput) {
const shared = toolInput?.file_path || toolInput?.file || '';
const edits = Array.isArray(toolInput?.edits) ? toolInput.edits : [];
const entryPaths = edits.map(edit => (edit && typeof edit === 'object' ? edit.file_path : undefined));
const candidates = [shared, ...entryPaths].filter(p => typeof p === 'string' && p);
return [...new Set(candidates)];
}
function checkTarget(filePath) {
const basename = path.basename(filePath);
// Match case-insensitively. Every PROTECTED_FILES entry is lowercase, and on
// case-insensitive filesystems (macOS APFS/HFS+, Windows NTFS) a write to
@@ -194,7 +213,7 @@ function run(inputOrRaw, options = {}) {
}
if (!exists) {
return { exitCode: 0 };
return null;
}
return {
@@ -207,7 +226,7 @@ function run(inputOrRaw, options = {}) {
};
}
return { exitCode: 0 };
return null;
}
module.exports = { run };
+159 -32
View File
@@ -179,6 +179,27 @@ function getExtraDestructiveRegex() {
// `**` across segments, `?` a single char.
let exemptCacheKey = null;
let exemptCacheRegexes = null;
function exemptGlobRegex(glob) {
let source = '';
for (let index = 0; index < glob.length; index++) {
const char = glob[index];
if (char === '*' && glob[index + 1] === '*') {
index++;
if (glob[index + 1] === '/') {
source += '(?:.*/)?';
index++;
} else source += '.*';
} else if (char === '*') source += '[^/]*';
else if (char === '?') source += '[^/]';
else source += char.replace(/[.+^${}()|[\]\\]/g, '\\$&');
}
try {
return new RegExp(`^${source}$`);
} catch (_) {
return null;
}
}
function getExemptMatchers() {
const raw = process.env.GATEGUARD_EXEMPT_GLOBS || '';
if (raw === exemptCacheKey) {
@@ -187,42 +208,59 @@ function getExemptMatchers() {
exemptCacheKey = raw;
exemptCacheRegexes = raw
.split(',')
.map(s => normalizeForMatch(s.trim()))
.map(s => s.trim().replace(/\\/g, '/'))
.filter(Boolean)
.map(glob => {
let source = '';
for (let index = 0; index < glob.length; index++) {
const char = glob[index];
if (char === '*' && glob[index + 1] === '*') {
index++;
if (glob[index + 1] === '/') {
source += '(?:.*/)?';
index++;
} else source += '.*';
} else if (char === '*') source += '[^/]*';
else if (char === '?') source += '[^/]';
else source += char.replace(/[.+^${}()|[\]\\]/g, '\\$&');
}
try {
return { regex: new RegExp(`^${source}$`), absolute: path.posix.isAbsolute(glob) || path.win32.isAbsolute(glob) };
} catch (_) {
return null;
}
.map(written => {
const glob = normalizeForMatch(written);
const regex = exemptGlobRegex(glob);
return regex ? { written, regex, absolute: path.posix.isAbsolute(glob) || path.win32.isAbsolute(glob) } : null;
})
.filter(Boolean);
return exemptCacheRegexes;
}
function matchesExemptGlob(target, projectRoot, paths, absoluteRegexFor = matcher => matcher.regex) {
const relative = paths.relative(projectRoot, target);
const contained = relative !== '..' && !relative.startsWith(`..${paths.sep}`) && !paths.isAbsolute(relative);
return getExemptMatchers().some(matcher => {
if (!matcher.absolute) return contained && matcher.regex.test(normalizeForMatch(relative));
const regex = absoluteRegexFor(matcher);
return Boolean(regex) && regex.test(normalizeForMatch(target));
});
}
// An absolute glob as it reads once its literal leading directories are
// symlink-resolved (`/tmp/...` is `/private/tmp/...` on macOS). Null when that
// prefix has no real location.
function realAbsoluteGlobRegex(glob, isWin) {
const segments = glob.split('/');
const wild = segments.findIndex(segment => /[*?]/.test(segment));
const literal = wild === -1 ? segments.length - 1 : wild;
const prefix = segments.slice(0, literal).join('/') || '/';
const realPrefix = targetClass().realLocationOf(isWin ? prefix.replace(/\//g, '\\') : prefix, isWin);
if (!realPrefix) return null;
const rest = segments.slice(literal).join('/');
return exemptGlobRegex(normalizeForMatch(`${realPrefix.replace(/[\\/]$/, '')}/${rest}`));
}
// The path as written and its real location must both match: a symlink inside
// an exempt tree does not exempt its target. See docs/gateguard/design-notes.md#exempt-globs
function isExemptPath(filePath, data) {
const projectRoot = process.env.CLAUDE_PROJECT_DIR || data.cwd || process.cwd();
if (typeof projectRoot !== 'string' || typeof filePath !== 'string') return false;
const paths = targetClass().WINDOWS_PATH_PATTERN.test(projectRoot) ? path.win32 : path.posix;
const isWin = targetClass().WINDOWS_PATH_PATTERN.test(projectRoot);
const paths = isWin ? path.win32 : path.posix;
if (!paths.isAbsolute(projectRoot)) return false;
const target = paths.resolve(projectRoot, filePath);
const relative = paths.relative(projectRoot, target);
const contained = relative !== '..' && !relative.startsWith(`..${paths.sep}`) && !paths.isAbsolute(relative);
return getExemptMatchers().some(({ regex, absolute }) =>
absolute ? regex.test(normalizeForMatch(target)) : contained && regex.test(normalizeForMatch(relative))
if (!matchesExemptGlob(target, projectRoot, paths)) return false;
// A Windows-style path has no real location on a POSIX host (and vice versa).
if (isWin !== (process.platform === 'win32')) return true;
const realTarget = targetClass().realLocationOf(target, isWin);
if (!realTarget) return false;
if (realTarget === target) return true;
const realRoot = targetClass().realLocationOf(projectRoot, isWin) || projectRoot;
return matchesExemptGlob(realTarget, realRoot, paths, matcher =>
matcher.regex.test(normalizeForMatch(realTarget)) ? matcher.regex : realAbsoluteGlobRegex(matcher.written, isWin)
);
}
@@ -514,9 +552,77 @@ const SUDO_VALUE_FLAGS = new Set([
'--type',
'-T',
'--command-timeout',
'-R',
'--chroot',
'-a',
'--auth-type',
'-c',
'--login-class',
]);
const DOAS_VALUE_FLAGS = new Set(['-u', '-C']);
const DOAS_VALUE_FLAGS = new Set(['-u', '-C', '-a']);
// Option letters that take no value (sudo's getopt string
// "+Aa:BbC:c:D:Eeg:Hh::iKklNnPp:R:r:SsT:t:U:u:Vv", doas's "+a:C:Lnsu:").
const SUDO_BOOLEAN_FLAGS = new Set('ABbEeHiKklNnPSsVv'.split('').map(c => `-${c}`));
const DOAS_BOOLEAN_FLAGS = new Set(['-L', '-n', '-s']);
// Modes that list, validate, edit, check config or report instead of running
// the command operand: `sudo -l rm -rf x` only checks whether rm is permitted.
const SUDO_NON_EXEC_FLAGS = new Set([
'-l', '--list', '-v', '--validate', '-K', '--remove-timestamp', '-V', '--version', '-e', '--edit',
'--help',
]);
const DOAS_NON_EXEC_FLAGS = new Set(['-L', '-C']);
/**
* True when a privilege-wrapper option puts it in a mode that does not run the
* command operand. A short cluster is read left to right: a value flag ends it
* (the rest is its value, so `-ul` is user `l` and `-R/live` is a chroot), and
* an unknown letter ends it too, so an unrecognized option never turns a
* command into a non-executing one.
*/
function isNonExecPrivilegeOption(arg, valueFlags, nonExecFlags, booleanFlags) {
if (arg.startsWith('--')) {
const separator = arg.indexOf('=');
return nonExecFlags.has(separator === -1 ? arg : arg.slice(0, separator));
}
for (let i = 1; i < arg.length; i += 1) {
const name = `-${arg[i]}`;
if (nonExecFlags.has(name)) return true;
if (valueFlags.has(name) || !booleanFlags.has(name)) return false;
}
return false;
}
// Every sudo long option (parse_args.c sudo_long_opts). getopt_long accepts a
// unique prefix, so `--use root` is `--user root` and `--chro /x` is `--chroot /x`.
const SUDO_LONG_OPTIONS = [
'--background', '--preserve-env', '--edit', '--set-home', '--login', '--remove-timestamp',
'--list', '--preserve-groups', '--shell', '--other-user', '--validate', '--askpass',
'--auth-type', '--bell', '--close-from', '--login-class', '--chdir', '--group', '--help',
'--host', '--reset-timestamp', '--no-update', '--non-interactive', '--prompt', '--chroot',
'--role', '--stdin', '--command-timeout', '--type', '--user', '--version',
];
/**
* Expand a unique sudo long-option prefix to its full name, keeping any
* attached `=value`. Exact names, ambiguous prefixes (sudo rejects those with
* a usage error and runs nothing) and non-long arguments come back unchanged.
*/
function canonicalSudoLongOption(arg) {
if (!arg.startsWith('--') || arg === '--') return arg;
const separator = arg.indexOf('=');
const name = separator === -1 ? arg : arg.slice(0, separator);
if (SUDO_LONG_OPTIONS.includes(name)) return arg;
const matches = SUDO_LONG_OPTIONS.filter(option => option.startsWith(name));
if (matches.length !== 1) return arg;
return separator === -1 ? matches[0] : `${matches[0]}${arg.slice(separator)}`;
}
// sudo accepts VAR=value environment assignments between its options
// (parse_args.c is_envar: not starting with '/' or '=', containing '=').
function isSudoEnvAssignment(arg) {
return arg[0] !== '/' && arg[0] !== '=' && arg.includes('=');
}
const EXEC_VALUE_FLAGS = new Set(['-a']);
const ENV_VALUE_FLAGS = new Set(['-u', '--unset', '-C', '--chdir', '-a', '--argv0', '-S', '--split-string']);
const SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
@@ -792,14 +898,21 @@ function unwrapLeadWrappers(tokens, allowShellBuiltins = true, allowDdLaunchers
allowShellBuiltins = false;
allowAssignments = true;
const valueFlags = base === 'sudo' ? SUDO_VALUE_FLAGS : DOAS_VALUE_FLAGS;
const nonExecFlags = base === 'sudo' ? SUDO_NON_EXEC_FLAGS : DOAS_NON_EXEC_FLAGS;
const booleanFlags = base === 'sudo' ? SUDO_BOOLEAN_FLAGS : DOAS_BOOLEAN_FLAGS;
index += 1;
while (index < argv.length) {
const flag = argv[index];
const flag = base === 'sudo' ? canonicalSudoLongOption(argv[index]) : argv[index];
if (flag === '--') {
index += 1;
break;
}
if (base === 'sudo' && isSudoEnvAssignment(flag)) {
index += 1;
continue;
}
if (flag === '-' || !flag.startsWith('-')) break;
if (isNonExecPrivilegeOption(flag, valueFlags, nonExecFlags, booleanFlags)) return true;
const option = wrapperValueOption(flag, valueFlags);
index += option && option.value === undefined ? 2 : 1;
}
@@ -926,8 +1039,7 @@ function isDestructiveQuoteAware(raw, depth = 0) {
for (const body of collectExecutableBodies(executable)) {
for (const tokens of quoteAwareSegments(body)) {
if (tokens.length === 0) continue;
if (isDestructiveRm(tokens)) return true;
if (isDestructiveGit(tokens)) return true;
if (isDestructiveRmOrGit(tokens)) return true;
if (isDestructiveDd(tokens)) return true;
if (isDestructiveSqlClient(tokens)) return true;
if (isDestructiveFindExec(tokens)) return true;
@@ -986,6 +1098,23 @@ function isDestructiveDd(tokens, allowShellBuiltins = true) {
return commandBasename(argv[0]) === 'dd' && argv.slice(1).some(operand => /^(?:if|of)=/i.test(operand));
}
/**
* rm/Git check on the segment as written and on the command it actually runs.
* Both detectors key on argv[0], so `sudo rm -rf build`, `command rm -rf build`
* and `env git reset --hard` read as calls to the wrapper and passed (#2832).
* unwrapLeadWrappers resolves the wrapped command word the same way the dd
* and `sh -c` paths already do. Argument text is left alone: in
* `echo sudo rm -rf x` the resolved command is still `echo`.
*
* @param {string[]} tokens
* @returns {boolean}
*/
function isDestructiveRmOrGit(tokens) {
if (isDestructiveRm(tokens) || isDestructiveGit(tokens)) return true;
const argv = unwrapLeadWrappers(tokens, true, true);
return argv.length > 0 && (isDestructiveRm(argv) || isDestructiveGit(argv));
}
/**
* Detect `rm` invocations that recursively force-delete files. Handles
* combined (`-rf`, `-fr`, `-Rf`) and split (`-r -f`) flag forms.
@@ -1392,9 +1521,7 @@ function isDestructiveBash(command) {
const stripped = stripQuotedStrings(segment);
if (DESTRUCTIVE_SQL.test(stripped)) return true;
if (extra && extra.test(stripped)) return true;
const tokens = tokenize(segment);
if (isDestructiveRm(tokens)) return true;
if (isDestructiveGit(tokens)) return true;
if (isDestructiveRmOrGit(tokenize(segment))) return true;
}
// Quote-aware pass: closes the quoted-command-word, newline-separator,
+88 -3
View File
@@ -3,6 +3,11 @@
const { StringDecoder } = require('string_decoder');
const DEFAULT_MAX_STDIN = 1024 * 1024;
// Stay below the shortest per-hook timeout in hooks/hooks.json (5 s) so a
// stalled stdin is settled by the reader, not by the harness killing the hook.
const DEFAULT_STDIN_IDLE_TIMEOUT_MS = 3000;
// setTimeout fires after 1 ms for any delay above this, so clamp to it.
const MAX_STDIN_IDLE_TIMEOUT_MS = 2 ** 31 - 1;
function resolveMaxStdin(value, options = {}) {
const writeDiagnostic = options.writeDiagnostic || (() => {});
@@ -24,8 +29,46 @@ function resolveMaxStdin(value, options = {}) {
return parsed;
}
function resolveStdinIdleTimeout(value, options = {}) {
const writeDiagnostic = options.writeDiagnostic || (() => {});
// Number(' ') is 0, which would silently disable the deadline.
const text = value === undefined ? '' : String(value).trim();
if (text === '') return DEFAULT_STDIN_IDLE_TIMEOUT_MS;
const parsed = Number(text);
if (!Number.isSafeInteger(parsed) || parsed < 0) {
writeDiagnostic(
'[Hook] ECC_HOOK_INPUT_IDLE_TIMEOUT_MS must be a non-negative safe integer; using the 3000 ms default\n'
);
return DEFAULT_STDIN_IDLE_TIMEOUT_MS;
}
if (parsed > MAX_STDIN_IDLE_TIMEOUT_MS) {
writeDiagnostic(
`[Hook] ECC_HOOK_INPUT_IDLE_TIMEOUT_MS exceeds the ${MAX_STDIN_IDLE_TIMEOUT_MS} ms timer maximum; clamping to it\n`
);
return MAX_STDIN_IDLE_TIMEOUT_MS;
}
return parsed;
}
// A JSON object cannot be the prefix of a longer valid document, so a payload
// that already parses as one is complete even though EOF never arrived.
function isCompleteJsonObject(text) {
try {
const parsed = JSON.parse(text);
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed);
} catch {
return false;
}
}
function readStdinRaw(stream = process.stdin, options = {}) {
const maxStdin = options.maxStdin || DEFAULT_MAX_STDIN;
const writeDiagnostic = options.writeDiagnostic
|| (stream === process.stdin ? message => process.stderr.write(message) : () => {});
const idleTimeoutMs = options.idleTimeoutMs === undefined
? resolveStdinIdleTimeout(process.env.ECC_HOOK_INPUT_IDLE_TIMEOUT_MS, { writeDiagnostic })
: options.idleTimeoutMs;
const decoder = new StringDecoder('utf8');
let raw = '';
let acceptedBytes = 0;
@@ -33,7 +76,20 @@ function readStdinRaw(stream = process.stdin, options = {}) {
return new Promise(resolve => {
let settled = false;
stream.on('data', chunk => {
let idleTimer = null;
const clearIdleTimer = () => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = null;
};
const armIdleTimer = () => {
if (!(idleTimeoutMs > 0)) return;
clearIdleTimer();
idleTimer = setTimeout(onIdleTimeout, idleTimeoutMs);
// Never keep the process alive just to wait for this deadline.
if (typeof idleTimer.unref === 'function') idleTimer.unref();
};
const onData = chunk => {
armIdleTimer();
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
if (typeof options.onChunk === 'function') options.onChunk(buffer);
const remaining = Math.max(0, maxStdin - acceptedBytes);
@@ -43,10 +99,11 @@ function readStdinRaw(stream = process.stdin, options = {}) {
acceptedBytes += accepted.length;
}
if (accepted.length < buffer.length) truncated = true;
});
};
const finish = () => {
if (settled) return;
settled = true;
clearIdleTimer();
if (!truncated) raw += decoder.end();
resolve({ raw, truncated });
};
@@ -55,16 +112,44 @@ function readStdinRaw(stream = process.stdin, options = {}) {
truncated = true;
finish();
};
// The writer kept stdin open without sending EOF (#3665). Stop reading
// and release the stream so a held-open pipe cannot keep the hook alive.
// Anything short of a complete JSON object is marked incomplete so safety
// hooks remain fail closed.
function onIdleTimeout() {
idleTimer = null;
if (settled) return;
stream.removeListener('data', onData);
if (typeof stream.pause === 'function') stream.pause();
if (!truncated) {
const pending = raw + decoder.end();
if (isCompleteJsonObject(pending)) {
raw = pending;
settled = true;
resolve({ raw, truncated: false });
return;
}
raw = pending;
}
writeDiagnostic(
`[Hook] stdin stayed open without EOF for ${idleTimeoutMs} ms; treating the hook input as incomplete\n`
);
finishIncomplete();
}
stream.on('data', onData);
stream.once('end', finish);
// A transport error or premature close can leave a syntactically plausible
// prefix behind. Mark it incomplete so safety hooks remain fail closed.
stream.once('error', finishIncomplete);
stream.once('close', finishIncomplete);
armIdleTimer();
});
}
module.exports = {
DEFAULT_MAX_STDIN,
DEFAULT_STDIN_IDLE_TIMEOUT_MS,
readStdinRaw,
resolveMaxStdin
resolveMaxStdin,
resolveStdinIdleTimeout
};
+8 -4
View File
@@ -17,9 +17,14 @@ const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-inpu
const { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output');
const { createHookContextScanner } = require('./hook-input-limits');
const FAIL_CLOSED_ON_TRUNCATION_HOOKS = new Set([
const GATEGUARD_HOOKS = new Set([
'pre:bash:gateguard-fact-force',
'pre:powershell:gateguard-fact-force',
'pre:edit-write:gateguard-fact-force',
'pre:edit-write:gateguard-fact-force'
]);
const FAIL_CLOSED_ON_TRUNCATION_HOOKS = new Set([
...GATEGUARD_HOOKS,
'pre:mcp-health-check'
]);
@@ -119,8 +124,7 @@ function resolveLegacySpawnStdout(result) {
function truncatedInputResult(hookId, maxStdin) {
if (!FAIL_CLOSED_ON_TRUNCATION_HOOKS.has(hookId)) return null;
if (hookId === 'pre:powershell:gateguard-fact-force'
|| hookId === 'pre:edit-write:gateguard-fact-force') {
if (GATEGUARD_HOOKS.has(hookId)) {
const gateGuardValue = String(process.env.ECC_GATEGUARD || '').trim().toLowerCase();
const legacyDisabled = String(process.env.GATEGUARD_DISABLED || '').trim() === '1';
if (legacyDisabled || ['0', 'false', 'off', 'disabled', 'disable'].includes(gateGuardValue)) {
+7 -9
View File
@@ -562,9 +562,8 @@ function summarizeOutput(toolOutput) {
}
function buildActivityRow(input, env = process.env) {
// Same env-var-reliance bug as the session id below: Claude Code doesn't
// set CLAUDE_HOOK_EVENT_NAME for hook subprocesses either. Real hook stdin
// payloads carry hook_event_name as a JSON field -- prefer that.
// Claude Code does not set CLAUDE_HOOK_EVENT_NAME for hook subprocesses.
// Real hook stdin payloads carry hook_event_name as a JSON field.
const hookEvent = String(
input?.hook_event_name || env.CLAUDE_HOOK_EVENT_NAME || ''
).trim();
@@ -573,12 +572,11 @@ function buildActivityRow(input, env = process.env) {
}
const toolName = String(input?.tool_name || '').trim();
// Claude Code does not set CLAUDE_SESSION_ID as an environment variable for
// hook subprocesses -- the session id is only available in the hook's own
// stdin JSON payload. Prefer that; keep the env vars as a fallback for any
// caller that does set them. Sanitized the same way as the sibling hooks
// (cost-tracker.js, ecc-context-monitor.js, ecc-metrics-bridge.js,
// gateguard-fact-force.js) that already use this exact fallback order.
// The payload identifies the actual harness conversation. Preserve it ahead
// of inherited environment IDs, which may belong to a parent or concurrent
// session. Correlating that conversation with a native ECC session requires
// an explicit binding, not an ownership guess from the environment.
// Sanitize candidates separately so invalid values retain safe fallbacks.
const sessionId =
sanitizeSessionId(input?.session_id) ||
sanitizeSessionId(env.ECC_SESSION_ID) ||
+13 -8
View File
@@ -8,6 +8,7 @@
const {
resolveProjectContext,
getAliasContexts,
removeSessionLease,
listSessionLeases,
stopObserverForContext,
@@ -30,17 +31,21 @@ function run(rawInput) {
try {
const observerContext = resolveProjectContext();
removeSessionLease(observerContext, sessionId);
const remainingLeases = listSessionLeases(observerContext);
// Leases from sessions that started before a remote was added sit under the root's older ids.
const contexts = [observerContext, ...getAliasContexts(observerContext)];
for (const context of contexts) removeSessionLease(context, sessionId);
const remainingLeases = contexts.reduce((count, context) => count + listSessionLeases(context).length, 0);
if (remainingLeases.length === 0) {
if (stopObserverForContext(observerContext)) {
log(`Stopped observer for project ${observerContext.projectId} after final session lease ended`);
} else {
log(`No running observer to stop for project ${observerContext.projectId}`);
if (remainingLeases === 0) {
for (const context of contexts) {
if (stopObserverForContext(context)) {
log(`Stopped observer for project ${context.projectId} after final session lease ended`);
} else if (context === observerContext) {
log(`No running observer to stop for project ${context.projectId}`);
}
}
} else {
log(`Retained observer for project ${observerContext.projectId}; ${remainingLeases.length} session lease(s) remain`);
log(`Retained observer for project ${observerContext.projectId}; ${remainingLeases} session lease(s) remain`);
}
} catch (err) {
log(`Observer cleanup skipped: ${err.message}`);
+2 -2
View File
@@ -221,7 +221,7 @@ function sessionShortId(transcriptPath) {
/**
* Decide whether to call LLM for a richer summary.
* Triggers: context remaining < 20%, or every 50 user messages as a baseline.
* Triggers: summary budget remaining < 20%, or every 50 user messages as a baseline.
*/
function maybeGenerateLlmSummary(transcriptPath, summary) {
const contextPct = getContextRemainingPct(transcriptPath);
@@ -231,7 +231,7 @@ function maybeGenerateLlmSummary(transcriptPath, summary) {
const isPeriodicTurn = summary.totalMessages > 0 && summary.totalMessages % safeInterval === 0;
if (!isContextLow && !isPeriodicTurn) return null;
log(`[SessionEnd] LLM summary triggered (context: ${contextPct ?? 'unknown'}%, messages: ${summary.totalMessages})`);
log(`[SessionEnd] LLM summary triggered (summary budget: ${contextPct ?? 'unknown'}%, messages: ${summary.totalMessages})`);
let skipped = false;
const llmSummary = generateSessionSummary(transcriptPath, {
onSkip: reason => {
+30 -14
View File
@@ -113,6 +113,23 @@ function treeDistance(a, b) {
return clamp01((da - lca + (db - lca)) / (da + db));
}
function mergeLineRanges(ranges) {
const sorted = ranges
.map(([start, end]) => [Math.min(start, end), Math.max(start, end)])
.filter(([start, end]) => start <= end)
.sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of sorted) {
const previous = merged[merged.length - 1];
if (previous && start <= previous[1] + 1) {
merged[merged.length - 1] = [previous[0], Math.max(previous[1], end)];
} else {
merged.push([start, end]);
}
}
return merged;
}
/**
* Line-range overlap as the overlap COEFFICIENT (Szymkiewicz–Simpson):
* |A ∩ B| / min(|A|, |B|). This is the right collision measure — if one agent's
@@ -124,21 +141,20 @@ function lineRangeOverlap(rangesA, rangesB) {
const a = Array.isArray(rangesA) ? rangesA : [];
const b = Array.isArray(rangesB) ? rangesB : [];
if (a.length === 0 || b.length === 0) return 1; // file-level edit ⇒ whole-file overlap
const covered = ranges => {
const set = new Set();
for (const [s, e] of ranges) {
const lo = Math.min(s, e);
const hi = Math.max(s, e);
for (let i = lo; i <= hi; i += 1) set.add(i);
}
return set;
};
const ca = covered(a);
const cb = covered(b);
if (ca.size === 0 || cb.size === 0) return 0;
const ca = mergeLineRanges(a);
const cb = mergeLineRanges(b);
const size = ranges => ranges.reduce((total, [start, end]) => total + end - start + 1, 0);
const minSize = Math.min(size(ca), size(cb));
if (minSize === 0) return 0;
let inter = 0;
for (const v of ca) if (cb.has(v)) inter += 1;
return inter / Math.min(ca.size, cb.size);
let i = 0;
let j = 0;
while (i < ca.length && j < cb.length) {
inter += Math.max(0, Math.min(ca[i][1], cb[j][1]) - Math.max(ca[i][0], cb[j][0]) + 1);
if (ca[i][1] < cb[j][1]) i += 1;
else j += 1;
}
return inter / minSize;
}
function jaccard(setA, setB) {
+21 -1
View File
@@ -1,9 +1,29 @@
'use strict';
function hasSingleSurroundingQuotePair(trimmed, quote) {
let escaped = false;
for (let index = 1; index < trimmed.length - 1; index += 1) {
const character = trimmed[index];
if (escaped) {
escaped = false;
} else if (character === '\\') {
escaped = true;
} else if (character === quote) {
return false;
}
}
return !escaped;
}
function stripSurroundingQuotes(value) {
const trimmed = value.trim();
const quote = trimmed[0];
if ((quote === '"' || quote === "'") && trimmed.endsWith(quote)) {
if (
trimmed.length >= 2
&& (quote === '"' || quote === "'")
&& trimmed.endsWith(quote)
&& hasSingleSurroundingQuotePair(trimmed, quote)
) {
return trimmed.slice(1, -1).trim();
}
return trimmed;
+15 -10
View File
@@ -8,6 +8,8 @@
*/
const DONE_STATUSES = new Set(['done', 'closed', 'resolved', 'merged', 'cancelled']);
// Only explicitly admitted work may be newly claimed.
const CLAIMABLE_STATUSES = new Set(['open', 'ready']);
const PRIORITY_RANK = { critical: 0, high: 1, urgent: 1, medium: 2, normal: 2, low: 3 };
// Kanban lanes the board renders, and the canonical status each maps to on a move.
@@ -21,11 +23,7 @@ const VALID_LANES = new Set(Object.keys(LANE_TO_STATUS));
const VALID_ASSIGNEE_KINDS = new Set(['agent', 'human']);
function isOpenStatus(status) {
return !DONE_STATUSES.has(
String(status || '')
.trim()
.toLowerCase()
);
return CLAIMABLE_STATUSES.has(String(status || '').trim().toLowerCase());
}
function priorityRank(priority) {
@@ -44,8 +42,9 @@ function selectClaimTarget(store, { id } = {}) {
}
return item;
}
const { items } = store.listWorkItems({ limit: 100 });
return items.filter(item => !item.owner && isOpenStatus(item.status)).sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority))[0] || null;
// The native SQL query filters all eligible items before choosing the
// highest-priority claim; a newer 100-item slice can hide older READY work.
return store.getNextClaimableWorkItem();
}
/**
@@ -65,13 +64,19 @@ function claimWorkItem(store, { id, owner, assigneeKind, sessionId, status } = {
if (!target) {
return { claimed: false, reason: 'no-unassigned-open-items' };
}
if (!isOpenStatus(target.status)) {
throw new Error(`Work item ${target.id} is already done; cannot claim.`);
}
if (target.owner) {
if (target.owner !== owner) {
throw new Error(`Work item ${target.id} is already owned by ${target.owner}; cannot claim.`);
}
// Repeating an active claim by the same owner is idempotent.
if (['running', 'claimed', 'in-progress'].includes(String(target.status).trim().toLowerCase())) {
return { claimed: true, item: target };
}
}
if (!isOpenStatus(target.status)) {
throw new Error(`Work item ${target.id} is not READY; cannot claim.`);
}
if (target.owner) {
return { claimed: true, item: target };
}
const metadata = { ...(target.metadata || {}) };
+5 -4
View File
@@ -4,8 +4,8 @@ const fs = require('fs');
const DEFAULT_TRANSCRIPT_TAIL_BYTES = 256 * 1024;
/** Last `tailBytes` of a file as UTF-8 text, with whether earlier bytes were skipped; null when unreadable. */
function readFileTail(filePath, tailBytes) {
/** Last `tailBytes` as UTF-8 text; optionally include the raw byte length. Null when unreadable. */
function readFileTail(filePath, tailBytes, options = {}) {
let fd;
try {
fd = fs.openSync(filePath, 'r');
@@ -18,14 +18,15 @@ function readFileTail(filePath, tailBytes) {
const start = Math.max(0, size - tailBytes);
const length = size - start;
if (length <= 0) {
return { text: '', truncated: false };
return { text: '', truncated: false, ...(options.includeByteLength ? { byteLength: 0 } : {}) };
}
const buffer = Buffer.alloc(length);
const bytesRead = fs.readSync(fd, buffer, 0, length, start);
return {
text: buffer.toString('utf8', 0, bytesRead),
truncated: start > 0
truncated: start > 0,
...(options.includeByteLength ? { byteLength: bytesRead } : {})
};
} catch {
return null;
+18 -1
View File
@@ -398,6 +398,22 @@ function realTargetPath(resolved, paths) {
return realDir ? paths.join(realDir, paths.basename(resolved)) : null;
}
/**
* Real (symlink-resolved) location of an absolute host-style path; a missing
* file resolves through its nearest existing ancestor. Null when the path is
* not host-style or its real location cannot be determined.
*/
function realLocationOf(nativePath, isWin) {
try {
if (typeof nativePath !== 'string' || !isHostPathStyle(isWin)) return null;
const paths = isWin ? path.win32 : path.posix;
if (!paths.isAbsolute(nativePath)) return null;
return realTargetPath(paths.resolve(nativePath), paths);
} catch (_) {
return null;
}
}
function isMissingEntry(nativePath) {
try {
fs.lstatSync(nativePath);
@@ -453,5 +469,6 @@ module.exports = {
collapseGateDir,
isSensitiveTarget,
isSensitiveTargetFor,
isHardLinkedTargetFor
isHardLinkedTargetFor,
realLocationOf
};
+6 -3
View File
@@ -201,7 +201,8 @@ function addMatchingRuleOperations(operations, options) {
sourcePath,
sourceRelativePath,
destinationPath,
strategy: options.strategy || 'flatten-copy'
strategy: options.strategy || 'flatten-copy',
contentTransform: options.contentTransform,
})
);
}
@@ -391,7 +392,8 @@ function planAntigravityLegacyInstall(context) {
sourceRelativeDir: path.join('rules', 'common'),
destinationDir: path.join(targetRoot, 'rules'),
matcher: fileName => fileName.endsWith('.md'),
rename: fileName => `common-${fileName}`
rename: fileName => `common-${fileName}`,
contentTransform: 'antigravity-rule-frontmatter',
});
for (const language of context.languages) {
@@ -412,7 +414,8 @@ function planAntigravityLegacyInstall(context) {
sourceRelativeDir: path.join('rules', language),
destinationDir: path.join(targetRoot, 'rules'),
matcher: fileName => fileName.endsWith('.md'),
rename: fileName => `${language}-${fileName}`
rename: fileName => `${language}-${fileName}`,
contentTransform: 'antigravity-rule-frontmatter',
});
}
@@ -12,11 +12,27 @@ const SUPPORTED_SOURCE_PREFIXES = ['rules', 'commands', 'agents', 'skills'];
function supportsAntigravitySourcePath(sourceRelativePath) {
const normalizedPath = normalizeRelativePath(sourceRelativePath);
if (normalizedPath.split('/').includes('..')) return false;
return SUPPORTED_SOURCE_PREFIXES.some(prefix => (
normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`)
));
}
// Rule packs live one level down (rules/common/, rules/python/, ...). The
// top-level rules/README.md is installer documentation and stays inert.
function isRulePackMarkdown(sourceRelativePath) {
const segments = normalizeRelativePath(sourceRelativePath).split('/');
return segments[0] === 'rules'
&& segments.length >= 3
&& /\.md$/i.test(segments[segments.length - 1]);
}
function withAntigravityRuleTrigger(operation) {
return isRulePackMarkdown(operation.sourceRelativePath)
? { ...operation, contentTransform: 'antigravity-rule-frontmatter' }
: operation;
}
module.exports = createInstallTargetAdapter({
id: 'antigravity-project',
target: 'antigravity',
@@ -59,7 +75,7 @@ module.exports = createInstallTargetAdapter({
repoRoot,
sourceRelativePath: normalizedSourcePath,
destinationDir: path.join(targetRoot, 'rules'),
});
}).map(withAntigravityRuleTrigger);
}
if (
+49 -9
View File
@@ -1,17 +1,23 @@
const fs = require('fs');
const path = require('path');
const {
createInstallTargetAdapter,
createManagedOperation,
listRelativeFiles,
normalizeRelativePath,
} = require('./helpers');
// GitHub Copilot CLI discovers skills from `.github/skills/` and custom agents
// from `.github/agents/`. Explicitly declared package-manager helpers live in
// `.github/ecc/scripts/`, outside Copilot's discovery roots. ECC's hooks target
// Claude Code's event model, and commands rely on slash-command argument
// substitution Copilot does not provide, so neither is installed here.
const SUPPORTED_SOURCE_PREFIXES = ['agents', 'skills'];
// GitHub Copilot CLI discovers skills from `.github/skills/`, custom agents
// from `.github/agents/`, and path-specific instructions from
// `.github/instructions/**/*.instructions.md`. Rules are installed under
// `instructions/ecc/` with their Claude-style `paths:` frontmatter converted
// to Copilot's `applyTo:` glob list. Explicitly declared package-manager
// helpers live in `.github/ecc/scripts/`, outside Copilot's discovery roots.
// ECC's hooks target Claude Code's event model, and commands rely on
// slash-command argument substitution Copilot does not provide, so neither is
// installed here.
const SUPPORTED_SOURCE_PREFIXES = ['agents', 'skills', 'rules'];
const COPILOT_HELPER_PATHS = new Set([
'scripts/setup-package-manager.js',
'scripts/lib/package-manager.js',
@@ -35,7 +41,36 @@ function stripPrefix(normalizedPath, prefix) {
return normalizedPath === prefix ? '' : normalizedPath.slice(`${prefix}/`.length);
}
function planSourcePathOperations(module, sourceRelativePath, targetRoot) {
// Rules expand to per-file operations because the destination renames each
// Markdown file to `.instructions.md`, which a directory-level copy cannot
// express. `rules/README.md` documents the rule set and is not installed.
function planCopilotRuleOperations(module, normalizedSourcePath, targetRoot, repoRoot) {
const sourceRoot = path.join(repoRoot || '', normalizedSourcePath);
if (!repoRoot || !fs.existsSync(sourceRoot)) {
return [];
}
const prefix = stripPrefix(normalizedSourcePath, 'rules');
const sourceFiles = fs.statSync(sourceRoot).isDirectory()
? listRelativeFiles(sourceRoot).map(file => ({ source: `${normalizedSourcePath}/${file}`, relative: prefix ? `${prefix}/${file}` : file }))
: [{ source: normalizedSourcePath, relative: prefix }];
return sourceFiles
.filter(({ relative }) => /\.md$/i.test(relative) && !/(^|\/)README\.md$/i.test(relative))
.map(({ source, relative }) => createManagedOperation({
moduleId: module.id,
sourceRelativePath: source,
destinationPath: path.join(
targetRoot,
'instructions',
'ecc',
relative.replace(/\.md$/i, '.instructions.md')
),
contentTransform: 'copilot-rule-frontmatter',
}));
}
function planSourcePathOperations(module, sourceRelativePath, targetRoot, repoRoot) {
const normalizedSourcePath = normalizeRelativePath(sourceRelativePath);
if (hasPrefix(normalizedSourcePath, 'agents')) {
@@ -65,6 +100,10 @@ function planSourcePathOperations(module, sourceRelativePath, targetRoot) {
];
}
if (hasPrefix(normalizedSourcePath, 'rules')) {
return planCopilotRuleOperations(module, normalizedSourcePath, targetRoot, repoRoot);
}
if (COPILOT_HELPER_PATHS.has(normalizedSourcePath)) {
return [createManagedOperation({
moduleId: module.id,
@@ -85,7 +124,7 @@ module.exports = createInstallTargetAdapter({
supportsModule(module) {
// Selection gating stays permissive so modules that only act as dependency
// anchors (rules-core, commands-core, platform-configs) still resolve.
// planOperations() narrows the install to agents, skills and declared helpers. An
// planOperations() narrows the install to agents, skills, rules and declared helpers. An
// unsupported path contributes zero operations rather than skipping the
// module and every module that depends on it.
const paths = Array.isArray(module && module.paths) ? module.paths : [];
@@ -105,7 +144,8 @@ module.exports = createInstallTargetAdapter({
.flatMap(sourceRelativePath => planSourcePathOperations(
module,
sourceRelativePath,
targetRoot
targetRoot,
repoRoot
));
});
},
+5 -2
View File
@@ -37,8 +37,10 @@ function setWSLForTesting(value) {
const WINDOWS_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
// Compact WSL conversion snippet for inline resolvers embedded in commands and hooks.
// Uses 8 backslashes in regex source so it preserves shell escaping when inlined into `node -e "..."`.
const INLINE_WSL_CONVERSION = `try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var m=d.match(/^([A-Za-z]):[\\\\\\\\/]/);if(m){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).replace(/\\\\\\\\/g,'/')}}}}catch(_){}`;
// Contains no backslash: on native Windows, Claude Code runs hooks as `bash.exe -c "<command>"`
// and the extra argv/MSYS unescape layer collapses backslashes, which broke regex literals (#3746).
// The backslash separator is built with String.fromCharCode(92) instead.
const INLINE_WSL_CONVERSION = `try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var b=String.fromCharCode(92),m=d.match(/^([A-Za-z]):/);if(m&&(d.charAt(2)==='/'||d.charAt(2)===b)){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).split(b).join('/')}}}}catch(_){}`;
/**
* Convert a Windows path to a WSL path.
@@ -499,6 +501,7 @@ module.exports = {
createNamespacedFlatRuleOperations,
createRemappedOperation,
isForeignPlatformPath,
listRelativeFiles,
normalizeRelativePath,
planClaudeHooksOperations,
isWSL,
+18 -9
View File
@@ -1,9 +1,14 @@
'use strict';
const { normalizeAgentTools } = require('../agent-tools');
const TOOL_NAMES = Object.freeze({
Read: 'view_file',
ReadFile: 'view_file',
NotebookRead: 'view_file',
Write: 'write_to_file',
Edit: 'replace_file_content',
MultiEdit: 'replace_file_content',
Grep: 'grep_search',
Glob: 'find_by_name',
Bash: 'run_command',
@@ -18,7 +23,8 @@ const MODEL_NAMES = Object.freeze({
});
function splitFrontmatter(source, label) {
const match = String(source || '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
const raw = String(source || '');
const match = raw.match(/^---(\r?\n)([\s\S]*?)\r?\n---(\r?\n)/);
if (!match) {
throw new Error(`Cannot adapt Antigravity agent ${label}: missing YAML frontmatter`);
}
@@ -26,27 +32,27 @@ function splitFrontmatter(source, label) {
// Keep YAML loading behind the transform boundary. Public help commands load
// the installer graph without executing a transform, including in hermetic
// packed-artifact checks where runtime dependencies are intentionally absent.
const frontmatter = require('js-yaml').load(match[1]);
const frontmatter = require('js-yaml').load(match[2]);
if (!frontmatter || typeof frontmatter !== 'object' || Array.isArray(frontmatter)) {
throw new Error(`Cannot adapt Antigravity agent ${label}: frontmatter must be an object`);
}
return {
frontmatter,
body: source.slice(match[0].length),
body: raw.slice(match[0].length),
headerEol: match[1],
trailingFenceEol: match[3],
};
}
function normalizeToolNames(value) {
const names = Array.isArray(value) ? value : String(value || '').split(',');
return [...new Set(names
.map(name => String(name).trim())
return [...new Set(normalizeAgentTools(value)
.filter(name => Object.hasOwn(TOOL_NAMES, name))
.map(name => TOOL_NAMES[name]))];
}
function adaptAntigravityAgent(source, label = '<unknown>') {
const { frontmatter, body } = splitFrontmatter(source, label);
const { frontmatter, body, headerEol, trailingFenceEol } = splitFrontmatter(source, label);
const { color: _claudeColor, ...supportedFrontmatter } = frontmatter;
const adapted = { ...supportedFrontmatter };
if (Object.hasOwn(frontmatter, 'tools')) {
@@ -59,10 +65,13 @@ function adaptAntigravityAgent(source, label = '<unknown>') {
}
const serialized = require('js-yaml')
.dump(adapted, { lineWidth: -1, noRefs: true })
.trimEnd();
return `---\n${serialized}\n---\n${body}`;
.trimEnd()
.replace(/\n/g, headerEol);
return `---${headerEol}${serialized}${headerEol}---${trailingFenceEol}${body}`;
}
module.exports = {
adaptAntigravityAgent,
MODEL_NAMES,
TOOL_NAMES,
};
+101
View File
@@ -0,0 +1,101 @@
'use strict';
// Antigravity only attaches a workspace rule when its frontmatter declares an
// activation trigger (always_on, glob, model_decision or manual). ECC's
// canonical rules are written for Claude Code: common rules have no
// frontmatter and language rules scope themselves with a `paths:` list, which
// Antigravity does not read. Without a trigger the installed files sit in
// .agents/rules/ and are never loaded.
const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
const TRIGGER_LINE = /^trigger[ \t]*:(.*)$/m;
// Fallback for frontmatter that strict YAML cannot load: read the trigger
// line by hand and accept it only when it holds a nonblank value.
function hasNativeTriggerLine(yamlText) {
const match = yamlText.match(TRIGGER_LINE);
if (!match) {
return false;
}
let value = match[1].trim();
if (value.startsWith('#')) {
return false;
}
value = value.replace(/[ \t]+#.*$/, '');
const quoted = value.match(/^(['"])(.*)\1$/);
if (quoted) {
value = quoted[2];
}
return value.trim() !== '';
}
function parseFrontmatter(source, label) {
const match = source.match(FRONTMATTER_PATTERN);
if (!match) {
return null;
}
// Keep YAML loading behind the transform boundary, like the agent adapter:
// planning must stay free of runtime package dependencies.
let frontmatter;
try {
frontmatter = require('js-yaml').load(match[1]);
} catch (error) {
// Antigravity-native glob rules may hold unquoted `globs: **/*.ts`, which
// strict YAML rejects as an alias. Leave such rules untouched.
if (hasNativeTriggerLine(match[1])) {
return { native: true };
}
throw error;
}
if (frontmatter === null || frontmatter === undefined) {
return { frontmatter: {}, body: source.slice(match[0].length) };
}
if (typeof frontmatter !== 'object' || Array.isArray(frontmatter)) {
throw new Error(`Cannot adapt Antigravity rule ${label}: frontmatter must be an object`);
}
// A rule that already declares a usable trigger is Antigravity-native.
if (typeof frontmatter.trigger === 'string' && frontmatter.trigger.trim()) {
return { native: true };
}
return { frontmatter, body: source.slice(match[0].length) };
}
function toGlobList(paths) {
const values = Array.isArray(paths) ? paths : [paths];
return values
.map(value => String(value).trim())
.filter(Boolean);
}
function adaptAntigravityRule(source, label = '<unknown>') {
const text = String(source || '');
const parsed = parseFrontmatter(text, label);
if (!parsed) {
return `---\ntrigger: always_on\n---\n${text}`;
}
if (parsed.native) {
return text;
}
const { frontmatter, body } = parsed;
const globs = Object.hasOwn(frontmatter, 'paths') ? toGlobList(frontmatter.paths) : [];
// Quote globs: a plain YAML scalar cannot start with `*` (alias indicator).
const lines = globs.length > 0
? ['trigger: glob', `globs: ${JSON.stringify(globs.join(','))}`]
: ['trigger: always_on'];
if (typeof frontmatter.description === 'string' && frontmatter.description.trim()) {
lines.push(`description: ${JSON.stringify(frontmatter.description.trim())}`);
}
return `---\n${lines.join('\n')}\n---\n${body}`;
}
module.exports = {
adaptAntigravityRule,
};
+38 -13
View File
@@ -13,6 +13,7 @@ const {
assertHookConsentReady,
parseJsoncConfig,
getDisabledOpenCodePluginContent,
isInertOpenCodePluginStub,
getRecordedHookConsent,
getOpenCodeActivationPathKind,
getOpenCodeSourceActivationKind,
@@ -257,6 +258,32 @@ function isMcpConfigPath(filePath) {
return basename === '.mcp.json' || basename === 'mcp.json';
}
function withMcpMergeExclusions(plan, disabledServers) {
if (disabledServers.length === 0) {
return plan;
}
const filterOperation = operation => (
operation.kind === 'merge-json' && isMcpConfigPath(operation.destinationPath)
&& isPlainObject(operation.mergePayload)
&& isPlainObject(operation.mergePayload.mcpServers)
? {
...operation,
mergePayload: filterMcpConfig(operation.mergePayload, disabledServers).config,
}
: operation
);
// Writes, recovery checkpoints, and the final ownership ledger must use the
// same payload. Repair and uninstall later run without the install environment.
return {
...plan,
operations: plan.operations.map(filterOperation),
statePreview: {
...plan.statePreview,
operations: plan.statePreview.operations.map(filterOperation),
},
};
}
function assertSafeInstallOperation(plan, operation) {
if (!operation || typeof operation.destinationPath !== 'string') {
throw new Error('Refusing to apply install operation: missing destination path.');
@@ -446,9 +473,11 @@ function openCodeActivationCandidates(plan, previousOperations) {
return candidates;
}
function activationIsInactive(kind, operation, content) {
function activationIsInactive(kind, operation, content, strict = false) {
if (kind === 'plugin') {
return content.toString('utf8') === getDisabledOpenCodePluginContent();
// The final gate accepts only the V2-valid stub: the pre-fix one is inert but OpenCode rejects it.
return strict ? content.toString('utf8') === getDisabledOpenCodePluginContent()
: isInertOpenCodePluginStub(content);
}
const text = content.toString('utf8');
const relativePath = operation.sourceRelativePath || operation.destinationPath;
@@ -504,7 +533,7 @@ function assertOpenCodeHookDeactivationReady(plan, options = {}) {
const digest = content === null ? null : crypto.createHash('sha256').update(content).digest('hex');
snapshot.set(key, digest);
if (content === null) continue;
const inactive = activationIsInactive(kind, operation, content);
const inactive = activationIsInactive(kind, operation, content, options.requireInactive);
if (options.requireInactive) {
if (!inactive) {
throw new Error(`OpenCode hook activation remains active at ${operation.destinationPath}`);
@@ -712,7 +741,8 @@ function preflightQwenAgentOperations(plan) {
}
}
function previewInstallPlan(plan) {
function previewInstallPlan(rawPlan) {
const plan = withMcpMergeExclusions(rawPlan, parseDisabledMcpServers(process.env.ECC_DISABLED_MCPS));
preflightQwenAgentOperations(plan);
assertOpenCodeScriptBoundary(plan);
assertOpenCodeHookDeactivationReady(plan);
@@ -775,7 +805,9 @@ function applyInstallPlan(plan, dependencies = {}) {
: applyInstallPlanLocked(plan, dependencies, false);
}
function applyInstallPlanLocked(plan, dependencies = {}, settingsLockHeld = false) {
function applyInstallPlanLocked(rawPlan, dependencies = {}, settingsLockHeld = false) {
const disabledServers = parseDisabledMcpServers(process.env.ECC_DISABLED_MCPS);
const plan = withMcpMergeExclusions(rawPlan, disabledServers);
preflightQwenAgentOperations(plan);
const persistInstallState = dependencies.writeInstallState || writeInstallState;
const beforeInstallStateRead = dependencies.beforeInstallStateRead;
@@ -803,7 +835,6 @@ function applyInstallPlanLocked(plan, dependencies = {}, settingsLockHeld = fals
operations: migration.appliedOperations,
};
const preparedClaudeSettings = preflightClaudeSettingsOperations(appliedPlan);
const disabledServers = parseDisabledMcpServers(process.env.ECC_DISABLED_MCPS);
const linkIndex = buildLinkIndexForPlan(appliedPlan);
const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0;
const hookRemovalCount = appliedPlan.operations.filter(operation => (
@@ -885,17 +916,11 @@ function applyInstallPlanLocked(plan, dependencies = {}, settingsLockHeld = fals
throw new Error(`Missing merge payload for ${operation.destinationPath}`);
}
const filteredPayload = (
isMcpConfigPath(operation.destinationPath) && disabledServers.length > 0
)
? filterMcpConfig(payload, disabledServers).config
: payload;
const currentValue = readOptionalJsonObject(
operation.destinationPath,
'existing JSON config'
);
const mergedValue = deepMergeJson(currentValue, filteredPayload);
const mergedValue = deepMergeJson(currentValue, payload);
fs.writeFileSync(operation.destinationPath, formatJson(mergedValue), 'utf8');
writtenDestinations.add(operation.destinationPath);
continue;
+26 -1
View File
@@ -2,14 +2,33 @@
const { stripPluginNamespace } = require('./plugin-namespace');
const { adaptAntigravityAgent } = require('./antigravity-agent');
const { adaptAntigravityRule } = require('./antigravity-rule');
const { adaptCopilotAgent } = require('./copilot-agent');
const { adaptCopilotRule } = require('./copilot-rule');
const { disableOpenCodeHookPluginRegistration, getDisabledOpenCodePluginContent } = require('./hook-consent');
function rewriteCopilotWorkflowPaths(content, sourceRelativePath) {
if (!/\.md$/i.test(sourceRelativePath)) return content;
// Commands run from the installed project root. Rewrite only the supported
// helper entrypoint, leaving unrelated project scripts and URLs untouched.
return content.replace(/(^|[\s`"'(])scripts\/setup-package-manager\.js\b/g,
const isTddWorkflow = /(?:^|\/)skills\/tdd-workflow\/SKILL\.md$/i.test(sourceRelativePath.replace(/\\/g, '/'));
let projectedDetector = false;
let projected = content.replace(/(^[ \t]*```bash\r?\n)([\s\S]*?)(^[ \t]*```)/gm,
(block, opening, body, closing) => {
if (!isTddWorkflow || !/^\s*ECC_ROOT=/m.test(body)
|| !/^\s*node "\$ECC_ROOT\/scripts\/setup-package-manager\.js" --detect\s*$/m.test(body)) {
return block;
}
projectedDetector = true;
const indent = opening.match(/^[ \t]*/)[0];
const newline = opening.endsWith('\r\n') ? '\r\n' : '\n';
return `${opening}${indent}node .github/ecc/scripts/setup-package-manager.js --detect${newline}${closing}`;
});
if (projectedDetector) {
projected = projected.replace(/^([ \t]*)The resolution lines (?:locate|use)[^\r\n]*$/gm,
'$1This Copilot projection runs the detector from the managed .github/ecc/scripts/ closure in the project root. It preserves the project working directory and does not use Claude plugin or home-directory resolution.');
}
return projected.replace(/(^|[\s`"'(])scripts\/setup-package-manager\.js\b/g,
'$1.github/ecc/scripts/setup-package-manager.js');
}
@@ -101,12 +120,18 @@ function transformInstallContent(operation, content) {
if (operation.contentTransform === 'antigravity-agent-frontmatter') {
return adaptAntigravityAgent(content, operation.sourceRelativePath);
}
if (operation.contentTransform === 'antigravity-rule-frontmatter') {
return adaptAntigravityRule(content, operation.sourceRelativePath);
}
if (operation.contentTransform === 'copilot-agent-frontmatter') {
return rewriteCopilotWorkflowPaths(adaptCopilotAgent(content, operation.sourceRelativePath), operation.sourceRelativePath);
}
if (operation.contentTransform === 'copilot-workflow-paths') {
return rewriteCopilotWorkflowPaths(content, operation.sourceRelativePath);
}
if (operation.contentTransform === 'copilot-rule-frontmatter') {
return adaptCopilotRule(content, operation.sourceRelativePath);
}
if (operation.contentTransform === 'opencode-disable-ecc-hooks') {
return transformInstallContent({ ...operation, contentTransform: 'opencode-home-skills-path' },
disableOpenCodeHookPluginRegistration(content, operation.sourceRelativePath));
+141
View File
@@ -0,0 +1,141 @@
'use strict';
// GitHub Copilot loads path-specific instructions from
// `.github/instructions/**/*.instructions.md`, where the `applyTo` frontmatter
// key carries a comma-separated glob list. ECC rules express the same scoping
// with the Claude Code convention, a YAML `paths:` list, and rules without
// frontmatter apply to every prompt. The transform maps one model onto the
// other: `paths:` becomes `applyTo:`, and a rule without `paths` becomes
// `applyTo: "**"` so it keeps applying globally.
//
// Relative Markdown links between rules are renamed to their installed
// `.instructions.md` names; links that leave the rule set (docs, README,
// external URLs) are kept as-is.
//
// The transform is an allowlist: only `paths` is read, so frontmatter keys
// added to ECC rules later cannot silently leak into the Copilot copy.
const path = require('path');
const GLOBAL_APPLY_TO = '**';
function splitFrontmatter(source, label) {
const text = String(source || '');
// An immediately empty block (`---\n---\n`) never reaches the YAML loader:
// the delimiters are stripped and the rule is treated as global.
const emptyBlock = text.match(/^---\r?\n---\r?\n/);
if (emptyBlock) {
return { frontmatter: {}, body: text.slice(emptyBlock[0].length) };
}
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
if (!match) {
return null;
}
// A whitespace-only block is empty metadata, not a YAML document.
if (match[1].trim() === '') {
return { frontmatter: {}, body: text.slice(match[0].length) };
}
// Keep YAML loading behind the transform boundary. Public help commands load
// the installer graph without executing a transform, including in hermetic
// packed-artifact checks where runtime dependencies are intentionally absent.
const frontmatter = require('js-yaml').load(match[1]);
if (!frontmatter || typeof frontmatter !== 'object' || Array.isArray(frontmatter)) {
throw new Error(`Cannot adapt Copilot rule ${label}: frontmatter must be an object`);
}
return {
frontmatter,
body: text.slice(match[0].length),
};
}
function serializeApplyTo(globs) {
return require('js-yaml')
.dump({ applyTo: globs }, { lineWidth: -1, noRefs: true })
.trimEnd();
}
// Markdown links with a compact target (no title), e.g. [text](../a/b.md#x).
const MARKDOWN_LINK_TARGET = /(\]\()([^)\s]+)(\))/g;
// Rewrite relative links that resolve inside the installed rule set to their
// `.instructions.md` names. Everything else — links escaping `rules/`,
// absolute or external targets, anchors, `README.md` (not installed), and
// anything inside fenced code blocks (examples must stay verbatim) — is left
// unchanged.
function rewriteRuleLinks(body, label) {
const normalizedLabel = String(label || '').replace(/\\/g, '/');
if (!/\.md$/i.test(normalizedLabel)) {
return body;
}
const sourceDir = path.posix.dirname(normalizedLabel);
let fence = null;
return body.split('\n').map(line => {
const marker = line.match(/^ {0,3}(`{3,}|~{3,})(.*)\r?$/);
if (fence) {
if (marker && marker[1][0] === fence.character
&& marker[1].length >= fence.length && marker[2].trim() === '') {
fence = null;
}
return line;
}
if (marker && (marker[1][0] !== '`' || !marker[2].includes('`'))) {
fence = { character: marker[1][0], length: marker[1].length };
return line;
}
return line.replace(MARKDOWN_LINK_TARGET, (link, open, target, close) => {
const anchorIndex = target.indexOf('#');
const targetPath = anchorIndex === -1 ? target : target.slice(0, anchorIndex);
const anchor = anchorIndex === -1 ? '' : target.slice(anchorIndex);
if (!/\.md$/i.test(targetPath)) {
return link;
}
if (/^[a-z][a-z0-9+.-]*:/i.test(targetPath) || targetPath.startsWith('/')) {
return link;
}
if (/^readme\.md$/i.test(path.posix.basename(targetPath))) {
return link;
}
const resolved = path.posix.normalize(path.posix.join(sourceDir, targetPath));
if (!resolved.startsWith('rules/')) {
return link;
}
return `${open}${targetPath.replace(/\.md$/i, '.instructions.md')}${anchor}${close}`;
});
}).join('\n');
}
function adaptCopilotRule(source, label = '<unknown>') {
const parsed = splitFrontmatter(source, label);
if (!parsed) {
return `---\napplyTo: "${GLOBAL_APPLY_TO}"\n---\n${rewriteRuleLinks(String(source || ''), label)}`;
}
const { frontmatter } = parsed;
const body = rewriteRuleLinks(parsed.body, label);
const paths = frontmatter.paths;
if (paths === undefined) {
return `---\napplyTo: "${GLOBAL_APPLY_TO}"\n---\n${body}`;
}
if (!Array.isArray(paths) || paths.length === 0 || paths.some(glob => typeof glob !== 'string' || glob.trim() === '')) {
throw new Error(`Cannot adapt Copilot rule ${label}: "paths" must be a non-empty list of glob strings`);
}
return `---\n${serializeApplyTo(paths.map(glob => glob.trim()).join(','))}\n---\n${body}`;
}
module.exports = {
adaptCopilotRule,
GLOBAL_APPLY_TO,
};
+16 -1
View File
@@ -183,7 +183,21 @@ function isOpenCodePluginEntrypoint(operation = {}) {
function getDisabledOpenCodePluginContent() {
// OpenCode discovers plugins independently of opencode.json registration.
// Do not import the original module: even module initialization has effects.
return 'export default async () => ({});\n';
// The stub must still satisfy the V2 loader schema: the default export has to
// be a definition object with an id and an effect or setup function. A factory
// (`export default async () => ({})`) is rejected at startup with
// PluginModule.LoadError / SchemaError(Expected object at ["default"]), which
// is the same failure reported for the V1 hook plugin in issue #3537.
return 'export default { id: "ecc-hooks", setup() {} };\n';
}
// Installs made before the V2 stub fix wrote this stub. It is inert either way;
// the V2 loader merely rejects it.
const LEGACY_DISABLED_OPENCODE_PLUGIN_CONTENT = 'export default async () => ({});\n';
function isInertOpenCodePluginStub(content) {
const text = content.toString('utf8');
return text === getDisabledOpenCodePluginContent() || text === LEGACY_DISABLED_OPENCODE_PLUGIN_CONTENT;
}
function isOpenCodeHookActivationOperation(operation = {}) {
@@ -429,6 +443,7 @@ module.exports = {
disableOpenCodeHookPluginRegistration,
parseJsoncConfig,
getDisabledOpenCodePluginContent,
isInertOpenCodePluginStub,
getOpenCodeActivationPathKind,
getOpenCodeSourceActivationKind,
formatHookCapabilityDisclosure,
@@ -6,6 +6,7 @@ const path = require('path');
const { readInstallState, validateInstallState } = require('../install-state');
const { assertWithinTrustedRoot } = require('../path-safety');
const { isInertOpenCodePluginStub } = require('./hook-consent');
const OPENCODE_TARGET = 'opencode';
const INSTALL_STATE_NAME = 'ecc-install-state.json';
@@ -210,7 +211,7 @@ function verifyManagedLegacyFile(operation, location, sourceRoot) {
} catch (_error) {
return { retainedPath: destinationPath };
}
if (source.digest !== destination.digest) {
if (source.digest !== destination.digest && !isInertOpenCodePluginStub(destination.content)) {
return { retainedPath: destinationPath };
}
return { destinationPath, digest: destination.digest, stat: destination.stat };
+6 -3
View File
@@ -104,10 +104,13 @@ function buildCopyFileOperation({
strategy,
contentTransform,
}) {
// Copilot's agent and workflow transforms are textual. Their directories may
// also contain binary assets and executable helpers, which must keep bytes.
// Agent frontmatter and workflow transforms are textual Markdown projections.
// Their directories may also contain binary assets and executable helpers,
// which must keep their bytes intact.
const applicableTransform = (contentTransform === 'copilot-workflow-paths'
|| contentTransform === 'copilot-agent-frontmatter')
|| contentTransform === 'copilot-agent-frontmatter'
|| contentTransform === 'antigravity-agent-frontmatter'
|| contentTransform === 'qwen-agent-frontmatter')
&& !/\.md$/i.test(sourceRelativePath) ? undefined : contentTransform;
return {
kind: 'copy-file',
+13 -5
View File
@@ -92,16 +92,24 @@ function extractConversationText(transcriptPath) {
}
/**
* Read the context remaining percentage from a transcript's latest usage record.
* Returns null when unavailable.
* Read the remaining context budget percentage for summary scheduling.
* Use the earlier of confirmed capacity and a native compaction budget.
* With inferred capacity, only an explicit native budget can supply a safe
* scheduling boundary; otherwise return null rather than certify a guess.
*/
function getContextRemainingPct(transcriptPath) {
try {
const { readLatestContextTokens, resolveContextWindowTokens } = require('./transcript-context');
const { readLatestContextTokens, resolveContextWindow } = require('./transcript-context');
const usage = readLatestContextTokens(transcriptPath);
if (!usage) return null;
const windowTokens = resolveContextWindowTokens(usage.tokens, usage.model);
return Math.round((1 - usage.tokens / windowTokens) * 100);
const resolution = resolveContextWindow(usage.tokens, usage.model);
const nativeBudget = Number(process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '');
const hasNativeBudget = Number.isSafeInteger(nativeBudget) && nativeBudget > 0;
const budget = resolution.inferred
? (hasNativeBudget ? nativeBudget : 0)
: (hasNativeBudget ? Math.min(resolution.windowTokens, nativeBudget) : resolution.windowTokens);
if (!Number.isSafeInteger(budget) || budget <= 0) return null;
return Math.round((1 - usage.tokens / budget) * 100);
} catch {
return null;
}
+94 -4
View File
@@ -85,12 +85,82 @@ function resolveProjectRoot(cwd = process.cwd()) {
return '';
}
function resolveMainWorktreeRoot(projectRoot) {
const listing = runGit(['worktree', 'list', '--porcelain'], projectRoot);
const line = listing.split(/\r?\n/).find(entry => entry.startsWith('worktree '));
return line ? line.slice('worktree '.length) : '';
}
function computeProjectId(projectRoot) {
const remoteUrl = stripRemoteCredentials(runGit(['remote', 'get-url', 'origin'], projectRoot));
const hashInput = normalizeRemoteUrl(remoteUrl) || remoteUrl || projectRoot;
// Same fallback as detect-project.sh: a remote-free linked worktree shares its main checkout's id.
const hashInput = normalizeRemoteUrl(remoteUrl) || remoteUrl || resolveMainWorktreeRoot(projectRoot) || projectRoot;
return crypto.createHash('sha256').update(hashInput).digest('hex').slice(0, 12);
}
// detect-project.sh creates instincts/ before it updates projects.json, so a
// folder with instincts/ is one the observer writes to (a bare folder may be
// one this module created).
function hasObserverData(projectId) {
return fs.existsSync(path.join(getProjectsDir(), projectId, 'instincts'));
}
// Match the project CLI's ID boundary before using registry data in paths.
function isSafeProjectId(projectId) {
return typeof projectId === 'string' && projectId.length <= 128
&& /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(projectId)
&& !projectId.includes('..');
}
/**
* Choose the project id for a root that has registry entries.
*
* After a repository gains a remote, detect-project.sh writes under the
* remote-hash id while the old path-hash entry stays in the registry. Prefer
* the id the observer derives now when it is registered or already holds
* observer data; otherwise keep a sole entry, or take the most recently seen
* of several. When other ids remain for the root, show a read-only inspection
* path. The current merge CLI deletes the source directory, including live
* observer state and files it does not copy, so SessionStart must not suggest it.
*/
function pickRootProjectId(entries, projectRoot) {
const computedId = computeProjectId(projectRoot);
const ids = [...new Set(entries.map(entry => entry.id))];
const lastSeen = entry => Date.parse(entry.last_seen || '') || 0;
let chosenId;
if (ids.includes(computedId) || hasObserverData(computedId)) {
chosenId = computedId;
} else if (entries.length === 1) {
return ids[0];
} else {
chosenId = entries.reduce((latest, entry) => (lastSeen(entry) > lastSeen(latest) ? entry : latest)).id;
}
const others = ids.filter(id => id !== chosenId);
if (others.length > 0) {
process.stderr.write(
`[ecc] ${projectRoot} has project ids ${[chosenId, ...others].join(', ')}; using ${chosenId}. `
+ 'Inspect with instinct-cli.py projects; do not merge live project storage. '
+ 'The merge command removes the source directory.\n'
);
}
return chosenId;
}
// Native real paths expand Windows 8.3 names; the JS realpath walker may retain
// a non-symlink short spelling. Canonicalize only root comparison; keep the Git
// spelling in computeProjectId's fallback hash for detect-project.sh parity.
// Unavailable roots cannot claim aliases.
function canonicalProjectRoot(root) {
if (typeof root !== 'string' || !path.isAbsolute(root)) return '';
try {
const realpath = fs.realpathSync.native || fs.realpathSync;
return realpath(root);
} catch {
return '';
}
}
function resolveProjectContext(cwd = process.cwd()) {
const projectRoot = resolveProjectRoot(cwd);
if (!projectRoot) {
@@ -100,12 +170,31 @@ function resolveProjectContext(cwd = process.cwd()) {
}
const registry = readProjectRegistry();
const registryEntry = Object.values(registry).find(entry => entry && path.resolve(entry.root || '') === projectRoot);
const projectId = registryEntry?.id || computeProjectId(projectRoot);
const canonicalRoot = canonicalProjectRoot(projectRoot);
const rootEntries = Object.values(registry).filter(entry => entry && isSafeProjectId(entry.id)
&& canonicalRoot && canonicalProjectRoot(entry.root) === canonicalRoot);
const projectId = rootEntries.length > 0
? pickRootProjectId(rootEntries, projectRoot)
: computeProjectId(projectRoot);
const projectDir = path.join(getProjectsDir(), projectId);
ensureDir(projectDir);
const aliasProjectIds = [...new Set(rootEntries.map(entry => entry.id))].filter(id => id !== projectId);
return { projectId, projectRoot, projectDir, isGlobal: false };
return { projectId, projectRoot, projectDir, isGlobal: false, aliasProjectIds };
}
/**
* Contexts for the other registry ids that share this root. A remote added
* mid-session moves the root to a new id, so a SessionStart lease can still
* sit under one of these.
*/
function getAliasContexts(context) {
return [...new Set((context.aliasProjectIds || []).filter(isSafeProjectId))].map(projectId => ({
...context,
projectId,
projectDir: path.join(getProjectsDir(), projectId),
aliasProjectIds: []
}));
}
function getObserverPidFile(context) {
@@ -201,6 +290,7 @@ module.exports = {
getHomunculusDir,
normalizeRemoteUrl,
resolveProjectContext,
getAliasContexts,
getObserverActivityFile,
getObserverPidFile,
getSessionLeaseDir,
+4 -1
View File
@@ -9,7 +9,6 @@
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
/**
* Language detection rules.
@@ -350,6 +349,10 @@ function hasFlutterSdkDependency(projectDir) {
const pubspecPath = path.join(projectDir, 'pubspec.yaml');
if (!fs.existsSync(pubspecPath)) return false;
const content = fs.readFileSync(pubspecPath, 'utf8');
// Loaded here, not at the top: the SessionStart hook requires this module
// from plugin installs that have no node_modules (#2822). Without js-yaml
// the catch below costs only the Flutter check, not the whole hook.
const yaml = require('js-yaml');
const pubspec = yaml.load(content, { schema: yaml.JSON_SCHEMA });
// Only a declared Flutter SDK dependency identifies the framework.
// Unrelated configuration, comments, and strings must not count.
+1 -1
View File
@@ -183,7 +183,7 @@ function getInlineWslConversion() {
try {
_inlineWslConversion = require('./install-targets/helpers').INLINE_WSL_CONVERSION;
} catch (_) {
_inlineWslConversion = `try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var m=d.match(/^([A-Za-z]):[\\\\\\\\/]/);if(m){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).replace(/\\\\\\\\/g,'/')}}}}catch(_){}`;
_inlineWslConversion = `try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var b=String.fromCharCode(92),m=d.match(/^([A-Za-z]):/);if(m&&(d.charAt(2)==='/'||d.charAt(2)===b)){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).split(b).join('/')}}}}catch(_){}`;
}
}
return _inlineWslConversion;
+63 -35
View File
@@ -105,20 +105,36 @@ function parenDelta(ch) {
return 0;
}
// `$'...'` (ANSI-C quoting) opens only on an unescaped `$`: an odd run of
// backslashes before it makes the `$` literal and the quote a plain one.
function opensAnsiC(source, i) {
if (source[i - 1] !== '$') return false;
let backslashes = 0;
while (source[i - 2 - backslashes] === '\\') backslashes += 1;
return backslashes % 2 === 0;
}
// Backslash escapes apply outside single quotes and inside `$'...'`.
function escapesActive(quotes) {
return !quotes.inSingle || quotes.ansiC;
}
/**
* Toggle quote state for a quote character at the current position.
* Returns true when `ch` opened or closed a quote.
* Quote state after the quote character at `source[i]`, as a new object, or
* null when it neither opens nor closes a quote. Callers consume escapes
* first, so a quote after a backslash here still closes (`'C:\'`, `"C:\\"`),
* while `\'` inside `$'...'` is consumed before it can close the string.
*/
function toggleQuote(ch, prev, quotes) {
if (ch === "'" && !quotes.inDouble && prev !== '\\') {
quotes.inSingle = !quotes.inSingle;
return true;
function toggleQuote(source, i, quotes) {
const ch = source[i];
if (ch === "'" && !quotes.inDouble) {
const inSingle = !quotes.inSingle;
return { ...quotes, inSingle, ansiC: inSingle && opensAnsiC(source, i) };
}
if (ch === '"' && !quotes.inSingle && prev !== '\\') {
quotes.inDouble = !quotes.inDouble;
return true;
if (ch === '"' && !quotes.inSingle) {
return { ...quotes, inDouble: !quotes.inDouble };
}
return false;
return null;
}
/**
@@ -126,16 +142,19 @@ function toggleQuote(ch, prev, quotes) {
* is at `start`, honoring quotes and escapes inside the span.
*/
function findParenSpanEnd(source, start) {
const quotes = { inSingle: false, inDouble: false };
let quotes = { inSingle: false, inDouble: false, ansiC: false };
let depth = 1;
let i = start;
while (i < source.length && depth > 0) {
const inner = source[i];
if (inner === '\\' && !quotes.inSingle) {
if (inner === '\\' && escapesActive(quotes)) {
i += 2;
continue;
}
if (!toggleQuote(inner, source[i - 1], quotes) && !quotes.inSingle && !quotes.inDouble) {
const toggled = toggleQuote(source, i, quotes);
if (toggled) {
quotes = toggled;
} else if (!quotes.inSingle && !quotes.inDouble) {
depth += parenDelta(inner);
}
i += 1;
@@ -161,17 +180,19 @@ function findBacktickEnd(source, start) {
/**
* Top-level scan step shared by the group extractors: escapes, quote state,
* `$(...)` and backtick spans. Returns the last index consumed so a `for`
* loop's `i++` resumes after it, or -1 when the caller must inspect `source[i]`.
* `$(...)` and backtick spans. Returns the quote state after `source[i]` and
* `skipped`, the last index consumed so a `for` loop's `i++` resumes after it,
* or -1 when the caller must inspect `source[i]`.
*/
function skipOuterSpan(source, i, quotes) {
const ch = source[i];
if (ch === '\\' && !quotes.inSingle) return i + 1;
if (toggleQuote(ch, source[i - 1], quotes)) return i;
if (quotes.inSingle || quotes.inDouble) return i;
if (ch === '$' && source[i + 1] === '(') return findParenSpanEnd(source, i + 2) - 1;
if (ch === '`') return findBacktickEnd(source, i + 1);
return -1;
if (ch === '\\' && escapesActive(quotes)) return { skipped: i + 1, quotes };
const toggled = toggleQuote(source, i, quotes);
if (toggled) return { skipped: i, quotes: toggled };
if (quotes.inSingle || quotes.inDouble) return { skipped: i, quotes };
if (ch === '$' && source[i + 1] === '(') return { skipped: findParenSpanEnd(source, i + 2) - 1, quotes };
if (ch === '`') return { skipped: findBacktickEnd(source, i + 1), quotes };
return { skipped: -1, quotes };
}
/**
@@ -179,20 +200,23 @@ function skipOuterSpan(source, i, quotes) {
* the body text and the index of the closing paren (or where input ran out).
*/
function readSubshellBody(source, start) {
const quotes = { inSingle: false, inDouble: false };
let quotes = { inSingle: false, inDouble: false, ansiC: false };
let depth = 1;
let body = '';
let i = start;
while (i < source.length && depth > 0) {
const inner = source[i];
if (inner === '\\' && !quotes.inSingle) {
if (inner === '\\' && escapesActive(quotes)) {
// Keep the escape and its operand together; a trailing backslash at the
// end of an unterminated span is appended once and the scan stops.
body += source.slice(i, i + 2);
i = Math.min(i + 2, source.length);
continue;
}
if (!toggleQuote(inner, source[i - 1], quotes) && !quotes.inSingle && !quotes.inDouble) {
const toggled = toggleQuote(source, i, quotes);
if (toggled) {
quotes = toggled;
} else if (!quotes.inSingle && !quotes.inDouble) {
depth += parenDelta(inner);
if (depth === 0) break;
}
@@ -222,12 +246,13 @@ function readSubshellBody(source, start) {
function extractSubshellGroups(input) {
const source = String(input || '');
const groups = [];
const quotes = { inSingle: false, inDouble: false };
let quotes = { inSingle: false, inDouble: false, ansiC: false };
for (let i = 0; i < source.length; i++) {
const skipped = skipOuterSpan(source, i, quotes);
if (skipped !== -1) {
i = skipped;
const step = skipOuterSpan(source, i, quotes);
quotes = step.quotes;
if (step.skipped !== -1) {
i = step.skipped;
continue;
}
if (source[i] !== '(') continue;
@@ -267,19 +292,21 @@ function opensBraceGroup(source, i) {
* the body text and the index of the closing brace (or where input ran out).
*/
function readBraceBody(source, start) {
const quotes = { inSingle: false, inDouble: false };
let quotes = { inSingle: false, inDouble: false, ansiC: false };
let depth = 1;
let body = '';
let i = start;
while (i < source.length && depth > 0) {
const inner = source[i];
const prev = source[i - 1];
if (inner === '\\' && !quotes.inSingle) {
if (inner === '\\' && escapesActive(quotes)) {
body += source.slice(i, i + 2);
i = Math.min(i + 2, source.length);
continue;
}
if (toggleQuote(inner, prev, quotes) || quotes.inSingle || quotes.inDouble) {
const toggled = toggleQuote(source, i, quotes);
if (toggled) quotes = toggled;
if (toggled || quotes.inSingle || quotes.inDouble) {
body += inner;
i += 1;
continue;
@@ -329,12 +356,13 @@ function readBraceBody(source, start) {
function extractBraceGroups(input) {
const source = String(input || '');
const groups = [];
const quotes = { inSingle: false, inDouble: false };
let quotes = { inSingle: false, inDouble: false, ansiC: false };
for (let i = 0; i < source.length; i++) {
const skipped = skipOuterSpan(source, i, quotes);
if (skipped !== -1) {
i = skipped;
const step = skipOuterSpan(source, i, quotes);
quotes = step.quotes;
if (step.skipped !== -1) {
i = step.skipped;
continue;
}
if (source[i] === '(') {
+22
View File
@@ -482,6 +482,22 @@ function createQueryApi(db, { prepareRead = sql => db.prepare(sql) } = {}) {
FROM work_items
ORDER BY updated_at DESC, id DESC
`);
// Read the entire native READY set in SQL instead of truncating to the
// 100 most recently updated items before checking their eligibility.
const nextClaimableWorkItemStatement = prepareRead(`
SELECT *
FROM work_items
WHERE (owner IS NULL OR owner = '')
AND LOWER(TRIM(COALESCE(status, ''))) IN ('open', 'ready')
ORDER BY CASE LOWER(COALESCE(priority, ''))
WHEN 'critical' THEN 0
WHEN 'high' THEN 1
WHEN 'urgent' THEN 1
WHEN 'low' THEN 3
ELSE 2
END ASC, updated_at DESC, id DESC
LIMIT 1
`);
const getWorkItemStatement = prepareRead(`
SELECT *
FROM work_items
@@ -760,6 +776,11 @@ function createQueryApi(db, { prepareRead = sql => db.prepare(sql) } = {}) {
};
}
function getNextClaimableWorkItem() {
const row = nextClaimableWorkItemStatement.get();
return row ? mapWorkItemRow(row) : null;
}
function getStatus(options = {}) {
const activeLimit = normalizeLimit(options.activeLimit, 5);
const recentSkillRunLimit = normalizeLimit(options.recentSkillRunLimit, 20);
@@ -870,6 +891,7 @@ function createQueryApi(db, { prepareRead = sql => db.prepare(sql) } = {}) {
},
listRecentSessions,
listWorkItems,
getNextClaimableWorkItem,
upsertInstallState(installState) {
const normalized = normalizeInstallStateInput(installState);
assertValidEntity('installState', normalized);
+28 -10
View File
@@ -94,14 +94,16 @@ function readLatestContextTokens(transcriptPath, options = {}) {
const tailBytes = Number.isInteger(options.tailBytes) && options.tailBytes > 0 ? options.tailBytes : DEFAULT_TRANSCRIPT_TAIL_BYTES;
const tail = readFileTail(transcriptPath, tailBytes);
// Include the preceding byte so a newline at the requested boundary keeps
// the first complete record; a mid-record boundary still gets discarded.
const tail = readFileTail(transcriptPath, tailBytes + 1, { includeByteLength: true });
if (!tail) {
return null;
}
const lines = tail.text.split('\n');
// The first line of a truncated tail is almost certainly partial JSON.
const firstLine = tail.truncated ? 1 : 0;
// Discard the extra boundary byte and any partial record containing it.
const firstLine = tail.truncated || tail.byteLength > tailBytes ? 1 : 0;
for (let i = lines.length - 1; i >= firstLine; i--) {
const line = lines[i].trim();
@@ -138,13 +140,13 @@ function readLatestContextTokens(transcriptPath, options = {}) {
* @returns {{ windowTokens: number, inferred: boolean }}
*/
function resolveContextWindow(tokens, model) {
const env = (typeof process !== 'undefined' && process.env) || {};
// Explicit window override wins: 400k models (e.g. Opus 4.x) match neither the
// 200k default nor the 1M marker and would otherwise report ~double usage (#2290).
// Honor ECC's own knob and Claude Code's native CLAUDE_CODE_AUTO_COMPACT_WINDOW.
const env = (typeof process !== 'undefined' && process.env) || {};
const envWindow = Number.parseInt(env.ECC_CONTEXT_WINDOW_TOKENS || env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '', 10);
if (Number.isInteger(envWindow) && envWindow > 0) {
return { windowTokens: envWindow, inferred: false };
const explicitWindow = Number(env.ECC_CONTEXT_WINDOW_TOKENS || '');
if (Number.isSafeInteger(explicitWindow) && explicitWindow > 0) {
return { windowTokens: explicitWindow, inferred: false };
}
if (typeof model === 'string' && model.includes(LARGE_WINDOW_MODEL_MARKER)) {
@@ -164,6 +166,15 @@ function resolveContextWindow(tokens, model) {
return { windowTokens: LARGE_CONTEXT_WINDOW_TOKENS, inferred: true };
}
// Claude Code's CLAUDE_CODE_AUTO_COMPACT_WINDOW is the harness auto-compact
// trigger point (e.g. 786432 on a 1M-window model), not the context window
// size. Honor it only as a last-resort fallback so it cannot mask the [1m]
// marker, known large-window families, or >200k observed tokens above.
const autoCompactWindow = Number(env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '');
if (Number.isSafeInteger(autoCompactWindow) && autoCompactWindow > 0) {
return { windowTokens: autoCompactWindow, inferred: false };
}
return { windowTokens: STANDARD_CONTEXT_WINDOW_TOKENS, inferred: true };
}
@@ -192,7 +203,8 @@ function isContextWindowInferred(tokens, model) {
/**
* Resolve the context-size suggestion threshold (tokens).
* `COMPACT_CONTEXT_THRESHOLD=0` disables the context signal entirely;
* other invalid values fall back to the window-scaled default.
* other invalid values fall back to the window-scaled default, capped at
* 80 percent of a valid native compaction budget when that is earlier.
*/
function resolveContextThreshold(env, windowTokens) {
const raw = env && env.COMPACT_CONTEXT_THRESHOLD;
@@ -206,7 +218,13 @@ function resolveContextThreshold(env, windowTokens) {
}
}
return windowTokens >= LARGE_CONTEXT_WINDOW_TOKENS ? DEFAULT_CONTEXT_THRESHOLD_LARGE : DEFAULT_CONTEXT_THRESHOLD_STANDARD;
const defaultThreshold = windowTokens >= LARGE_CONTEXT_WINDOW_TOKENS ? DEFAULT_CONTEXT_THRESHOLD_LARGE : DEFAULT_CONTEXT_THRESHOLD_STANDARD;
const nativeBudget = Number(env && env.CLAUDE_CODE_AUTO_COMPACT_WINDOW);
if (!Number.isSafeInteger(nativeBudget) || nativeBudget <= 0) return defaultThreshold;
// Keep the standard 160k/200k headroom before native compaction, without
// changing model-capacity evidence or an explicit reminder policy above.
const nativeThreshold = Math.max(1, Math.floor(nativeBudget * (DEFAULT_CONTEXT_THRESHOLD_STANDARD / STANDARD_CONTEXT_WINDOW_TOKENS)));
return Math.min(defaultThreshold, nativeThreshold);
}
/**
+3 -3
View File
@@ -32,8 +32,8 @@ EOF
mkdir -p "$(dirname "$handoff_file")" "$(dirname "$status_file")"
if [[ ! -r "$task_file" ]]; then
write_status "failed" "- Error: task file is missing or unreadable (\`$task_file\`)"
if [[ ! -f "$task_file" || ! -r "$task_file" ]]; then
write_status "failed" "- Error: task file is missing, unreadable, or not a regular file (\`$task_file\`)"
{
echo "# Handoff"
echo
@@ -41,7 +41,7 @@ if [[ ! -r "$task_file" ]]; then
echo "- Branch: \`$(git rev-parse --abbrev-ref HEAD)\`"
echo "- Worktree: \`$(pwd)\`"
echo
echo "Task file is missing or unreadable: \`$task_file\`"
echo "Task file is missing, unreadable, or not a regular file: \`$task_file\`"
} > "$handoff_file"
exit 1
fi
+104 -39
View File
@@ -176,8 +176,36 @@ function slugifyWorkItemSegment(value) {
);
}
function normalizeGithubRepo(repo) {
return typeof repo === 'string' ? repo.toLowerCase() : '';
}
function githubWorkItemId(repo, type, number) {
return `github-${slugifyWorkItemSegment(repo)}-${type}-${number}`;
return `github-${encodeURIComponent(normalizeGithubRepo(repo))}-${type}-${number}`;
}
function isSameGithubWorkItem(existing, incoming) {
return existing
&& existing.source === incoming.source
&& existing.sourceId === incoming.sourceId
&& existing.metadata?.syncedBy === 'ecc-work-items-sync-github'
&& normalizeGithubRepo(existing.metadata.repo) === normalizeGithubRepo(incoming.metadata.repo);
}
function resolveGithubWorkItemId(store, item) {
const existing = store.getWorkItemById(item.id);
if (existing) {
if (!isSameGithubWorkItem(existing, item)) {
throw new Error(`GitHub work item ID collision: ${item.id} belongs to a different item.`);
}
return item.id;
}
// Keep references to older imports intact, but never reuse a slug belonging
// to another repository. Prefer an existing canonical ID on every sync.
const type = item.source === 'github-pr' ? 'pr' : 'issue';
const legacyId = `github-${slugifyWorkItemSegment(item.metadata.repo)}-${type}-${item.sourceId}`;
return isSameGithubWorkItem(store.getWorkItemById(legacyId), item) ? legacyId : item.id;
}
function githubPrStatus(pr) {
@@ -201,7 +229,7 @@ function buildGithubPrWorkItem(repo, pr, options = {}) {
status: githubPrStatus(pr),
priority: pr.isDraft || pr.mergeStateStatus === 'DIRTY' ? 'high' : 'normal',
url: pr.url || null,
owner: githubAuthorLogin(pr),
owner: null,
repoRoot: options.repoRoot || process.cwd(),
sessionId: options.sessionId || null,
metadata: {
@@ -210,6 +238,7 @@ function buildGithubPrWorkItem(repo, pr, options = {}) {
mergeStateStatus: pr.mergeStateStatus || null,
isDraft: Boolean(pr.isDraft),
headRefName: pr.headRefName || null,
sourceAuthor: githubAuthorLogin(pr),
sourceUpdatedAt: pr.updatedAt || null,
syncedBy: 'ecc-work-items-sync-github'
}
@@ -225,19 +254,52 @@ function buildGithubIssueWorkItem(repo, issue, options = {}) {
status: 'needs-review',
priority: 'normal',
url: issue.url || null,
owner: githubAuthorLogin(issue),
owner: null,
repoRoot: options.repoRoot || process.cwd(),
sessionId: options.sessionId || null,
metadata: {
repo,
type: 'issue',
labels: Array.isArray(issue.labels) ? issue.labels.map(label => label.name || label).filter(Boolean) : [],
sourceAuthor: githubAuthorLogin(issue),
sourceUpdatedAt: issue.updatedAt || null,
syncedBy: 'ecc-work-items-sync-github'
}
};
}
function githubWorkflowState(item) {
return Object.fromEntries(['status', 'owner', 'sessionId', 'priority', 'repoRoot']
.map(key => [key, item[key] ?? null]));
}
function isLocallyManagedGithubItem(item) {
const metadata = item.metadata || {};
const sync = metadata.githubSync;
// Legacy imports have no reliable record of their original owner/status.
if (!sync || !sync.state || sync.managedLocally || metadata.assigneeKind) return true;
return Object.entries(githubWorkflowState(item)).some(([key, value]) => value !== sync.state[key]);
}
function refreshGithubWorkItem(store, payload, syncedAt) {
const existing = store.getWorkItemById(payload.id);
const preserveExisting = existing && isLocallyManagedGithubItem(existing);
const managedLocally = Boolean(preserveExisting || payload.sessionId);
const state = githubWorkflowState(preserveExisting ? existing : payload);
const { sourceClosedAt: _sourceClosedAt, ...metadata } = (existing && existing.metadata) || {};
return store.upsertWorkItem({
...payload,
...state,
metadata: {
...metadata,
...payload.metadata,
githubSync: { state, managedLocally }
},
createdAt: existing ? existing.createdAt : undefined,
updatedAt: syncedAt
});
}
function closeStaleGithubItems(store, repo, activeIds, options = {}) {
const payload = store.listWorkItems({ limit: options.limit || 10000 });
const closed = [];
@@ -245,12 +307,21 @@ function closeStaleGithubItems(store, repo, activeIds, options = {}) {
if (!item.metadata || item.metadata.syncedBy !== 'ecc-work-items-sync-github') {
continue;
}
if (item.metadata.repo !== repo || activeIds.has(item.id)) {
if (normalizeGithubRepo(item.metadata.repo) !== normalizeGithubRepo(repo) || activeIds.has(item.id)) {
continue;
}
if (item.status === 'closed' || item.status === 'done') {
continue;
}
if (isLocallyManagedGithubItem(item)) {
if (!item.metadata.githubSync || !item.metadata.githubSync.managedLocally) {
store.upsertWorkItem({
...item,
metadata: { ...item.metadata, githubSync: { state: githubWorkflowState(item), managedLocally: true } }
});
}
continue;
}
closed.push(
store.upsertWorkItem({
...item,
@@ -258,6 +329,7 @@ function closeStaleGithubItems(store, repo, activeIds, options = {}) {
updatedAt: new Date().toISOString(),
metadata: {
...item.metadata,
githubSync: { state: { ...githubWorkflowState(item), status: 'closed' }, managedLocally: false },
sourceClosedAt: new Date().toISOString()
}
})
@@ -276,42 +348,35 @@ function syncGithubWorkItems(store, options) {
const prs = runGhJson(['pr', 'list', '--repo', repo, '--state', 'open', '--limit', String(limit), '--json', 'number,title,author,url,updatedAt,mergeStateStatus,isDraft,headRefName']);
const issues = runGhJson(['issue', 'list', '--repo', repo, '--state', 'open', '--limit', String(limit), '--json', 'number,title,author,url,updatedAt,labels']);
const syncedAt = new Date().toISOString();
const activeIds = new Set();
const items = [];
for (const pr of prs) {
const payload = buildGithubPrWorkItem(repo, pr, options);
activeIds.add(payload.id);
items.push(
store.upsertWorkItem({
...payload,
createdAt: undefined,
updatedAt: syncedAt
})
);
}
for (const issue of issues) {
const payload = buildGithubIssueWorkItem(repo, issue, options);
activeIds.add(payload.id);
items.push(
store.upsertWorkItem({
...payload,
createdAt: undefined,
updatedAt: syncedAt
})
);
}
// Fetch before taking the store lock, then reconcile against one current snapshot.
return store._database.transaction(() => {
const syncedAt = new Date().toISOString();
const activeIds = new Set();
const items = [];
for (const pr of prs) {
const candidate = buildGithubPrWorkItem(repo, pr, options);
const payload = { ...candidate, id: resolveGithubWorkItemId(store, candidate) };
activeIds.add(payload.id);
items.push(refreshGithubWorkItem(store, payload, syncedAt));
}
for (const issue of issues) {
const candidate = buildGithubIssueWorkItem(repo, issue, options);
const payload = { ...candidate, id: resolveGithubWorkItemId(store, candidate) };
activeIds.add(payload.id);
items.push(refreshGithubWorkItem(store, payload, syncedAt));
}
const closedItems = closeStaleGithubItems(store, repo, activeIds, { limit: Math.max(limit * 4, 1000) });
return {
repo,
syncedAt,
prCount: prs.length,
issueCount: issues.length,
closedCount: closedItems.length,
items,
closedItems
};
const closedItems = closeStaleGithubItems(store, repo, activeIds, { limit: Math.max(limit * 4, 1000) });
return {
repo,
syncedAt,
prCount: prs.length,
issueCount: issues.length,
closedCount: closedItems.length,
items,
closedItems
};
})();
}
function buildUpsertPayload(options, existing = null) {