mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-24 00:35:31 +00:00
merge: sync upstream main into feat/antigravity-tier1
Regenerate the skill-triggers registryDigest against the merged context registry instead of taking either side of the conflict. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
e0214a3409
136 files changed
+4390
-1060
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 };
|
||||
@@ -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) {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -269,7 +269,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
|
||||
});
|
||||
}
|
||||
@@ -461,6 +461,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
|
||||
};
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
@@ -7,6 +7,55 @@ 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.
|
||||
// Uses 8 backslashes in regex source so it preserves shell escaping when inlined into `node -e "..."`.
|
||||
const INLINE_WSL_CONVERSION = `try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var m=d.match(/^([A-Za-z]):[\\\\\\\\/]/);if(m){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).replace(/\\\\\\\\/g,'/')}}}}catch(_){}`;
|
||||
|
||||
/**
|
||||
* 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',
|
||||
@@ -448,4 +497,9 @@ module.exports = {
|
||||
isForeignPlatformPath,
|
||||
normalizeRelativePath,
|
||||
planClaudeHooksOperations,
|
||||
isWSL,
|
||||
resetWSLDetection,
|
||||
setWSLForTesting,
|
||||
convertWindowsPathToWSL,
|
||||
INLINE_WSL_CONVERSION,
|
||||
};
|
||||
@@ -12,7 +12,7 @@ const {
|
||||
const { readInstallState, writeInstallState } = require('../install-state');
|
||||
const {
|
||||
assertHookConsentReady,
|
||||
disableOpenCodeHookPluginRegistration,
|
||||
parseJsoncConfig,
|
||||
getDisabledOpenCodePluginContent,
|
||||
getRecordedHookConsent,
|
||||
getOpenCodeActivationPathKind,
|
||||
@@ -463,9 +463,16 @@ function activationIsInactive(kind, operation, content) {
|
||||
return content.toString('utf8') === getDisabledOpenCodePluginContent();
|
||||
}
|
||||
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');
|
||||
}
|
||||
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
@@ -334,6 +427,7 @@ module.exports = {
|
||||
assertHookConsentReady,
|
||||
disableUnselectedOpenCodeHooks,
|
||||
disableOpenCodeHookPluginRegistration,
|
||||
parseJsoncConfig,
|
||||
getDisabledOpenCodePluginContent,
|
||||
getOpenCodeActivationPathKind,
|
||||
getOpenCodeSourceActivationKind,
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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('~\\'))
|
||||
@@ -160,10 +180,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 m=d.match(/^([A-Za-z]):[\\\\\\\\/]/);if(m){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).replace(/\\\\\\\\/g,'/')}}}}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' };
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
|
||||
@@ -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') {
|
||||
|
||||
Reference in new issue
Block a user