Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 45 additions & 19 deletions dist/mcp-server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2302,23 +2302,26 @@ function getLineWindowOffsets(text, lineStarts, startLine, endLine) {
}
const totalLines = lineStarts.length;
const sLine = startLine !== void 0 ? Math.trunc(startLine) : 1;
const eLine = endLine !== void 0 ? Math.min(totalLines, Math.trunc(endLine)) : totalLines;
if (sLine > totalLines) {
return { windowStart: text.length, windowEnd: text.length };
const requestedEnd = endLine !== void 0 ? Math.trunc(endLine) : void 0;
if (requestedEnd !== void 0 && requestedEnd < sLine) {
throw new Error(`Invalid line range: startLine (${sLine}) > endLine (${requestedEnd}). Correct the line bounds for this path.`);
}
if (eLine < sLine) {
throw new Error(`Invalid line range: startLine (${sLine}) > endLine (${eLine})`);
if (startLine !== void 0 && sLine > totalLines) {
return { windowStart: text.length, windowEnd: text.length };
}
const windowStart = lineStarts[sLine - 1];
const eLine = Math.min(totalLines, requestedEnd ?? totalLines);
const windowStart = lineStarts[sLine - 1] ?? text.length;
const windowEnd = eLine < totalLines ? lineStarts[eLine] : text.length;
return { windowStart, windowEnd };
}
var MAX_NEARBY_LINES = 26;
function formatNearbyLines(text, startLine, endLine) {
const lines = text.split("\n");
if (startLine === void 0 && endLine === void 0) return "";
const lines = text.split("\n");
if (lines.at(-1) === "") lines.pop();
const from = Math.max(1, (startLine ?? endLine ?? 1) - 2);
const rawTo = Math.min(lines.length, (endLine ?? startLine ?? 1) + 2);
if (from > rawTo) return "";
const truncated = rawTo - from + 1 > MAX_NEARBY_LINES;
const to = truncated ? from + MAX_NEARBY_LINES - 1 : rawTo;
const snippet = [];
Expand Down Expand Up @@ -2460,6 +2463,9 @@ ${snippet.join("\n")}`;
}
function planHunksForContent(normalizedContent, hunks, displayPath) {
const lineStarts = computeLineStarts(normalizedContent);
if (normalizedContent.length > 0 && lineStarts.at(-1) === normalizedContent.length) {
lineStarts.pop();
}
const spans = [];
const errors = [];
for (let idx = 0; idx < hunks.length; idx++) {
Expand Down Expand Up @@ -2506,7 +2512,7 @@ function planHunksForContent(normalizedContent, hunks, displayPath) {
if (foundOffsets.length === 0) {
const hasRange = hunk.startLine !== void 0 || hunk.endLine !== void 0;
const rangeNote = hasRange ? ` within lines ${hunk.startLine ?? 1}-${hunk.endLine ?? lineStarts.length}` : "";
let hint = "";
let hint = " Re-read the file and copy the exact current target, including whitespace, or correct 'path'.";
if (hasRange) {
const globalOffsets = [];
let gPos = 0;
Expand All @@ -2518,18 +2524,36 @@ function planHunksForContent(normalizedContent, hunks, displayPath) {
}
if (globalOffsets.length > 0) {
const hitLines = globalOffsets.map((o) => formatMatchLineRange(lineStarts, o, normTarget.length)).join(", ");
hint = ` Exact match found outside range at ${hitLines} \u2014 adjust startLine/endLine or omit them.`;
let action = "choose bounds covering the intended matches.";
if (globalOffsets.length === 1 && !hunk.replaceAll) {
const start = globalOffsets[0];
const firstLine = offsetToLine(lineStarts, start);
const lastLine = offsetToLine(lineStarts, start + normTarget.length - 1);
action = `use startLine: ${firstLine}, endLine: ${lastLine} or omit both bounds.`;
} else if (!hunk.replaceAll) {
action = "narrow the bounds to one match or include more surrounding text.";
}
hint = ` Exact match found outside range at ${hitLines} \u2014 check 'path', then ${action}`;
} else {
const outOfBoundsStart = hunk.startLine !== void 0 && Math.trunc(hunk.startLine) > lineStarts.length;
if (outOfBoundsStart) {
const totalLines = lineStarts.length;
const unit = totalLines === 1 ? "line" : "lines";
errors.push(
`${displayPath} hunk #${idx + 1}: startLine ${Math.trunc(hunk.startLine)} exceeds file length (${totalLines} ${unit}). Check 'path' and refresh the line bounds.`
);
continue;
}
const effStart = hunk.startLine ?? 1;
const effEnd = hunk.endLine ?? lineStarts.length;
if (effEnd - effStart + 1 > MAX_NEARBY_LINES - 4) {
hint = findClosestRegionSnippet(normalizedContent, normTarget, effStart, effEnd) || findClosestRegionSnippet(normalizedContent, normTarget) || formatNearbyLines(normalizedContent, effStart, effEnd);
hint += findClosestRegionSnippet(normalizedContent, normTarget, effStart, effEnd) || findClosestRegionSnippet(normalizedContent, normTarget) || formatNearbyLines(normalizedContent, effStart, effEnd);
} else {
hint = formatNearbyLines(normalizedContent, hunk.startLine, hunk.endLine);
hint += formatNearbyLines(normalizedContent, hunk.startLine, hunk.endLine);
}
}
} else {
hint = findClosestRegionSnippet(normalizedContent, normTarget);
hint += findClosestRegionSnippet(normalizedContent, normTarget);
}
errors.push(
`${displayPath} hunk #${idx + 1}: target text not found${rangeNote}.${hint}`
Expand All @@ -2539,7 +2563,7 @@ function planHunksForContent(normalizedContent, hunks, displayPath) {
if (foundOffsets.length > 1 && !hunk.replaceAll) {
const lines = foundOffsets.slice(0, 10).map((o) => formatMatchLineRange(lineStarts, o, normTarget.length, "")).join(", ");
errors.push(
`${displayPath} hunk #${idx + 1}: target matched ${foundOffsets.length} times (lines: ${lines}). Provide startLine/endLine, more surrounding context, or set replaceAll: true.`
`${displayPath} hunk #${idx + 1}: target matched ${foundOffsets.length} times (lines: ${lines}). Narrow the line bounds or include more surrounding text. Set replaceAll: true only if every match in scope should change.`
);
continue;
}
Expand All @@ -2562,7 +2586,7 @@ function planHunksForContent(normalizedContent, hunks, displayPath) {
if (curr.start < prev.end) {
const line = offsetToLine(lineStarts, curr.start);
errors.push(
`${displayPath}: hunk #${prev.hunkIndex + 1} and hunk #${curr.hunkIndex + 1} overlap near line ${line}.`
`${displayPath}: hunk #${prev.hunkIndex + 1} and hunk #${curr.hunkIndex + 1} overlap near line ${line}. Combine them into one hunk using the current file text as the target.`
);
}
}
Expand Down Expand Up @@ -2832,7 +2856,7 @@ function corruptedEditsError(items) {
header: "Validation failed (0 files modified)",
toolName: "apply_edits",
items,
fallbackAdvice: "immediately fall back to parallel built-in edit_file / write_file calls for these file(s)."
fallbackAdvice: "fall back to built-in edit_file / write_file for this batch only. Use apply_edits again for the next batch."
}),
isError: true
};
Expand Down Expand Up @@ -2961,7 +2985,7 @@ ${summaryLines.join("\n")}`;
}
function formatBestEffortPartialResult(params) {
const { partialHeader, errors, summaryLines, noOpCount, dryRun, verifySkipped, maxBytes } = params;
const failedHeading = dryRun ? "Failed (fix only these):" : "Failed (retry ONLY these failed file(s); do NOT re-send applied files):";
const failedHeading = dryRun ? "Failed (correct these files and retry the full dry run):" : "Failed (retry all intended edits for these failed files; skip applied files):";
const failedFull = `${failedHeading}
- ${errors.join("\n- ")}`;
const appliedFull = `Applied:
Expand Down Expand Up @@ -3792,7 +3816,9 @@ Example: ${TOOL_VALIDATION_EXAMPLES.apply_edits}`;
}
const bestEffort = Boolean(input.bestEffort);
if (errors.length > 0 && (!bestEffort || plans.length === 0)) {
const prefix = bestEffort ? "Edit aborted (0 files modified):" : "Atomic edit aborted (0 files modified):";
const heading = bestEffort ? "Edit aborted (0 files modified):" : "Atomic edit aborted (0 files modified):";
const prefix = `${heading}
Retry the full corrected batch.`;
const hasSchemaTypeError = errors.some(
(e) => e.includes("'target' must be") || e.includes("'replacement' must be") || e.includes("must be an object with 'target' and 'replacement'")
);
Expand Down Expand Up @@ -11298,10 +11324,10 @@ function buildApplyEditsToolDefinition(compat) {
required: ["path"]
}
};
const baseDesc = `Atomic multi-file edits. bestEffort writes valid files per file, gives closest lines, skips verify on failure. dryRun validates only. verify cmd in cwd after writes (60s/4000 chars, ${MCP_CALL_BUDGET_SEC}s max). diff adds +-2-line diff. 8800B UTF-8 max. Absolute cwd if no roots/list (Desktop 2.0 Hub).`;
const baseDesc = `Atomic multi-file edits. One edits entry per file; copy exact current target text. Omit line bounds for a unique target; 1-based bounds. bestEffort writes valid files per file. dryRun validates only. verify cmd in cwd after writes (60s/4000 chars, ${MCP_CALL_BUDGET_SEC}s max). diff shows +-2 lines. 8800B UTF-8 max. Absolute cwd if no roots/list (Desktop 2.0 Hub).`;
return {
name: "apply_edits",
description: preferStringEdits ? baseDesc : `${baseDesc} Exact target in 1-based window (all if replaceAll). Nonempty hunks XOR full-file create. overwrite allows replacing via create.`,
description: preferStringEdits ? baseDesc : `${baseDesc} Use create XOR hunks; overwrite replaces files; replaceAll covers scope.`,
inputSchema: {
type: "object",
properties: {
Expand Down
2 changes: 1 addition & 1 deletion rules/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Use `agy-fast_fast` MCP tools where batching amortizes the fixed per-call remote
2. **Outline via `quick_outline` (or `read_slices`), read code via parallel `read_file`**: Batch `quick_outline({ paths: [...] })` on `>=2` unknown `>300`-line files or a single `>500`-line unknown file (use `read_slices` only to piggyback 1-2 tiny <=120-line slices onto outlines), then fetch complete symbol ranges with parallel built-in `read_file(StartLine, EndLine)` (<=200 lines/call; split larger blocks). Prefer parallel `read_file` over 1-file `quick_outline` (<=500 lines) or slice-only `read_slices` to avoid MCP remote checks (~1.8s+). **Do NOT** bulk-read >150 lines via `read_slices` (8.8 KB cap) or blind-read `1-800` on large unknown files.
3. **Keep images out of long coding sessions (TTFT & cache hygiene)**: Loading `.png`/`.jpg`/`.webp` images (UI screenshots, business/voucher/receipt images, or debug captures) into a long (>150k-token) coding conversation can trigger full prompt-cache invalidation and a **3-7x TTFT cliff (40-97s/turn)**. Delegate visual inspection of any image to a subagent that returns a **text-only** list of findings (values, file paths, selectors, concrete fixes); do **not** read those images in the main coding session unless strictly unavoidable.
4. **Prevent context bloat & cache expiry**: Keep subagent reports structured and concise (no raw file dumps) and delegate noisy broad exploration to read-only subagents. In `batch_search`, start broad scans with `outputMode: "files_with_matches"` or `"count"`, and run `--stat` or path-scoped diffs first for large `git diff`/`git show`. Reserve `run_checks` for `>=2` concurrent commands (keep single lightweight commands on native `run_command`, avoiding unnecessary `powershell` wrappers on Windows) and default to `outputMode: "compact"` (`"full"` shares the `8800`-char cap with passing stdout—use only for exit-0 warnings; rerun truncated failures with `run_command` or a narrower filter). In edit-verify loops, keep `apply_edits(verify)` / `run_checks` to fast targeted checks (`verifyTimeoutSec`/`timeoutSec` <=45s; no >60s servers/watchers), avoid unnecessary Plan Mode toggling inside implementation loops (prefix changes invalidate prompt cache), and defer >60s full builds/suites to phase end so turn gaps stay within prompt-cache TTL; for <=10s `run_command` calls, set `WaitMsBeforeAsync` (5000-10000; prefer 10000 on Windows for 3-10s commands) instead of backgrounding early (async wakeups miss cache far more often than continuous tool loops). In multi-phase tasks exceeding ~100k-150k tokens (or ~15+ tool turns), batch aggressively and proactively suggest `/compact` or a fresh session at milestone handoffs.
5. **Apply across all directories, use `bestEffort: true` for >=3 files & circuit-break corrupted MCP args**: Use `apply_edits` and `batch_search` consistently for code, Vue/HTML/CSS, docs, scripts, and scratch folders. For `apply_edits` touching >=3 files, pass `bestEffort: true` (batches <=6-8 files) so one mismatch never rolls back valid files. If `apply_edits` reports nested-argument serialization corruption (e.g., `boolean`/`null` in `edits`, or an empty `edits` array), **do NOT retry the same payload**—immediately fall back to parallel built-in `edit_file` / `write_file`.
5. **Apply across all directories, group edits by file, use `bestEffort: true` for >=3 files & circuit-break corrupted MCP args**: Use `apply_edits` and `batch_search` consistently for code, Vue/HTML/CSS, docs, scripts, and scratch folders; send one `apply_edits` entry per file with only that file's hunks (copy each `target` exactly from the current file; omit `startLine/endLine` unless disambiguating repeated text). For `apply_edits` touching >=3 files, pass `bestEffort: true` (batches <=6-8 files) so one mismatch never rolls back valid files. On a matching/validation failure, fix the reported path/hunk per the error and retry the failed files with all their intended edits (resend the full batch if zero files were written). If `verify` fails after writes, diagnose from its output and treat the edits as committed. If `apply_edits` reports nested-argument serialization corruption (e.g., `boolean`/`null` in `edits`, or an empty `edits` array), **do NOT retry the same payload**—fall back to built-in `edit_file` / `write_file` for that batch only, then use `apply_edits` again.
6. **Pack into ONE MCP call per turn, use the startup snapshot & brief swarm workers**: Combine cross-repo searches into one `batch_search`, combine edits + verify into one `apply_edits`, always pass explicit `cwd` (especially on Desktop 2.0 / Hub where MCP `roots/list` may be unavailable), read the `SessionStart` snapshot before running `ls`/`git status`, and avoid issuing 2 parallel calls to the same `agy-fast_fast` tool in one turn. When spawning swarm workers for codebase tasks (Antigravity does not mount MCP/rules/`SessionStart` into swarm workers), include exact cross-platform `--cli` commands in their brief: use parallel ranged `read_file` (<=200 lines) and invoke `node "<plugin>/dist/mcp-server.mjs" --cli ...` directly (using the installed plugin path from this rule's header—do not store command+flags in one shell variable, and put per-query modifiers before their query, e.g. `node "<plugin>/dist/mcp-server.mjs" --cli search --path src --text "foo" --git "status --short"`, `... --cli outline a.ts b.ts`, `... --cli edit --best-effort --stdin` with `{"edits":[...]}`, `... --cli check --compact "cmd1" "cmd2"`).

## Quick Schemas (`ServerName: "agy-fast_fast"`)
Expand Down
4 changes: 2 additions & 2 deletions src/mcp-server-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,13 +383,13 @@ function buildApplyEditsToolDefinition(
},
};

const baseDesc = `Atomic multi-file edits. bestEffort writes valid files per file, gives closest lines, skips verify on failure. dryRun validates only. verify cmd in cwd after writes (60s/4000 chars, ${MCP_CALL_BUDGET_SEC}s max). diff adds +-2-line diff. 8800B UTF-8 max. Absolute cwd if no roots/list (Desktop 2.0 Hub).`;
const baseDesc = `Atomic multi-file edits. One edits entry per file; copy exact current target text. Omit line bounds for a unique target; 1-based bounds. bestEffort writes valid files per file. dryRun validates only. verify cmd in cwd after writes (60s/4000 chars, ${MCP_CALL_BUDGET_SEC}s max). diff shows +-2 lines. 8800B UTF-8 max. Absolute cwd if no roots/list (Desktop 2.0 Hub).`;

return {
name: "apply_edits",
description: preferStringEdits
? baseDesc
: `${baseDesc} Exact target in 1-based window (all if replaceAll). Nonempty hunks XOR full-file create. overwrite allows replacing via create.`,
: `${baseDesc} Use create XOR hunks; overwrite replaces files; replaceAll covers scope.`,
inputSchema: {
type: "object",
properties: {
Expand Down
Loading
Loading