mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-17 13:32:18 +00:00
Merge remote-tracking branch 'origin/main' into fix/block-no-verify-group-piped-into-shell
This commit is contained in:
368 files changed
+21371
-1682
No files matched your search
@@ -0,0 +1,336 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Audit recently closed issues whose asserted delivery claims cite a PR that
|
||||
* is not actually merged.
|
||||
*
|
||||
* Motivated by #3223: an issue closed as "fixed in #N" while #N was closed
|
||||
* without merging leaves a completion claim that does not hold up. This audit
|
||||
* runs weekly from .github/workflows/maintenance.yml, scans issue text and
|
||||
* close-window comments for *asserted* delivery claims, verifies each cited
|
||||
* PR's merge state, and reports findings to the workflow step summary.
|
||||
*
|
||||
* Evidence contract (per the #3522 review):
|
||||
* - Only asserted delivery claims ("delivered through #N", "fixed in #N")
|
||||
* produce findings. Historical mentions, quoted text, fenced examples,
|
||||
* negated claims, and tracking-only references are reported separately as
|
||||
* context — a merged PR alone also does not certify issue completion.
|
||||
* - Observed states are reported distinctly: merged, open-unmerged,
|
||||
* closed-unmerged, and unknown (404, rate limit, transient failures). An
|
||||
* unavailable PR warrants manual verification; it does not establish that
|
||||
* a claim failed.
|
||||
* - Collection is paginated and its completeness is visible: skipped pages,
|
||||
* rate limits, and retrieval failures turn the report into an explicitly
|
||||
* incomplete audit rather than an all-clear.
|
||||
*
|
||||
* Read-only by design: findings are advisory, the script never comments on or
|
||||
* closes anything, and always exits 0 so the scheduled run never breaks.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const { execFileSync } = require('child_process');
|
||||
|
||||
const DEFAULT_WINDOW_DAYS = 30;
|
||||
const MAX_COMMENT_REQUESTS = 200;
|
||||
const MAX_PR_CHECKS = 100;
|
||||
|
||||
const CLAIM_PATTERN =
|
||||
/\b(?:delivered|delivers|fixed|fixes|shipped|ships|landed|lands|resolved|resolves|implemented|implements|completed|completes|closed|closes|merged|merges)\s+(?:through|in|via|by|with|as|into)\s+(?:PR\s+)?#(\d+)\b/gi;
|
||||
const PR_REF_PATTERN = /\bPR\s+#(\d+)\b/gi;
|
||||
const ANY_REF_PATTERN = /(?:^|[^\w&])#(\d+)\b/g;
|
||||
const NEGATION_PATTERN =
|
||||
/\b(?:not|never|cannot|can't|won't|doesn't|does\s+not|no\s+longer|isn't|wasn't)\s+(?:\w+\s+){0,2}$/i;
|
||||
|
||||
function runGh(args, env) {
|
||||
const options = { encoding: 'utf8', env, timeout: 60000, maxBuffer: 64 * 1024 * 1024 };
|
||||
if (env.AUDIT_GH_SCRIPT) {
|
||||
// Testability hook: run a fixture script instead of the real gh CLI.
|
||||
return execFileSync(process.execPath, [env.AUDIT_GH_SCRIPT, ...args], options);
|
||||
}
|
||||
return execFileSync('gh', args, options);
|
||||
}
|
||||
|
||||
function describeGhError(error) {
|
||||
const stderr = (error && error.stderr) || '';
|
||||
const http = stderr.match(/HTTP (\d{3})/);
|
||||
if (http) return `HTTP ${http[1]}`;
|
||||
return String((error && error.message) || error).split('\n')[0];
|
||||
}
|
||||
|
||||
// Pure: fenced code blocks, inline code, and blockquoted lines are examples or
|
||||
// quotation, not assertions made by the author — strip them before matching.
|
||||
function stripNonEvidence(text) {
|
||||
if (!text) return '';
|
||||
return text
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`[^`\n]*`/g, ' ')
|
||||
.split('\n')
|
||||
.filter((line) => !/^\s*>/.test(line))
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
// Pure: a claim pattern preceded by negation words is not an assertion.
|
||||
function isNegated(clean, matchIndex) {
|
||||
const before = clean.slice(Math.max(0, matchIndex - 60), matchIndex);
|
||||
return NEGATION_PATTERN.test(before);
|
||||
}
|
||||
|
||||
// Pure: classify every #N in one text as an asserted delivery claim or a
|
||||
// contextual reference. Deduplicates per (pr, kind). In a closing comment a
|
||||
// bare "PR #N" reference is the closing evidence; in issue text it stays
|
||||
// context.
|
||||
function extractRefs(text, source, sourceUrl) {
|
||||
const clean = stripNonEvidence(text);
|
||||
if (!clean) return [];
|
||||
const refs = [];
|
||||
const claimMatches = [...clean.matchAll(CLAIM_PATTERN)];
|
||||
if (source === 'closing-comment') claimMatches.push(...clean.matchAll(PR_REF_PATTERN));
|
||||
for (const match of claimMatches) {
|
||||
if (isNegated(clean, match.index)) continue;
|
||||
refs.push({ pr: Number(match[1]), kind: 'claim', source, sourceUrl, snippet: match[0] });
|
||||
}
|
||||
const ranges = claimMatches.map((m) => [m.index, m.index + m[0].length]);
|
||||
for (const match of clean.matchAll(ANY_REF_PATTERN)) {
|
||||
const insideClaim = ranges.some(([start, end]) => match.index >= start && match.index < end);
|
||||
if (insideClaim || isNegated(clean, match.index)) continue;
|
||||
refs.push({ pr: Number(match[1]), kind: 'reference', source, sourceUrl, snippet: match[0].trim() });
|
||||
}
|
||||
const seen = new Set();
|
||||
return refs.filter((ref) => (seen.has(ref.pr + ':' + ref.kind) ? false : (seen.add(ref.pr + ':' + ref.kind), true)));
|
||||
}
|
||||
|
||||
// Pure: issues closed within the look-back window; PRs are not issues.
|
||||
function selectRecentClosedIssues(issues, nowMs, windowDays) {
|
||||
const cutoff = nowMs - windowDays * 24 * 60 * 60 * 1000;
|
||||
return issues.filter(
|
||||
(issue) =>
|
||||
issue.state === 'closed' &&
|
||||
!issue.pull_request &&
|
||||
typeof issue.closed_at === 'string' &&
|
||||
Date.parse(issue.closed_at) >= cutoff
|
||||
);
|
||||
}
|
||||
|
||||
// Pure: comment objects (body + html_url) inside the window, starting at the
|
||||
// issue's closure so the closing comment always counts as evidence.
|
||||
function selectWindowComments(comments, issueClosedAt, windowDays, nowMs) {
|
||||
const cutoff = nowMs - windowDays * 24 * 60 * 60 * 1000;
|
||||
return comments
|
||||
.filter((comment) => typeof comment.body === 'string')
|
||||
.filter((comment) => Date.parse(comment.created_at) >= Math.max(cutoff, Date.parse(issueClosedAt) - 60_000));
|
||||
}
|
||||
|
||||
// Pure: one entry per issue with its claims and contextual references.
|
||||
function extractEvidence(issue, comments, nowMs) {
|
||||
const refs = [
|
||||
...extractRefs([issue.title, issue.body].filter(Boolean).join('\n'), 'issue-body', issue.html_url),
|
||||
];
|
||||
for (const comment of selectWindowComments(comments, issue.closed_at, DEFAULT_WINDOW_DAYS, nowMs)) {
|
||||
refs.push(...extractRefs(comment.body, 'closing-comment', comment.html_url));
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
// Collect issues + evidence. Fetch failures are surfaced as incomplete notes,
|
||||
// never silently swallowed into an empty list.
|
||||
function collectEntries(fetchIssues, fetchComments, nowMs, windowDays) {
|
||||
const { items: issues, error } = fetchIssues();
|
||||
if (error) return { entries: [], incomplete: [`issue list unavailable: ${error}`] };
|
||||
const incomplete = [];
|
||||
const entries = [];
|
||||
for (const issue of selectRecentClosedIssues(issues, nowMs, windowDays)) {
|
||||
const { items: comments, error: commentError } = fetchComments(issue.number);
|
||||
if (commentError) incomplete.push(`#${issue.number} comments unavailable: ${commentError}`);
|
||||
const refs = extractEvidence(issue, comments, nowMs);
|
||||
if (refs.length) entries.push({ issue: issue.number, issueUrl: issue.html_url, refs });
|
||||
}
|
||||
return { entries, incomplete };
|
||||
}
|
||||
|
||||
function uniqueClaimPrs(entries) {
|
||||
return [...new Set(entries.flatMap((entry) => entry.refs.filter((r) => r.kind === 'claim').map((r) => r.pr)))];
|
||||
}
|
||||
|
||||
function collectReferences(entries) {
|
||||
const seen = new Set();
|
||||
const refs = [];
|
||||
for (const entry of entries) {
|
||||
for (const ref of entry.refs.filter((r) => r.kind === 'reference')) {
|
||||
const key = entry.issue + ':' + ref.pr;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
refs.push({ issue: entry.issue, pr: ref.pr });
|
||||
}
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
// Pure: one verdict row per asserted claim. Merged passes; open/closed
|
||||
// unmerged are findings; unknown is unverifiable and needs manual verification.
|
||||
function buildVerdicts(entries, pullStates) {
|
||||
const rows = [];
|
||||
for (const entry of entries) {
|
||||
for (const ref of entry.refs.filter((r) => r.kind === 'claim')) {
|
||||
const state = pullStates.get(ref.pr) || { observed: 'unknown', reason: 'not fetched' };
|
||||
rows.push({
|
||||
issue: entry.issue, pr: ref.pr, snippet: ref.snippet, source: ref.source,
|
||||
sourceUrl: ref.sourceUrl, observed: state.observed, reason: state.reason || null,
|
||||
verdict: state.observed === 'merged' ? 'pass' : state.observed === 'unknown' ? 'unverifiable' : 'unmerged',
|
||||
});
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function summaryIncomplete(lines, incomplete) {
|
||||
if (!incomplete.length) return;
|
||||
lines.push('', '**Audit incomplete** — some evidence could not be collected; absence of findings below is not an all-clear:');
|
||||
for (const note of incomplete) lines.push(`- ${note}`);
|
||||
}
|
||||
|
||||
function summaryFindings(lines, unmerged) {
|
||||
if (!unmerged.length) return;
|
||||
lines.push('', '### Findings — asserted delivery claims whose cited PR is not merged');
|
||||
for (const v of unmerged) {
|
||||
lines.push(`- #${v.issue} claims "${v.snippet}" (source: ${v.source}, ${v.sourceUrl}) → #${v.pr}: ${v.observed}.`);
|
||||
}
|
||||
}
|
||||
|
||||
function summaryUnverifiable(lines, unverifiable) {
|
||||
if (!unverifiable.length) return;
|
||||
lines.push('', '### Unverifiable — manual verification required');
|
||||
for (const v of unverifiable) {
|
||||
lines.push(`- #${v.issue} claims "${v.snippet}" (${v.sourceUrl}) → #${v.pr}: unavailable (${v.reason}). An unavailable PR does not establish that the claim failed.`);
|
||||
}
|
||||
}
|
||||
|
||||
// Traceability: every checked claim is listed with its evidence link, passes
|
||||
// included — an all-clear line alone cannot be audited.
|
||||
function summaryPasses(lines, passes) {
|
||||
if (!passes.length) return;
|
||||
lines.push('', '### Checked claims — cited PR is merged');
|
||||
for (const v of passes) {
|
||||
lines.push(`- #${v.issue} claims "${v.snippet}" (source: ${v.source}, ${v.sourceUrl}) → #${v.pr}: merged.`);
|
||||
}
|
||||
}
|
||||
|
||||
// Pure: markdown lines for the step summary.
|
||||
function buildSummary(verdicts, references, incomplete) {
|
||||
const lines = ['## Closed-issue delivery-claim audit', '', `Observed: ${new Date().toISOString()}`];
|
||||
summaryIncomplete(lines, incomplete);
|
||||
const unmerged = verdicts.filter((v) => v.verdict === 'unmerged');
|
||||
const unverifiable = verdicts.filter((v) => v.verdict === 'unverifiable');
|
||||
lines.push('', `${verdicts.length} asserted delivery claim(s) found: ${unmerged.length} unmerged finding(s), ${unverifiable.length} unverifiable.`);
|
||||
summaryFindings(lines, unmerged);
|
||||
summaryUnverifiable(lines, unverifiable);
|
||||
summaryPasses(lines, verdicts.filter((v) => v.verdict === 'pass'));
|
||||
if (references.length) {
|
||||
lines.push('', '### Contextual references (not delivery claims)');
|
||||
const byIssue = new Map();
|
||||
for (const r of references) {
|
||||
if (!byIssue.has(r.issue)) byIssue.set(r.issue, []);
|
||||
byIssue.get(r.issue).push('#' + r.pr);
|
||||
}
|
||||
for (const [issue, prs] of byIssue) {
|
||||
lines.push(`- #${issue}: ${[...new Set(prs)].join(', ')}`);
|
||||
}
|
||||
}
|
||||
if (!verdicts.length && !references.length && !incomplete.length) {
|
||||
lines.push('No asserted delivery claims found in recently closed issues.');
|
||||
}
|
||||
if (verdicts.length && !unmerged.length) {
|
||||
lines.push('', 'No unmerged findings. A merged cited PR supports the claim; it does not by itself certify issue completion, current code after a revert, or package publication.');
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Paginated gh api fetch: --paginate --slurp yields one array per page.
|
||||
function fetchAllPages(args, env) {
|
||||
try {
|
||||
const raw = JSON.parse(runGh(['api', '--paginate', '--slurp', args], env));
|
||||
return { items: Array.isArray(raw) ? raw.flat() : [], error: null };
|
||||
} catch (error) {
|
||||
return { items: [], error: describeGhError(error) };
|
||||
}
|
||||
}
|
||||
|
||||
// Comment fetching is bounded by a request budget; exhaustion is reported as
|
||||
// incompleteness instead of passing as an empty list.
|
||||
function makeCommentFetcher(env) {
|
||||
let budget = MAX_COMMENT_REQUESTS;
|
||||
return (number) => {
|
||||
if (budget-- <= 0) return { items: [], error: 'comment request budget exhausted' };
|
||||
return fetchAllPages(`repos/${env.GITHUB_REPOSITORY}/issues/${number}/comments?per_page=100`, env);
|
||||
};
|
||||
}
|
||||
|
||||
// Four observed states, kept distinct: merged / open-unmerged /
|
||||
// closed-unmerged / unknown (404, rate limit, transient failure).
|
||||
function fetchPullState(env, number) {
|
||||
try {
|
||||
const pr = JSON.parse(runGh(['api', `repos/${env.GITHUB_REPOSITORY}/pulls/${number}`], env));
|
||||
if (pr.merged === true) return { observed: 'merged' };
|
||||
if (pr.state === 'open') return { observed: 'open-unmerged' };
|
||||
if (pr.state === 'closed') return { observed: 'closed-unmerged' };
|
||||
return { observed: 'unknown', reason: 'unexpected PR payload' };
|
||||
} catch (error) {
|
||||
return { observed: 'unknown', reason: describeGhError(error) };
|
||||
}
|
||||
}
|
||||
|
||||
function fetchPullStates(env, prNumbers, incomplete) {
|
||||
const states = new Map();
|
||||
if (prNumbers.length > MAX_PR_CHECKS) {
|
||||
incomplete.push(`${prNumbers.length - MAX_PR_CHECKS} cited PR(s) not checked: PR check limit of ${MAX_PR_CHECKS} reached`);
|
||||
}
|
||||
for (const number of prNumbers.slice(0, MAX_PR_CHECKS)) {
|
||||
states.set(number, fetchPullState(env, number));
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const env = process.env;
|
||||
if (!env.GITHUB_REPOSITORY || !env.GITHUB_STEP_SUMMARY) {
|
||||
console.error('audit-closed-references: requires GITHUB_REPOSITORY and GITHUB_STEP_SUMMARY');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
const issuesResult = fetchAllPages(
|
||||
`repos/${env.GITHUB_REPOSITORY}/issues?state=closed&sort=updated&direction=desc&per_page=100`, env
|
||||
);
|
||||
const fetchComments = makeCommentFetcher(env);
|
||||
const { entries, incomplete } = collectEntries(
|
||||
() => issuesResult, fetchComments, Date.now(), DEFAULT_WINDOW_DAYS
|
||||
);
|
||||
const pullStates = fetchPullStates(env, uniqueClaimPrs(entries), incomplete);
|
||||
const verdicts = buildVerdicts(entries, pullStates);
|
||||
const references = collectReferences(entries);
|
||||
const report = buildSummary(verdicts, references, incomplete).join('\n');
|
||||
fs.appendFileSync(env.GITHUB_STEP_SUMMARY, report + '\n');
|
||||
console.log(report);
|
||||
// Advisory by design: findings land in the summary; the run stays green so
|
||||
// the weekly audit is never the thing that fails.
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_WINDOW_DAYS,
|
||||
MAX_COMMENT_REQUESTS,
|
||||
CLAIM_PATTERN,
|
||||
stripNonEvidence,
|
||||
isNegated,
|
||||
extractRefs,
|
||||
selectRecentClosedIssues,
|
||||
selectWindowComments,
|
||||
extractEvidence,
|
||||
collectEntries,
|
||||
uniqueClaimPrs,
|
||||
collectReferences,
|
||||
buildVerdicts,
|
||||
buildSummary,
|
||||
fetchAllPages,
|
||||
fetchPullState,
|
||||
};
|
||||
|
||||
if (require.main === module) main();
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env node
|
||||
/** Moderate Issue creation metadata only. Never execute or print contributor text. */
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { githubAPI, listPages, validatePolicy, strongestWindow, blockAuthor } = require('./pr-burst-guard');
|
||||
|
||||
const LOGIN = /^[a-z\d](?:[a-z\d-]{0,38})(?:\[bot\])?$/i;
|
||||
const CAP_MARKER = '<!-- ecc-issue-open-cap -->';
|
||||
const ALERT_MARKER = '<!-- ecc-issue-burst:';
|
||||
const isIssue = issue => !issue.pull_request;
|
||||
const byCreation = (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at) || a.number - b.number;
|
||||
|
||||
function capExcess(openRows, current, policy, alreadyClosed = new Set(), action = 'opened') {
|
||||
validatePolicy(policy);
|
||||
const open = [...new Map([...openRows, current].map(issue => [issue.number, issue])).values()]
|
||||
.filter(issue => isIssue(issue) && issue.user.id === current.user.id
|
||||
&& issue.state === 'open' && !alreadyClosed.has(issue.number)).sort(byCreation);
|
||||
const currentIndex = open.findIndex(issue => issue.number === current.number);
|
||||
const excess = open.length <= policy.maxOpen || currentIndex < 0 ? []
|
||||
: action === 'reopened' ? [open[currentIndex]]
|
||||
: open.filter((issue, index) => index >= policy.maxOpen && byCreation(issue, current) >= 0);
|
||||
return { openCount: open.length, maxOpen: policy.maxOpen,
|
||||
capExcess: excess.map(issue => ({ number: issue.number, state: issue.state })) };
|
||||
}
|
||||
|
||||
async function notify(api, root, current, result, policy) {
|
||||
const day = result.until.slice(0, 10);
|
||||
const marker = `${ALERT_MARKER}${current.user.id}:${day} -->`;
|
||||
const rows = await listPages(api, `${root}/issues?state=all&sort=created&direction=desc`,
|
||||
batch => batch.some(issue => issue.created_at?.slice(0, 10) < day));
|
||||
const existing = rows.find(issue => isIssue(issue) && issue.user?.login === 'github-actions[bot]'
|
||||
&& issue.body?.includes(marker));
|
||||
const escalation = '<!-- ecc-issue-burst:block-threshold -->';
|
||||
if (existing?.body.includes(escalation) && !result.block) return;
|
||||
const mentions = policy.notify.map(login => `@${login}`).join(' ');
|
||||
const body = [marker, result.block ? escalation : '', `${mentions}: Issue submission moderation triggered.`, '',
|
||||
`Author: @${current.user.login} (user ID ${current.user.id}).`,
|
||||
`Observed: ${result.count} Issue creations between ${result.since} and ${result.until}.`,
|
||||
`Policy: close Issues beyond ${policy.closeAbove}; block beyond ${policy.blockAbove} in ${policy.windowMinutes} minutes.`,
|
||||
`Blocking: ${result.blockStatus}.`, `Excess Issues: ${result.excess.map(issue => `#${issue.number}`).join(', ') || 'none'}.`,
|
||||
`Enforcement errors: ${result.errors.join('; ') || 'none'}.`, '',
|
||||
'Counts include closed Issues and exclude pull requests. Review the Actions run before lifting an account block.']
|
||||
.filter(Boolean).join('\n');
|
||||
if (!existing) await api('POST', `${root}/issues`, { title: `Issue burst alert: ${current.user.login}`, body });
|
||||
else {
|
||||
if (result.block && !existing.body.includes(escalation)) {
|
||||
await api('POST', `${root}/issues/${existing.number}/comments`, {
|
||||
body: `${mentions}: the Issue burst escalated. Blocking: ${result.blockStatus}.`,
|
||||
});
|
||||
}
|
||||
await api('PATCH', `${root}/issues/${existing.number}`, { body });
|
||||
}
|
||||
}
|
||||
|
||||
async function enforceCap(api, root, issue, current, result) {
|
||||
try {
|
||||
await api('PATCH', `${root}/issues/${issue.number}`, { state: 'closed' });
|
||||
const comments = await listPages(api, `${root}/issues/${issue.number}/comments?sort=created`);
|
||||
if (comments.some(comment => comment.user?.login === 'github-actions[bot]'
|
||||
&& comment.body?.includes(CAP_MARKER))) return;
|
||||
await api('POST', `${root}/issues/${issue.number}/comments`, { body: [CAP_MARKER,
|
||||
`Closed automatically: @${current.user.login} has ${result.openCount} open Issues in this repository, above the limit of ${result.maxOpen} per author.`,
|
||||
'', 'Close older Issues or wait for them to be resolved, then reopen this one. This limit protects maintainer triage capacity.',
|
||||
'Policy: `.github/ISSUE_MODERATION.md`.'].join('\n') });
|
||||
} catch (error) { result.errors.push(`#${issue.number}: ${error.message}`); }
|
||||
}
|
||||
|
||||
async function moderate({ api, blockAPI, repository, number, action = 'opened', policy, dryRun = false, now = Date.now() }) {
|
||||
validatePolicy(policy);
|
||||
if (!/^[a-z\d-]+\/[a-z\d_.-]+$/i.test(repository) || !Number.isSafeInteger(number) || number < 1) {
|
||||
throw new Error('Invalid repository or Issue number');
|
||||
}
|
||||
if (!['opened', 'reopened'].includes(action)) throw new Error('Unsupported Issue event');
|
||||
const root = `/repos/${repository}`;
|
||||
const repo = await api('GET', root);
|
||||
const current = await api('GET', `${root}/issues/${number}`);
|
||||
if (!isIssue(current)) return { skipped: 'pull request' };
|
||||
if (!LOGIN.test(current.user.login)) throw new Error('Invalid Issue author login');
|
||||
// The guard's own alert Issues must never enter the moderation ledger.
|
||||
if (current.user.login === 'github-actions[bot]') return { skipped: 'guard bot' };
|
||||
let permission;
|
||||
try { permission = (await api('GET', `${root}/collaborators/${current.user.login}/permission`)).permission; }
|
||||
catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
permission = 'none';
|
||||
}
|
||||
const burstExempt = ['admin', 'maintain', 'write'].includes(permission);
|
||||
let result;
|
||||
if (burstExempt) result = { author: current.user.login, burstExempt, dryRun, errors: [], excess: [],
|
||||
blockStatus: 'Exempt from burst threshold' };
|
||||
else {
|
||||
const end = action === 'opened' ? Date.parse(current.created_at) : now;
|
||||
const since = end - policy.windowMinutes * 60000;
|
||||
const rows = (await listPages(api, `${root}/issues?state=all&sort=created&direction=desc`,
|
||||
batch => batch.some(issue => Date.parse(issue.created_at) < since))).filter(isIssue);
|
||||
result = { ...strongestWindow(rows, current, policy, end), author: current.user.login,
|
||||
burstExempt, dryRun, errors: [], blockStatus: 'Below blocking threshold' };
|
||||
}
|
||||
const openRows = (await listPages(api, `${root}/issues?state=open&sort=created&direction=desc`)).filter(isIssue);
|
||||
Object.assign(result, capExcess(openRows, current, policy, new Set(result.excess.map(issue => issue.number)), action));
|
||||
if (dryRun) {
|
||||
if (result.block) result.blockStatus = 'Dry run: would attempt owner-scoped blocking';
|
||||
return result;
|
||||
}
|
||||
if (result.excess.length) {
|
||||
if (result.block) result.blockStatus = await blockAuthor(blockAPI, repo.owner, current.user.login);
|
||||
for (const issue of result.excess) {
|
||||
if (issue.state !== 'open') continue;
|
||||
try {
|
||||
await api('PATCH', `${root}/issues/${issue.number}`, { state: 'closed' });
|
||||
await api('PUT', `${root}/issues/${issue.number}/lock`, { lock_reason: 'spam' });
|
||||
} catch (error) { result.errors.push(`#${issue.number}: ${error.message}`); }
|
||||
}
|
||||
await notify(api, root, current, result, policy);
|
||||
}
|
||||
for (const issue of result.capExcess) await enforceCap(api, root, issue, current, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const dryRun = process.argv.includes('--dry-run');
|
||||
const event = process.env.GITHUB_EVENT_PATH ? JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) : {};
|
||||
const issueIndex = process.argv.indexOf('--issue');
|
||||
const number = issueIndex >= 0 ? Number(process.argv[issueIndex + 1]) : event.issue?.number;
|
||||
const policy = JSON.parse(fs.readFileSync(path.join(__dirname, '../../.github/issue-submission-policy.json'), 'utf8'));
|
||||
const result = await moderate({ api: githubAPI(process.env.GITHUB_TOKEN),
|
||||
blockAPI: !dryRun && process.env.PR_MODERATION_BLOCK_TOKEN ? githubAPI(process.env.PR_MODERATION_BLOCK_TOKEN) : undefined,
|
||||
repository: process.env.GITHUB_REPOSITORY, number, action: event.action || 'opened', policy, dryRun });
|
||||
const report = JSON.stringify(result, null, 2);
|
||||
console.log(report);
|
||||
if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY,
|
||||
`## Issue submission guard\n\n\`\`\`json\n${report}\n\`\`\`\n`);
|
||||
if (result.errors?.length || /^(Failed|Unavailable):/.test(result.blockStatus || '')) process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
module.exports = { capExcess, moderate };
|
||||
@@ -230,4 +230,4 @@ async function main() {
|
||||
}
|
||||
|
||||
if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
module.exports = { evaluate, moderate, githubAPI, listPages, validatePolicy, strongestWindow, capExcess };
|
||||
module.exports = { evaluate, moderate, githubAPI, listPages, validatePolicy, strongestWindow, capExcess, blockAuthor };
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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 };
|
||||
@@ -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)
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const { isGitRepo, getGitModifiedFiles, readFile, log } = require('../lib/utils');
|
||||
const path = require('path');
|
||||
const { isGitRepo, getGitModifiedFiles, readFile, log, runCommand } = require('../lib/utils');
|
||||
|
||||
// Files where console.log is expected and should not trigger warnings
|
||||
const EXCLUDED_PATTERNS = [
|
||||
@@ -27,6 +28,18 @@ const EXCLUDED_PATTERNS = [
|
||||
];
|
||||
|
||||
const MAX_DIRECT_STDIN_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
// This Stop hook inspects the session's working directory. Inherited GIT_*
|
||||
// variables from another Git process can silently redirect discovery and diff
|
||||
// commands to a different repository, so give every Git call the same clean env.
|
||||
function sessionGitOptions() {
|
||||
const env = { ...process.env };
|
||||
for (const name of Object.keys(env)) {
|
||||
if (name.toUpperCase().startsWith('GIT_')) delete env[name];
|
||||
}
|
||||
return { env };
|
||||
}
|
||||
|
||||
let data = '';
|
||||
let stdinBytes = 0;
|
||||
let oversized = false;
|
||||
@@ -61,19 +74,23 @@ function passThroughAndExit() {
|
||||
|
||||
process.stdin.on('end', () => {
|
||||
try {
|
||||
if (!isGitRepo()) {
|
||||
const gitOptions = sessionGitOptions();
|
||||
if (!isGitRepo(gitOptions)) {
|
||||
passThroughAndExit();
|
||||
return;
|
||||
}
|
||||
|
||||
const files = getGitModifiedFiles(['\\.tsx?$', '\\.jsx?$'])
|
||||
.filter(f => fs.existsSync(f))
|
||||
// git reports paths from the repository root, and the session can run in a
|
||||
// subdirectory of it, so read each file from the root.
|
||||
const root = runCommand('git rev-parse --show-toplevel', gitOptions).output;
|
||||
const files = getGitModifiedFiles(['\\.tsx?$', '\\.jsx?$'], gitOptions)
|
||||
.filter(f => fs.existsSync(path.join(root, f)))
|
||||
.filter(f => !EXCLUDED_PATTERNS.some(pattern => pattern.test(f)));
|
||||
|
||||
let hasConsole = false;
|
||||
|
||||
for (const file of files) {
|
||||
const content = readFile(file);
|
||||
const content = readFile(path.join(root, file));
|
||||
if (content && content.includes('console.log')) {
|
||||
log(`[Hook] WARNING: console.log found in ${file}`);
|
||||
hasConsole = true;
|
||||
|
||||
@@ -117,8 +117,9 @@ const PROTECTED_FILES = new Set([
|
||||
const PROTECTED_PATTERNS = [
|
||||
// eslint.config.base.mjs, prettier.config.shared.cjs, stylelint.config.local.js ...
|
||||
/^(eslint|prettier|stylelint|commitlint|oxlint)\.config(\.[A-Za-z0-9_-]+)*\.(js|mjs|cjs|ts|mts|cts)$/i,
|
||||
// .eslintrc.base.json, .prettierrc.shared.yml ...
|
||||
/^\.(eslintrc|prettierrc|stylelintrc|markdownlintrc)(\.[A-Za-z0-9_-]+)*\.(js|cjs|mjs|json|jsonc|yml|yaml|toml)$/i,
|
||||
// .eslintrc.base.json, .prettierrc.shared.yml ... Prettier also reads
|
||||
// `.prettierrc.ts`, `.mts`, `.cts` and `.json5`.
|
||||
/^\.(eslintrc|prettierrc|stylelintrc|markdownlintrc)(\.[A-Za-z0-9_-]+)*\.(js|cjs|mjs|ts|mts|cts|json|jsonc|json5|yml|yaml|toml)$/i,
|
||||
];
|
||||
|
||||
function isProtectedName(basename) {
|
||||
@@ -156,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
|
||||
@@ -193,7 +213,7 @@ function run(inputOrRaw, options = {}) {
|
||||
}
|
||||
|
||||
if (!exists) {
|
||||
return { exitCode: 0 };
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -206,7 +226,7 @@ function run(inputOrRaw, options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
return { exitCode: 0 };
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = { run };
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -56,7 +56,9 @@ function readToken(input, startIndex) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '\\' && quote === '"' && index + 1 < input.length) {
|
||||
// Inside double quotes, bash drops a backslash only before $ ` " \ or a
|
||||
// newline, so `"echo ready\;"` keeps its `\;` for tmux.
|
||||
if (ch === '\\' && quote === '"' && index + 1 < input.length && '$`"\\\n'.includes(input[index + 1])) {
|
||||
token += input[index + 1];
|
||||
index += 2;
|
||||
continue;
|
||||
@@ -104,7 +106,7 @@ function normalizeCommandWord(token) {
|
||||
return base.replace(/\.(cmd|exe|bat)$/i, '');
|
||||
}
|
||||
|
||||
function getLeadingCommandWord(segment) {
|
||||
function getLeadingCommand(segment) {
|
||||
let index = 0;
|
||||
let activeWrapper = null;
|
||||
let skipNextValue = false;
|
||||
@@ -145,7 +147,7 @@ function getLeadingCommandWord(segment) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return normalizedToken;
|
||||
return { word: normalizedToken, end: index };
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -160,7 +162,19 @@ process.stdin.on('data', chunk => {
|
||||
}
|
||||
});
|
||||
|
||||
const TMUX_LAUNCHER = /^\s*tmux\s+(new|new-session|new-window|split-window)\b/;
|
||||
// tmux commands, and their aliases, that run their shell command in a tmux pane,
|
||||
// where its output stays readable. run-shell and `tmux -c` run it without one.
|
||||
const TMUX_PANE_COMMANDS = new Set([
|
||||
'new-session', 'new',
|
||||
'new-window', 'neww',
|
||||
'split-window', 'splitw',
|
||||
'respawn-pane', 'respawnp',
|
||||
'respawn-window', 'respawnw',
|
||||
'send-keys', 'send'
|
||||
]);
|
||||
// tmux's own options that take a value (`-L work`, `-Lwork`, or the last of a
|
||||
// cluster such as `-vL work`).
|
||||
const TMUX_OPTION_VALUE_LETTERS = new Set(['f', 'L', 'S', 'T']);
|
||||
// Trailing (?![\w-]) rather than \b: \b treats a hyphen as a word boundary, so
|
||||
// `dev\b` matches the `dev` prefix of distinct scripts like `dev-setup` /
|
||||
// `dev-docs` / `dev-build` and wrongly blocks them. The lookahead still matches
|
||||
@@ -199,10 +213,51 @@ function collectCheckSegments(cmd) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true when the tmux invocation that starts at `index` runs the dev
|
||||
* server in a pane. The tmux commands follow tmux's own options (`-L work`,
|
||||
* `-f conf`), and the executable may come through a path or an env prefix, so
|
||||
* this reads the parsed tokens instead of the start of the segment. A sequence
|
||||
* (`new-session -d \; run-shell ...`) is exempt only when every command in it
|
||||
* that runs the dev server is a pane command.
|
||||
*/
|
||||
function isTmuxPaneLaunch(segment, index) {
|
||||
const tokens = [];
|
||||
for (let parsed = readToken(segment, index); parsed; parsed = readToken(segment, parsed.end)) {
|
||||
if (parsed.token) tokens.push(parsed.token);
|
||||
}
|
||||
|
||||
let next = 0;
|
||||
for (; next < tokens.length && isOptionToken(tokens[next]); next++) {
|
||||
const letters = tokens[next].slice(1);
|
||||
for (let i = 0; i < letters.length; i++) {
|
||||
// -c runs its shell command without a pane.
|
||||
if (letters[i] === 'c') return false;
|
||||
if (TMUX_OPTION_VALUE_LETTERS.has(letters[i])) {
|
||||
if (i === letters.length - 1) next++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tmux ends a command at a `;` argument and at a `;` that ends an argument
|
||||
// (`'npm run dev;'`); an escaped `\;` at the end stays literal.
|
||||
const commands = [[]];
|
||||
for (const token of tokens.slice(next)) {
|
||||
const ends = token.endsWith(';') && !token.endsWith('\\;');
|
||||
const value = ends ? token.slice(0, -1) : token;
|
||||
if (value) commands[commands.length - 1].push(value);
|
||||
if (ends) commands.push([]);
|
||||
}
|
||||
const devCommands = commands.filter(command => DEV_PATTERN.test(command.join(' ')));
|
||||
return devCommands.length > 0 && devCommands.every(command => TMUX_PANE_COMMANDS.has(command[0]));
|
||||
}
|
||||
|
||||
function isBlockedDevSegment(segment) {
|
||||
const commandWord = getLeadingCommandWord(segment);
|
||||
if (!commandWord || !DEV_COMMAND_WORDS.has(commandWord)) return false;
|
||||
return DEV_PATTERN.test(segment) && !TMUX_LAUNCHER.test(segment);
|
||||
const command = getLeadingCommand(segment);
|
||||
if (!command || !DEV_COMMAND_WORDS.has(command.word)) return false;
|
||||
if (!DEV_PATTERN.test(segment)) return false;
|
||||
return !(command.word === 'tmux' && isTmuxPaneLaunch(segment, command.end));
|
||||
}
|
||||
|
||||
process.stdin.on('end', () => {
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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) ||
|
||||
|
||||
@@ -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}`);
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
@@ -128,10 +128,16 @@ function findTsConfigDir(filePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// tsc --pretty false starts each diagnostic with the file it is about:
|
||||
// `src/a.ts(1,14): error TS2322: ...`. Compare that path instead of looking for
|
||||
// the edited path anywhere in the line, which let a root `index.ts` claim the
|
||||
// errors of `src/index.ts`, and `src/utils.ts` those of `web/src/utils.ts`.
|
||||
function diagnosticMatchesFile(line, paths) {
|
||||
const normalizedLine = line.replace(/\\/g, '/');
|
||||
const location = /^(.+?)\(\d+,\d+\): /.exec(line);
|
||||
if (!location) return false;
|
||||
const file = location[1].replace(/\\/g, '/');
|
||||
for (const candidate of paths) {
|
||||
if (normalizedLine.includes(candidate.replace(/\\/g, '/'))) return true;
|
||||
if (file === candidate.replace(/\\/g, '/')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 || {}) };
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -48,7 +48,7 @@ function readManagedHookConfig(env = process.env) {
|
||||
if (!configPath || !fs.existsSync(configPath)) return {};
|
||||
|
||||
try {
|
||||
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
||||
const config = JSON.parse(fs.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));
|
||||
return config?.hooks
|
||||
&& typeof config.hooks === 'object'
|
||||
&& !Array.isArray(config.hooks)
|
||||
|
||||
@@ -21,8 +21,15 @@ function normalizeFailureReason(reason) {
|
||||
.replace(/\d{4}-\d{2}-\d{2}[t ]\d{2}:\d{2}:\d{2}[.\dz]*/g, '<timestamp>')
|
||||
// Strip UUIDs (already lowercased)
|
||||
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '<uuid>')
|
||||
// Strip file paths
|
||||
.replace(/\/[\w./-]+/g, '<path>')
|
||||
// Quoted Windows paths preserve spaces and apostrophes inside path components.
|
||||
// A closing quote must be followed by a delimiter, not another name character.
|
||||
.replace(/(["'])(?:[a-z]:[\\/]|\\\\)[^\r\n]*?\1(?=[:\s),;.!?]|$)/gu, '$1<path>$1')
|
||||
// Directories may contain spaces, but trailing whitespace separates diagnostic prose.
|
||||
// Unquoted spaced leaves allow one final dotted token; longer prose stays diagnostic.
|
||||
// Quote paths with multiple spaces in the final filename to remove ambiguity.
|
||||
.replace(/(?:\b[a-z]:|\\)[\\/](?:[^\\/:*?"<>|\r\n]*[^\s\\/:*?"<>|][\\/])*[^\s\\/:*?"<>|(),;]+(?: [^\s\\/:*?"<>|]+\.[^\s\\/:*?"<>|]+(?=:))?[\\/]*/gu, '<path>')
|
||||
// Strip remaining file paths
|
||||
.replace(/(?:\b[a-z]:)?[\\/][\w./\\-]+/g, '<path>')
|
||||
// Collapse whitespace
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
@@ -60,6 +67,14 @@ function groupFailures(skillRuns) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
function compareTimestampsDescending(a, b) {
|
||||
const timeA = Date.parse(a);
|
||||
const timeB = Date.parse(b);
|
||||
if (Number.isNaN(timeA)) return Number.isNaN(timeB) ? 0 : 1;
|
||||
if (Number.isNaN(timeB)) return -1;
|
||||
return timeB - timeA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect recurring failure patterns from skill runs.
|
||||
*
|
||||
@@ -79,7 +94,7 @@ function detectPatterns(skillRuns, options = {}) {
|
||||
}
|
||||
|
||||
const sortedRuns = [...group.runs].sort(
|
||||
(a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')
|
||||
(a, b) => compareTimestampsDescending(a.createdAt, b.createdAt)
|
||||
);
|
||||
|
||||
const firstSeen = sortedRuns[sortedRuns.length - 1].createdAt || null;
|
||||
@@ -106,7 +121,7 @@ function detectPatterns(skillRuns, options = {}) {
|
||||
// Sort by count descending, then by lastSeen descending
|
||||
return patterns.sort((a, b) => {
|
||||
if (b.count !== a.count) return b.count - a.count;
|
||||
return (b.lastSeen || '').localeCompare(a.lastSeen || '');
|
||||
return compareTimestampsDescending(a.lastSeen, b.lastSeen);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -201,7 +201,8 @@ function addMatchingRuleOperations(operations, options) {
|
||||
sourcePath,
|
||||
sourceRelativePath,
|
||||
destinationPath,
|
||||
strategy: options.strategy || 'flatten-copy'
|
||||
strategy: options.strategy || 'flatten-copy',
|
||||
contentTransform: options.contentTransform,
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -269,7 +270,7 @@ function planClaudeStyleLegacyInstall(context, { adapterId, adapterRootInput, ru
|
||||
function planClaudeLegacyInstall(context) {
|
||||
return planClaudeStyleLegacyInstall(context, {
|
||||
adapterId: 'claude',
|
||||
adapterRootInput: { homeDir: context.homeDir },
|
||||
adapterRootInput: { homeDir: context.homeDir, env: context.env },
|
||||
rulesDir: context.claudeRulesDir || null
|
||||
});
|
||||
}
|
||||
@@ -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',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -461,6 +464,7 @@ function createLegacyInstallPlan(options = {}) {
|
||||
sourceRoot,
|
||||
projectRoot,
|
||||
homeDir,
|
||||
env: options.env || {},
|
||||
languages: Array.isArray(options.languages) ? options.languages : [],
|
||||
claudeRulesDir: options.claudeRulesDir || process.env.CLAUDE_RULES_DIR || null
|
||||
};
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { resolveInvocationEnvironment } = require('../invocation-environment');
|
||||
|
||||
const {
|
||||
HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
|
||||
@@ -7,6 +9,7 @@ const {
|
||||
isForeignPlatformPath,
|
||||
normalizeRelativePath,
|
||||
planClaudeHooksOperations,
|
||||
convertWindowsPathToWSL,
|
||||
} = require('./helpers');
|
||||
|
||||
const CLAUDE_ECC_NAMESPACE = 'ecc';
|
||||
@@ -47,11 +50,52 @@ function getClaudeManagedDestinationPath(adapter, sourceRelativePath, input) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand leading ~, ~/, ~\ against the home directory.
|
||||
* Mirrors the expansion in resolveEccRoot to keep install and runtime roots in sync.
|
||||
*/
|
||||
function expandTilde(inputPath, homeDir) {
|
||||
if (typeof inputPath !== 'string') return inputPath;
|
||||
const trimmed = inputPath.trim();
|
||||
if (trimmed === '~') return homeDir;
|
||||
if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
|
||||
return path.join(homeDir, trimmed.slice(2));
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// Claude Code loads its user-level config from CLAUDE_CONFIG_DIR when set,
|
||||
// otherwise ~/.claude. Resolve the install root the same way the runtime does
|
||||
// (see resolveClaudePaths/inventory and getDefaultClaudeAgentDataHome) so an
|
||||
// install lands where Claude Code will actually read it; without this, ECC
|
||||
// writes to ~/.claude and "installs, but nothing loads" whenever CLAUDE_CONFIG_DIR
|
||||
// redirects the config root (common on WSL / dev-container / dotfile setups).
|
||||
// On WSL, convert Windows paths (e.g., C:\Users\name\.claude) to WSL paths
|
||||
// (/mnt/c/Users/name/.claude) so the installer writes to the correct location.
|
||||
function resolveClaudeConfigRoot(options = {}) {
|
||||
const environment = resolveInvocationEnvironment(options);
|
||||
const configured = environment && environment.CLAUDE_CONFIG_DIR;
|
||||
const homeDir = path.resolve(options.homeDir || os.homedir());
|
||||
if (typeof configured === 'string' && configured.trim() !== '') {
|
||||
const normalized = configured.trim();
|
||||
const converted = convertWindowsPathToWSL(normalized);
|
||||
// After WSL conversion, a blank result means the config dir was invalid.
|
||||
// Fall back to the default Claude directory just like the runtime adapter does.
|
||||
const expanded = expandTilde(converted, homeDir);
|
||||
if (typeof expanded === 'string' && expanded.trim() === '') {
|
||||
return path.join(homeDir, '.claude');
|
||||
}
|
||||
return path.resolve(expanded);
|
||||
}
|
||||
return path.join(homeDir, '.claude');
|
||||
}
|
||||
|
||||
module.exports = createInstallTargetAdapter({
|
||||
id: 'claude-home',
|
||||
target: 'claude',
|
||||
kind: 'home',
|
||||
rootSegments: ['.claude'],
|
||||
resolveRoot: resolveClaudeConfigRoot,
|
||||
installStatePathSegments: ['ecc', 'install-state.json'],
|
||||
excludedSourcePaths: HOME_INSTALL_EXCLUDED_SOURCE_PATHS,
|
||||
nativeRootRelativePath: '.claude-plugin',
|
||||
@@ -63,6 +107,7 @@ module.exports = createInstallTargetAdapter({
|
||||
repoRoot: input.repoRoot,
|
||||
projectRoot: input.projectRoot,
|
||||
homeDir: input.homeDir,
|
||||
env: input.env,
|
||||
};
|
||||
|
||||
const operations = modules.flatMap(module => {
|
||||
|
||||
@@ -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
|
||||
));
|
||||
});
|
||||
},
|
||||
|
||||
@@ -7,6 +7,57 @@ const {
|
||||
} = require('../install/claude-settings');
|
||||
const { METADATA_FILENAME } = require('../hooks-config');
|
||||
|
||||
// Memoized WSL detection (avoids repeated /proc/version reads)
|
||||
let _isWSL = null;
|
||||
function isWSL() {
|
||||
if (_isWSL !== null) return _isWSL;
|
||||
if (process.platform !== 'linux') {
|
||||
_isWSL = false;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
_isWSL = fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft');
|
||||
} catch {
|
||||
_isWSL = false;
|
||||
}
|
||||
return _isWSL;
|
||||
}
|
||||
|
||||
// Reset WSL detection memoization (for testing only)
|
||||
function resetWSLDetection() {
|
||||
_isWSL = null;
|
||||
}
|
||||
|
||||
// Set WSL detection for testing (for testing only)
|
||||
function setWSLForTesting(value) {
|
||||
_isWSL = value;
|
||||
}
|
||||
|
||||
// Windows path pattern: drive letter followed by :\ or :/
|
||||
const WINDOWS_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
// Compact WSL conversion snippet for inline resolvers embedded in commands and hooks.
|
||||
// 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.
|
||||
* Example: "C:\Users\name" -> "/mnt/c/Users/name"
|
||||
* Example: "D:/Projects" -> "/mnt/d/Projects"
|
||||
* Returns the original path if it's not a Windows path or not on WSL.
|
||||
*/
|
||||
function convertWindowsPathToWSL(windowsPath) {
|
||||
if (!isWSL()) return windowsPath;
|
||||
if (typeof windowsPath !== 'string') return windowsPath;
|
||||
const trimmed = windowsPath.trim();
|
||||
if (!WINDOWS_PATH_PATTERN.test(trimmed)) return trimmed;
|
||||
const driveLetter = trimmed[0].toLowerCase();
|
||||
const rest = trimmed.slice(2).replace(/\\/g, '/');
|
||||
return `/mnt/${driveLetter}${rest}`;
|
||||
}
|
||||
|
||||
const PLATFORM_SOURCE_PATH_OWNERS = Object.freeze({
|
||||
'.claude-plugin': 'claude',
|
||||
'.codex': 'codex',
|
||||
@@ -439,6 +490,12 @@ module.exports = {
|
||||
createNamespacedFlatRuleOperations,
|
||||
createRemappedOperation,
|
||||
isForeignPlatformPath,
|
||||
listRelativeFiles,
|
||||
normalizeRelativePath,
|
||||
planClaudeHooksOperations,
|
||||
isWSL,
|
||||
resetWSLDetection,
|
||||
setWSLForTesting,
|
||||
convertWindowsPathToWSL,
|
||||
INLINE_WSL_CONVERSION,
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
@@ -11,8 +11,9 @@ const {
|
||||
const { readInstallState, writeInstallState } = require('../install-state');
|
||||
const {
|
||||
assertHookConsentReady,
|
||||
disableOpenCodeHookPluginRegistration,
|
||||
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,14 +473,23 @@ 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');
|
||||
// Validate first so malformed JSON retains its source context.
|
||||
disableOpenCodeHookPluginRegistration(text, operation.sourceRelativePath || operation.destinationPath);
|
||||
const config = JSON.parse(text);
|
||||
const relativePath = operation.sourceRelativePath || operation.destinationPath;
|
||||
// JSONC-tolerant parse so a comment in the user's config does not crash
|
||||
// the install; the ownership guard never writes this file (issue #3546).
|
||||
const config = parseJsoncConfig(text, relativePath);
|
||||
// Keep the same shape error the strict parser surfaced via
|
||||
// disableOpenCodeHookPluginRegistration: a non-array plugin must not
|
||||
// silently count as inactive.
|
||||
if (config.plugin !== undefined && !Array.isArray(config.plugin)) {
|
||||
throw new Error(`Invalid ${relativePath}: plugin must be an array`);
|
||||
}
|
||||
return !Array.isArray(config.plugin) || !config.plugin.includes('./plugins');
|
||||
}
|
||||
|
||||
@@ -497,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}`);
|
||||
@@ -705,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);
|
||||
@@ -768,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;
|
||||
@@ -796,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 => (
|
||||
@@ -878,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;
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -26,12 +45,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));
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -45,16 +45,109 @@ function normalizeOperationPath(value) {
|
||||
return String(value || '').replace(/\\/g, '/').toLowerCase();
|
||||
}
|
||||
|
||||
function disableOpenCodeHookPluginRegistration(content, sourceRelativePath) {
|
||||
/**
|
||||
* Parse an OpenCode config the way OpenCode itself does: comments and the
|
||||
* trailing commas they hide are legal (JSONC). The installer only ever
|
||||
* reads these files (the ownership guard never writes user-owned configs),
|
||||
* so a tolerant read prevents a membership check from crashing the install
|
||||
* on a config OpenCode accepts.
|
||||
*/
|
||||
function parseJsoncConfig(content, sourceRelativePath) {
|
||||
let config;
|
||||
try {
|
||||
config = JSON.parse(content);
|
||||
config = JSON.parse(stripJsonc(content));
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse ${sourceRelativePath}: ${error.message}`);
|
||||
}
|
||||
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
||||
throw new Error(`Invalid ${sourceRelativePath}: expected a JSON object`);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function isLineBreak(ch) {
|
||||
return ch === '\n' || ch === '\r';
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance past whitespace and // or /* *\/ comments; returns the index of
|
||||
* the next significant character.
|
||||
*/
|
||||
function skipJsoncTrivia(input, start) {
|
||||
let j = start;
|
||||
for (;;) {
|
||||
while (j < input.length && /\s/.test(input[j])) j += 1;
|
||||
if (input[j] === '/' && input[j + 1] === '/') {
|
||||
while (j < input.length && !isLineBreak(input[j])) j += 1;
|
||||
continue;
|
||||
}
|
||||
if (input[j] === '/' && input[j + 1] === '*') {
|
||||
j += 2;
|
||||
while (j < input.length && !(input[j] === '*' && input[j + 1] === '/')) j += 1;
|
||||
if (j >= input.length) throw new Error('Unterminated block comment');
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
}
|
||||
|
||||
function isJsoncTrailingComma(input, index, previousSignificant) {
|
||||
const next = skipJsoncTrivia(input, index + 1);
|
||||
// Preserve commas in empty containers or after another separator so
|
||||
// JSON.parse rejects them; it validates the remaining value syntax.
|
||||
return (input[next] === '}' || input[next] === ']')
|
||||
&& previousSignificant !== null && !'[{,:'.includes(previousSignificant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip // and /* *\/ comments and the trailing commas they hide, without
|
||||
* touching string contents (URLs like "https://..." must survive intact).
|
||||
*/
|
||||
function stripJsonc(input) {
|
||||
let out = '';
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
let previousSignificant = null;
|
||||
for (let i = 0; i < input.length; i += 1) {
|
||||
const ch = input[i];
|
||||
if (inString) {
|
||||
out += ch;
|
||||
if (escaped) escaped = false;
|
||||
else if (ch === '\\') escaped = true;
|
||||
else if (ch === '"') inString = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inString = true;
|
||||
out += ch;
|
||||
previousSignificant = '"';
|
||||
continue;
|
||||
}
|
||||
if (ch === '/' && input[i + 1] === '/') {
|
||||
while (i < input.length && !isLineBreak(input[i])) i += 1;
|
||||
out += '\n';
|
||||
continue;
|
||||
}
|
||||
if (ch === '/' && input[i + 1] === '*') {
|
||||
i += 2;
|
||||
while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i += 1;
|
||||
if (i >= input.length) throw new Error('Unterminated block comment');
|
||||
i += 1; // consume the closing '/'
|
||||
out += ' ';
|
||||
continue;
|
||||
}
|
||||
if (ch === ',') {
|
||||
if (isJsoncTrailingComma(input, i, previousSignificant)) continue;
|
||||
}
|
||||
out += ch;
|
||||
if (!/\s/.test(ch)) previousSignificant = ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function disableOpenCodeHookPluginRegistration(content, sourceRelativePath) {
|
||||
const config = parseJsoncConfig(content, sourceRelativePath);
|
||||
if (config.plugin !== undefined && !Array.isArray(config.plugin)) {
|
||||
throw new Error(`Invalid ${sourceRelativePath}: plugin must be an array`);
|
||||
}
|
||||
@@ -90,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 = {}) {
|
||||
@@ -328,7 +435,9 @@ module.exports = {
|
||||
assertHookConsentReady,
|
||||
disableUnselectedOpenCodeHooks,
|
||||
disableOpenCodeHookPluginRegistration,
|
||||
parseJsoncConfig,
|
||||
getDisabledOpenCodePluginContent,
|
||||
isInertOpenCodePluginStub,
|
||||
getOpenCodeActivationPathKind,
|
||||
getOpenCodeSourceActivationKind,
|
||||
formatHookCapabilityDisclosure,
|
||||
|
||||
@@ -4,6 +4,7 @@ const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { isWithinRoot, realpathNearestExisting } = require('../path-safety');
|
||||
const { convertWindowsPathToWSL } = require('../install-targets/helpers');
|
||||
|
||||
const CURRENT_PLUGIN_ID = 'ecc@ecc';
|
||||
// Legacy plugin ids, kept so existing installs are still recognized.
|
||||
@@ -12,19 +13,44 @@ const LEGACY_PLUGIN_IDS = new Set([
|
||||
'everything-claude-code@ecc',
|
||||
]);
|
||||
|
||||
function expandTilde(inputPath, homeDir) {
|
||||
if (typeof inputPath !== 'string') return inputPath;
|
||||
const trimmed = inputPath.trim();
|
||||
if (trimmed === '~') return homeDir;
|
||||
if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
|
||||
return path.join(homeDir, trimmed.slice(2));
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function resolveClaudePaths(options = {}) {
|
||||
const homeDir = options.homeDir
|
||||
|| process.env.HOME
|
||||
|| process.env.USERPROFILE
|
||||
|| os.homedir();
|
||||
const configDir = options.configDir
|
||||
|| process.env.CLAUDE_CONFIG_DIR
|
||||
|| path.join(homeDir, '.claude');
|
||||
const homeDir = path.resolve(
|
||||
options.homeDir
|
||||
|| process.env.HOME
|
||||
|| process.env.USERPROFILE
|
||||
|| os.homedir()
|
||||
);
|
||||
const configured = options.configDir !== undefined
|
||||
? options.configDir
|
||||
: process.env.CLAUDE_CONFIG_DIR;
|
||||
let resolvedConfigDir;
|
||||
if (typeof configured === 'string' && configured.trim() !== '') {
|
||||
const normalized = configured.trim();
|
||||
const converted = convertWindowsPathToWSL(normalized);
|
||||
const expanded = expandTilde(converted, homeDir);
|
||||
if (typeof expanded === 'string' && expanded.trim() !== '') {
|
||||
resolvedConfigDir = path.resolve(expanded.trim());
|
||||
} else {
|
||||
resolvedConfigDir = path.join(homeDir, '.claude');
|
||||
}
|
||||
} else {
|
||||
resolvedConfigDir = path.join(homeDir, '.claude');
|
||||
}
|
||||
const projectRoot = options.projectRoot || process.cwd();
|
||||
|
||||
return {
|
||||
homeDir: path.resolve(homeDir),
|
||||
configDir: path.resolve(configDir),
|
||||
homeDir,
|
||||
configDir: resolvedConfigDir,
|
||||
projectRoot: path.resolve(projectRoot),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -53,6 +53,7 @@ function createRawInstallPlan(request, options = {}) {
|
||||
languages: request.languages,
|
||||
projectRoot: options.projectRoot,
|
||||
homeDir: options.homeDir,
|
||||
env: resolveInvocationEnvironment(options),
|
||||
claudeRulesDir: options.claudeRulesDir,
|
||||
sourceRoot: options.sourceRoot,
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -4,6 +4,23 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
// Lazily loaded so this module can be required from stripped-down directories
|
||||
// (e.g., temp dirs in tests that copy only resolve-ecc-root.js + utils.js).
|
||||
// Falls back to identity on failure, which matches non-WSL behavior.
|
||||
let _convertWindowsPathToWSL = null;
|
||||
function convertWindowsPathToWSL(windowsPath) {
|
||||
if (_convertWindowsPathToWSL === null) {
|
||||
try {
|
||||
_convertWindowsPathToWSL = require('./install-targets/helpers').convertWindowsPathToWSL;
|
||||
} catch (_) {
|
||||
// Module unavailable from this location; non-WSL behavior returns
|
||||
// the input unchanged, so the fallback is safe.
|
||||
_convertWindowsPathToWSL = (p) => p;
|
||||
}
|
||||
}
|
||||
return _convertWindowsPathToWSL(windowsPath);
|
||||
}
|
||||
|
||||
const CURRENT_PLUGIN_SLUG = 'ecc';
|
||||
// Legacy install id, kept for existing installs.
|
||||
const LEGACY_PLUGIN_SLUG = 'everything-claude-code';
|
||||
@@ -66,7 +83,10 @@ function resolveEccRoot(options = {}) {
|
||||
const configuredDir = options.configDir !== undefined
|
||||
? options.configDir
|
||||
: process.env.CLAUDE_CONFIG_DIR;
|
||||
const rawDir = typeof configuredDir === 'string' ? configuredDir.trim() : '';
|
||||
// On WSL, convert Windows paths (e.g., C:\Users\name\.claude) to WSL paths
|
||||
// (/mnt/c/Users/name/.claude) so the resolver finds the correct location.
|
||||
const wslConfiguredDir = convertWindowsPathToWSL(configuredDir);
|
||||
const rawDir = typeof wslConfiguredDir === 'string' ? wslConfiguredDir.trim() : '';
|
||||
const expandedDir = rawDir === '~'
|
||||
? homeDir
|
||||
: (rawDir.startsWith('~/') || rawDir.startsWith('~\\'))
|
||||
@@ -154,10 +174,41 @@ function normalizePluginRootForPlatform(rootDir, platform = process.platform) {
|
||||
* const _r = <paste INLINE_RESOLVE>;
|
||||
* const sm = require(_r + '/scripts/lib/session-manager');
|
||||
*/
|
||||
const INLINE_RESOLVE = `(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=(process.env.CLAUDE_CONFIG_DIR||'').trim()||p.join(o.homedir(),'.claude');if(d==='~')d=o.homedir();else if(d.charAt(0)==='~'&&(d.charAt(1)==='/'||d.charCodeAt(1)===92))d=p.join(o.homedir(),d.slice(2));d=p.resolve(d);function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}function D(x){try{return f.readdirSync(x,{withFileTypes:true}).filter(function(z){return z.isDirectory()}).map(function(z){return z.name})}catch(e){if(e.code==='ENOENT')return [];throw e}}var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=D(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=D(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}return d})()`;
|
||||
// Lazily loaded so this module can be required from stripped-down directories
|
||||
// (e.g., temp dirs in tests that copy only resolve-ecc-root.js + utils.js).
|
||||
// Falls back to canonical inline string with identical escaping when unavailable.
|
||||
let _inlineWslConversion = null;
|
||||
function getInlineWslConversion() {
|
||||
if (_inlineWslConversion === null) {
|
||||
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 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;
|
||||
}
|
||||
|
||||
function buildInlineResolve(options = {}) {
|
||||
const wslConversion = getInlineWslConversion();
|
||||
let probeArg = '';
|
||||
if (options && options.probe) {
|
||||
const segments = String(options.probe).split(/[\\/]/).filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
if (!/^[\w.-]+$/.test(seg)) {
|
||||
throw new Error(`Invalid probe segment: ${seg}`);
|
||||
}
|
||||
}
|
||||
probeArg = `{probe:p.join(${segments.map((s) => `'${s}'`).join(',')})}`;
|
||||
}
|
||||
return `(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=(process.env.CLAUDE_CONFIG_DIR||'').trim()||p.join(o.homedir(),'.claude');if(d==='~')d=o.homedir();else if(d.charAt(0)==='~'&&(d.charAt(1)==='/'||d.charCodeAt(1)===92))d=p.join(o.homedir(),d.slice(2));${wslConversion}d=p.resolve(d);function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot(${probeArg})}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}function D(x){try{return f.readdirSync(x,{withFileTypes:true}).filter(function(z){return z.isDirectory()}).map(function(z){return z.name})}catch(e){if(e.code==='ENOENT')return [];throw e}}var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=D(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=D(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}return d})()`;
|
||||
}
|
||||
|
||||
const INLINE_RESOLVE = buildInlineResolve();
|
||||
|
||||
module.exports = {
|
||||
resolveEccRoot,
|
||||
normalizePluginRootForPlatform,
|
||||
INLINE_RESOLVE,
|
||||
buildInlineResolve,
|
||||
};
|
||||
@@ -32,7 +32,16 @@ const PRETTIER_CONFIGS = [
|
||||
'.prettierrc.toml',
|
||||
'prettier.config.js',
|
||||
'prettier.config.cjs',
|
||||
'prettier.config.mjs'
|
||||
'prettier.config.mjs',
|
||||
// The rest of the names Prettier's config searcher looks for
|
||||
// (src/config/prettier-config/config-searcher.js).
|
||||
'.prettierrc.json5',
|
||||
'.prettierrc.ts',
|
||||
'.prettierrc.mts',
|
||||
'.prettierrc.cts',
|
||||
'prettier.config.ts',
|
||||
'prettier.config.mts',
|
||||
'prettier.config.cts'
|
||||
];
|
||||
|
||||
const PROJECT_ROOT_MARKERS = ['package.json', ...BIOME_CONFIGS, ...PRETTIER_CONFIGS];
|
||||
|
||||
@@ -58,7 +58,7 @@ function loadAliases() {
|
||||
const data = JSON.parse(content);
|
||||
|
||||
// Validate structure
|
||||
if (!data.aliases || typeof data.aliases !== 'object') {
|
||||
if (!data.aliases || typeof data.aliases !== 'object' || Array.isArray(data.aliases)) {
|
||||
log('[Aliases] Invalid aliases file structure, resetting');
|
||||
return getDefaultAliases();
|
||||
}
|
||||
@@ -215,6 +215,10 @@ function setAliasUnlocked(alias, sessionPath, title = null) {
|
||||
return { success: false, error: 'Session path cannot be empty' };
|
||||
}
|
||||
|
||||
if (title !== null && typeof title !== 'string') {
|
||||
return { success: false, error: 'Title must be a string or null' };
|
||||
}
|
||||
|
||||
if (alias.length > 128) {
|
||||
return { success: false, error: 'Alias name cannot exceed 128 characters' };
|
||||
}
|
||||
|
||||
@@ -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] === '(') {
|
||||
|
||||
@@ -69,7 +69,7 @@ function bucketByDay(records, nowMs, days) {
|
||||
}
|
||||
|
||||
for (const bucket of buckets) {
|
||||
if (recordMs > bucket.start && recordMs <= bucket.end) {
|
||||
if (recordMs >= bucket.start && recordMs <= bucket.end) {
|
||||
bucket.records.push(record);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ function toNullableNumber(value, fieldName) {
|
||||
}
|
||||
|
||||
const numericValue = Number(value);
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
throw new Error(`${fieldName} must be a number`);
|
||||
if (!Number.isFinite(numericValue) || numericValue < 0) {
|
||||
throw new Error(`${fieldName} must be a number greater than or equal to zero`);
|
||||
}
|
||||
|
||||
return numericValue;
|
||||
@@ -79,7 +79,7 @@ function normalizeExecutionRecord(input, options = {}) {
|
||||
throw new Error('failure_reason must be a string or null');
|
||||
}
|
||||
|
||||
if (Number.isNaN(Date.parse(recordedAt))) {
|
||||
if (typeof recordedAt !== 'string' || Number.isNaN(Date.parse(recordedAt))) {
|
||||
throw new Error('recorded_at must be an ISO timestamp');
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Vendored
+2
-2
@@ -193,10 +193,10 @@ export interface CommandResult {
|
||||
export function runCommand(cmd: string, options?: ExecSyncOptions): CommandResult;
|
||||
|
||||
/** Check if the current directory is inside a git repository */
|
||||
export function isGitRepo(): boolean;
|
||||
export function isGitRepo(options?: ExecSyncOptions): boolean;
|
||||
|
||||
/**
|
||||
* Get git modified files (staged + unstaged), optionally filtered by regex patterns.
|
||||
* Invalid regex patterns are silently skipped.
|
||||
*/
|
||||
export function getGitModifiedFiles(patterns?: string[]): string[];
|
||||
export function getGitModifiedFiles(patterns?: string[], options?: ExecSyncOptions): string[];
|
||||
@@ -537,22 +537,25 @@ function runCommand(cmd, options = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if current directory is a git repository
|
||||
* Check if current directory is a git repository.
|
||||
* @param {object} [options] - Options forwarded to runCommand, including env.
|
||||
*/
|
||||
function isGitRepo() {
|
||||
return runCommand('git rev-parse --git-dir').success;
|
||||
function isGitRepo(options = {}) {
|
||||
return runCommand('git rev-parse --git-dir', options).success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get git modified files, optionally filtered by regex patterns
|
||||
* @param {string[]} patterns - Array of regex pattern strings to filter files.
|
||||
* Invalid patterns are silently skipped.
|
||||
* @param {object} [options] - Options forwarded to every Git subprocess.
|
||||
* @returns {string[]} Array of modified file paths
|
||||
*/
|
||||
function getGitModifiedFiles(patterns = []) {
|
||||
if (!isGitRepo()) return [];
|
||||
function getGitModifiedFiles(patterns = [], options = {}) {
|
||||
if (!isGitRepo(options)) return [];
|
||||
|
||||
const result = runCommand('git diff --name-only HEAD');
|
||||
// Paths from the repository root even when diff.relative is set.
|
||||
const result = runCommand('git -c diff.relative=false diff --name-only HEAD', options);
|
||||
if (!result.success) return [];
|
||||
|
||||
let files = result.output.split('\n').filter(Boolean);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -39,7 +39,13 @@ function usage() {
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = argv.slice(2);
|
||||
const target = args.find(argument => !argument.startsWith('--'));
|
||||
const valueOptions = ['--adapter', '--target-type', '--skill', '--amendment-id', '--observations', '--write'];
|
||||
for (const [index, argument] of args.entries()) {
|
||||
if (valueOptions.includes(argument) && (!args[index + 1] || args[index + 1].startsWith('--'))) {
|
||||
throw new Error(`Missing value for ${argument}`);
|
||||
}
|
||||
}
|
||||
const target = args.find((argument, index) => !argument.startsWith('--') && !valueOptions.includes(args[index - 1]));
|
||||
const listAdapters = args.includes('--list-adapters');
|
||||
|
||||
const adapterIndex = args.indexOf('--adapter');
|
||||
|
||||
@@ -28,11 +28,17 @@ function parseArgs(argv) {
|
||||
const arg = args[index];
|
||||
|
||||
if (arg === '--db') {
|
||||
if (!args[index + 1] || args[index + 1].startsWith('--') || args[index + 1] === '-h') {
|
||||
throw new Error(`Missing value for ${arg}`);
|
||||
}
|
||||
parsed.dbPath = args[index + 1] || null;
|
||||
index += 1;
|
||||
} else if (arg === '--json') {
|
||||
parsed.json = true;
|
||||
} else if (arg === '--limit') {
|
||||
if (!args[index + 1] || args[index + 1].startsWith('--') || args[index + 1] === '-h') {
|
||||
throw new Error(`Missing value for ${arg}`);
|
||||
}
|
||||
parsed.limit = args[index + 1] || null;
|
||||
index += 1;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
|
||||
+104
-39
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user