Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(runtime): git tools run async; Windows service drift is detected too
Salman Qureshia87021ac94b5
diff --git a/.lint-baseline.json b/.lint-baseline.jsonindex 73b00afe..7a300fbb 100644--- a/.lint-baseline.json+++ b/.lint-baseline.json@@ -1,11 +1,11 @@{"$comment": "ESLint ratchet baseline. Per-rule counts (errors + warnings) may only go down. Refresh with `npm run lint:ratchet -- --update` after a clean-up.","provisional": false,- "generatedAt": "2026-10-10T16:59:09.838Z",+ "generatedAt": "2026-10-11T07:49:39.756Z","target": "src","rules": {"(unknown)": 1,- "@typescript-eslint/no-explicit-any": 1138,+ "@typescript-eslint/no-explicit-any": 1136,"@typescript-eslint/no-require-imports": 6,"@typescript-eslint/no-this-alias": 5,"@typescript-eslint/no-unused-expressions": 100,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dbabfb0d..5d1be500 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased — one runtime (ADR-024)+- **git tools no longer hold the runtime.** `git_status/log/diff/add/commit/push` (and `/code diff`) ran git synchronously — a push over a slow link froze Telegram, every bot and the attach TUI for up to 60 s. They now run async; errors and output are unchanged.+- **Windows service drift** is detected too (Task Scheduler XML and the Run key are read back), so a stale autostart is re-pointed on every platform.- **The login service follows the install.** After a reinstall (npm → binary, stable → dev, a new Node under nvm) the old LaunchAgent / systemd unit kept resurrecting the *old* daemon on every login, so the new build could never own its port. Mercury now checks what the service launches on every launch and re-points it (unloading the old job first); `mercury doctor` shows **Login service: points at this install / STALE**, and the "port owned by another Mercury" message names the service when it is the cause.- **The terminal no longer runs a second copy of Mercury.** Launching `mercury` with no daemon used to spawn the daemon *and* boot a full runtime in the terminal — Telegram, the scheduler and every bot ran twice, and the second copy ran on the thread that paints your keystrokes. That was the typing lag, and the Telegram "terminated by other getUpdates" (409) conflicts. Now the terminal spawns the daemon and attaches to it; a foreground runtime beside a live daemon (`mercury code`, recovery) is a terminal for the main agent only — no bots, no channels, no web port.- **Attach waits for a booting daemon** (token not written yet, token rotated at bind) instead of failing on the first read.diff --git a/src/capabilities/git/git-add.ts b/src/capabilities/git/git-add.tsindex 2b14c610..2944e09c 100644--- a/src/capabilities/git/git-add.ts+++ b/src/capabilities/git/git-add.ts@@ -1,6 +1,6 @@import { tool, zodSchema } from 'ai';+import { runGit } from './git-path.js';import { z } from 'zod';-import { execFileSync } from 'node:child_process';import type { PermissionManager } from '../permissions.js';export function createGitAddTool(permissions: PermissionManager, getCwd: () => string) {@@ -13,7 +13,7 @@ export function createGitAddTool(permissions: PermissionManager, getCwd: () => stry {const permission = await permissions.checkShellCommand(`git add -- ${paths.join(' ')}`);if (!permission.allowed) return `Permission denied: ${permission.reason || 'git add requires approval'}`;- const result = execFileSync('git', ['add', '--', ...paths], { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });+ const result = await runGit('git', ['add', '--', ...paths], { timeoutMs: 20000, cwd: getCwd() });return `Staged ${paths.length} file(s): ${paths.join(', ')}`;} catch (err: any) {return `Error: ${err.stderr?.trim() || err.message}`;diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.tsindex 34686a94..8dac921a 100644--- a/src/capabilities/git/git-commit.ts+++ b/src/capabilities/git/git-commit.ts@@ -1,6 +1,6 @@import { tool, zodSchema } from 'ai';+import { runGit } from './git-path.js';import { z } from 'zod';-import { execFileSync } from 'node:child_process';import { writeFileSync, unlinkSync } from 'node:fs';import { join } from 'node:path';import type { PermissionManager } from '../permissions.js';@@ -21,11 +21,7 @@ export function createGitCommitTool(permissions: PermissionManager, getCwd: () =const cwd = getCwd();const msgFilePath = join(cwd, '.git', 'MERCU_MSG');writeFileSync(msgFilePath, fullMessage, 'utf-8');- const result = execFileSync('git', ['commit', '-F', msgFilePath], {- encoding: 'utf-8',- timeout: 20000,- cwd,- });+ const result = await runGit('git', ['commit', '-F', msgFilePath], { timeoutMs: 20000, cwd: getCwd() });try { unlinkSync(msgFilePath); } catch {}return result.trim() || 'Committed successfully.';} catch (err: any) {diff --git a/src/capabilities/git/git-diff.ts b/src/capabilities/git/git-diff.tsindex 682830a0..a17b299e 100644--- a/src/capabilities/git/git-diff.ts+++ b/src/capabilities/git/git-diff.ts@@ -1,8 +1,7 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execFileSync } from 'node:child_process';import type { PermissionManager } from '../permissions.js';-import { checkGitReadPath, gitReadInvocation } from './git-path.js';+import { checkGitReadPath, gitReadInvocation, runGit } from './git-path.js';export function createGitDiffTool(permissions: PermissionManager, getCwd: () => string) {return tool({@@ -24,7 +23,7 @@ export function createGitDiffTool(permissions: PermissionManager, getCwd: () =>try {const git = gitReadInvocation(args);if ('error' in git) return git.error;- const result = execFileSync(git.file, git.args, { encoding: 'utf-8', timeout: 30000, cwd: getCwd(), env: git.env });+ const result = await runGit(git.file, git.args, { timeoutMs: 30000, cwd: getCwd(), env: git.env });if (!result.trim()) return 'No differences found.';const truncated = result.length > 15000 ? result.slice(0, 15000) + '\n... (truncated)' : result;return truncated;diff --git a/src/capabilities/git/git-helpers.test.ts b/src/capabilities/git/git-helpers.test.tsindex 928f0250..ab4d72c8 100644--- a/src/capabilities/git/git-helpers.test.ts+++ b/src/capabilities/git/git-helpers.test.ts@@ -4,14 +4,15 @@ import { resolve } from 'node:path';// Regression tests for ROADMAP P0.4: the git helpers used to build a shell// string from a model-chosen path and run it through execSync with no// permission check. They must now (a) hand the path to git as one argv-// element via execFileSync and (b) refuse out-of-scope paths before exec.+// element via execFile (async — git must never hold the event loop) and+// (b) refuse out-of-scope paths before exec.vi.mock('node:child_process', () => ({- execFileSync: vi.fn(() => ''),+ execFile: vi.fn((_f: unknown, _a: unknown, _o: unknown, cb: (e: unknown, out: string, err: string) => void) => cb(null, '', '')),execSync: vi.fn(() => { throw new Error('execSync must not be used by git helpers'); }),}));-import { execFileSync, execSync } from 'node:child_process';+import { execFile, execSync } from 'node:child_process';import { createGitStatusTool } from './git-status.js';import { createGitLogTool } from './git-log.js';import { createGitDiffTool } from './git-diff.js';@@ -38,8 +39,8 @@ function fakePermissions(opts: { readAllowed: boolean; shellAllowed?: boolean })const run = (t: any, input: Record<string, unknown>) => (t.execute as any)(input, { toolCallId: 't', messages: [] });beforeEach(() => {- vi.mocked(execFileSync).mockClear();- vi.mocked(execFileSync).mockImplementation(() => '' as any);+ vi.mocked(execFile).mockClear();+ vi.mocked(execFile).mockImplementation(((...a: unknown[]) => (a[3] as (...r: unknown[]) => void)(null, '', '')) as never);vi.mocked(execSync).mockClear();});@@ -49,8 +50,8 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>await run(createGitStatusTool(permissions, () => CWD), { path: INJECTED });expect(execSync).not.toHaveBeenCalled();- expect(execFileSync).toHaveBeenCalledTimes(1);- const [file, args, opts] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[], any];+ expect(execFile).toHaveBeenCalledTimes(1);+ const [file, args, opts] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[], any];expect(file).toBe(PINNED_GIT);expect(args).toEqual([...H, '-C', resolve(INJECTED), 'status', '--porcelain']);expect(opts.cwd).toBe(CWD);@@ -65,7 +66,7 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>await run(createGitLogTool(permissions, () => CWD), { path: INJECTED, count: 5 });expect(execSync).not.toHaveBeenCalled();- const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];+ const [file, args] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[]];expect(file).toBe(PINNED_GIT);expect(args).toEqual([...H, 'log', '--no-ext-diff', '--no-textconv', '--oneline', '--decorate', '-5', '--', INJECTED]);});@@ -75,7 +76,7 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>await run(createGitDiffTool(permissions, () => CWD), { path: INJECTED, staged: true });expect(execSync).not.toHaveBeenCalled();- const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];+ const [file, args] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[]];expect(file).toBe(PINNED_GIT);expect(args).toEqual([...H, 'diff', '--no-ext-diff', '--no-textconv', '--cached', '--', INJECTED]);});@@ -86,21 +87,21 @@ describe('git helpers pass the path as a single argv element (no shell)', () =>await run(push, { remote: 'origin; echo pwned', branch: 'main' });expect(execSync).not.toHaveBeenCalled();- const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];+ const [file, args] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[]];expect(file).toBe('git');expect(args).toEqual(['push', 'origin; echo pwned', 'main']);- vi.mocked(execFileSync).mockClear();+ vi.mocked(execFile).mockClear();const result = await run(push, { remote: '--receive-pack=echo pwned', branch: 'main' });expect(result).toMatch(/must be names/);- expect(execFileSync).not.toHaveBeenCalled();+ expect(execFile).not.toHaveBeenCalled();});it('git_status without a path runs plain `git status --porcelain` and skips the scope check', async () => {const permissions = fakePermissions({ readAllowed: false });await run(createGitStatusTool(permissions, () => CWD), {});expect(permissions.checkFsAccess).not.toHaveBeenCalled();- const [, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];+ const [, args] = vi.mocked(execFile).mock.calls[0] as unknown as [string, string[]];expect(args).toEqual([...H, 'status', '--porcelain']);});});@@ -122,7 +123,7 @@ describe('git helpers reject out-of-scope paths before any exec', () => {expect(result).toMatch(DENIED);expect(permissions.checkFsAccess).toHaveBeenCalledWith(OUTSIDE_RESOLVED, 'read');- expect(execFileSync).not.toHaveBeenCalled();+ expect(execFile).not.toHaveBeenCalled();expect(execSync).not.toHaveBeenCalled();});@@ -130,7 +131,7 @@ describe('git helpers reject out-of-scope paths before any exec', () => {const permissions = fakePermissions({ readAllowed: false });await run(createGitLogTool(permissions, () => CWD), { path: '../outside' });expect(permissions.checkFsAccess).toHaveBeenCalledWith(resolve(CWD, '../outside'), 'read');- expect(execFileSync).not.toHaveBeenCalled();+ expect(execFile).not.toHaveBeenCalled();});it('git_push denies before exec when the shell permission check fails', async () => {@@ -138,7 +139,7 @@ describe('git helpers reject out-of-scope paths before any exec', () => {const result = await run(createGitPushTool(permissions, () => CWD), {});expect(result).toMatch(/^Error:/);expect(permissions.checkShellCommand).toHaveBeenCalledWith('git push origin');- expect(execFileSync).not.toHaveBeenCalled();+ expect(execFile).not.toHaveBeenCalled();});});@@ -151,13 +152,13 @@ describe('output format is unchanged', () => {// The pre-existing behaviour trims the whole result (including the// leading porcelain status column); keep it byte-for-byte identical.- vi.mocked(execFileSync).mockImplementation(() => ' M src/a.ts\n?? new.ts\n' as any);+ vi.mocked(execFile).mockImplementation(((...a: unknown[]) => (a[3] as (...r: unknown[]) => void)(null, ' M src/a.ts\n?? new.ts\n', '')) as never);expect(await run(createGitStatusTool(permissions, () => CWD), {})).toBe('M src/a.ts\n?? new.ts');});it('surfaces git stderr as an Error line', async () => {const permissions = fakePermissions({ readAllowed: true });- vi.mocked(execFileSync).mockImplementation(() => { throw Object.assign(new Error('boom'), { stderr: 'fatal: not a git repository\n' }); });+ vi.mocked(execFile).mockImplementation(((...a: unknown[]) => (a[3] as (...r: unknown[]) => void)(Object.assign(new Error('boom'), { stderr: 'fatal: not a git repository\n' }))) as never);expect(await run(createGitDiffTool(permissions, () => CWD), {})).toBe('Error: fatal: not a git repository');});});diff --git a/src/capabilities/git/git-log.ts b/src/capabilities/git/git-log.tsindex 0629fc73..5c4557ec 100644--- a/src/capabilities/git/git-log.ts+++ b/src/capabilities/git/git-log.ts@@ -1,8 +1,7 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execFileSync } from 'node:child_process';import type { PermissionManager } from '../permissions.js';-import { checkGitReadPath, gitReadInvocation } from './git-path.js';+import { checkGitReadPath, gitReadInvocation, runGit } from './git-path.js';export function createGitLogTool(permissions: PermissionManager, getCwd: () => string) {return tool({@@ -24,7 +23,7 @@ export function createGitLogTool(permissions: PermissionManager, getCwd: () => stry {const git = gitReadInvocation(args);if ('error' in git) return git.error;- const result = execFileSync(git.file, git.args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd(), env: git.env });+ const result = await runGit(git.file, git.args, { timeoutMs: 20000, cwd: getCwd(), env: git.env });if (!result.trim()) return 'No commits found.';return result.trim();} catch (err: any) {diff --git a/src/capabilities/git/git-path.ts b/src/capabilities/git/git-path.tsindex fb594959..dab69b60 100644--- a/src/capabilities/git/git-path.ts+++ b/src/capabilities/git/git-path.ts@@ -1,4 +1,5 @@import { resolve, isAbsolute } from 'node:path';+import { execFile } from 'node:child_process';import type { PermissionManager } from '../permissions.js';import { readDenialMessage } from '../filesystem/verified-read.js';import { pinnedBinary, pinnedSearchDirs, minimalEnv } from '../shell/argv-lane.js';@@ -50,4 +51,25 @@ export function gitReadInvocation(args: string[]): { file: string; args: string[return { file, args: [...GIT_READ_HARDENING, ...body], env: minimalEnv() };}+/**+ * Run git without holding the event loop. The sync form froze the whole+ * runtime — Telegram, every bot, the attach TUI — for as long as git took+ * (a push over a slow link: up to its 60 s timeout). Errors carry+ * `stderr` and `message` exactly as execFileSync's did, so callers' catch+ * blocks are unchanged.+ */+export function runGit(file: string, args: readonly string[], opts: { cwd: string; env?: NodeJS.ProcessEnv; timeoutMs: number; maxBuffer?: number }): Promise<string> {+ return new Promise((resolve, reject) => {+ execFile(file, [...args], { encoding: 'utf-8', timeout: opts.timeoutMs, cwd: opts.cwd, env: opts.env, maxBuffer: opts.maxBuffer ?? 10 * 1024 * 1024 }, (err, stdout, stderr) => {+ if (err) {+ const e = err as Error & { stderr?: string };+ if (typeof e.stderr !== 'string') e.stderr = typeof stderr === 'string' ? stderr : String(stderr ?? '');+ reject(e);+ return;+ }+ resolve(typeof stdout === 'string' ? stdout : String(stdout));+ });+ });+}+export const GIT_READ_HARDENING: readonly string[] = ['-c', 'core.fsmonitor=false', '-c', 'core.pager=cat', '--no-pager'];diff --git a/src/capabilities/git/git-push.ts b/src/capabilities/git/git-push.tsindex 5eb4d53c..5e074c39 100644--- a/src/capabilities/git/git-push.ts+++ b/src/capabilities/git/git-push.ts@@ -1,8 +1,7 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execFileSync } from 'node:child_process';import type { PermissionManager } from '../permissions.js';-import { looksLikeGitOption } from './git-path.js';+import { looksLikeGitOption, runGit } from './git-path.js';export function createGitPushTool(permissions: PermissionManager, getCwd: () => string) {return tool({@@ -26,7 +25,7 @@ export function createGitPushTool(permissions: PermissionManager, getCwd: () =>}try {- const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 60000, cwd: getCwd() });+ const result = await runGit('git', args, { timeoutMs: 60000, cwd: getCwd() });return result.trim() || 'Pushed successfully.';} catch (err: any) {return `Error: ${err.stderr?.trim() || err.message}`;diff --git a/src/capabilities/git/git-status.ts b/src/capabilities/git/git-status.tsindex 988b0cfa..bf88d22c 100644--- a/src/capabilities/git/git-status.ts+++ b/src/capabilities/git/git-status.ts@@ -1,8 +1,7 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execFileSync } from 'node:child_process';import type { PermissionManager } from '../permissions.js';-import { checkGitReadPath, gitReadInvocation } from './git-path.js';+import { checkGitReadPath, gitReadInvocation, runGit } from './git-path.js';export function createGitStatusTool(permissions: PermissionManager, getCwd: () => string) {return tool({@@ -22,7 +21,7 @@ export function createGitStatusTool(permissions: PermissionManager, getCwd: () =try {const git = gitReadInvocation(args);if ('error' in git) return git.error;- const result = execFileSync(git.file, git.args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd(), env: git.env });+ const result = await runGit(git.file, git.args, { timeoutMs: 20000, cwd: getCwd(), env: git.env });if (!result.trim()) return 'Working tree clean — no changes.';return result.trim();} catch (err: any) {diff --git a/src/cli/service.test.ts b/src/cli/service.test.tsindex 0631ead8..daafed18 100644--- a/src/cli/service.test.ts+++ b/src/cli/service.test.ts@@ -365,4 +365,12 @@ describe('login service drift (what the installed service actually launches)', (expect(parseSystemdExecStart(buildSystemdUnit(args, { mercuryHome: '/home/x/.mercury', userHome: '/home/x', pathEnv: '/usr/bin' } as never))).toEqual(args);expect(parseSystemdExecStart('ExecStart="/opt/My Apps/mercury" start --daemon')).toEqual(['/opt/My Apps/mercury', 'start', '--daemon']);});++ it('reads the Windows forms back: task XML Command/Arguments and the Run-key REG_SZ data', async () => {+ const { buildWindowsTaskXml, parseWindowsTaskXml, splitWindowsCommandLine, parseRegQueryValue } = await import('./service.js');+ const args = ['C:\\Program Files\\nodejs\\node.exe', 'C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\@cosmicstack\\mercury-agent\\dist\\index.js', 'start', '--daemon'];+ expect(parseWindowsTaskXml(buildWindowsTaskXml(args, { workingDirectory: 'C:\\Users\\x' }))).toEqual(args);+ expect(splitWindowsCommandLine('"C:\\Program Files\\mercury.exe" start --daemon')).toEqual(['C:\\Program Files\\mercury.exe', 'start', '--daemon']);+ expect(parseRegQueryValue('\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n MercuryAgent REG_SZ "C:\\mercury.exe" start\r\n', 'MercuryAgent')).toBe('"C:\\mercury.exe" start');+ });});diff --git a/src/cli/service.ts b/src/cli/service.tsindex 28d6ead1..820c670d 100644--- a/src/cli/service.ts+++ b/src/cli/service.ts@@ -165,10 +165,62 @@ export function parseSystemdExecStart(unit: string): string[] {return words;}+/** Split a Windows command line into argv (CreateProcess quoting: "..." groups, \" inside). */+export function splitWindowsCommandLine(line: string): string[] {+ const words: string[] = [];+ let i = 0;+ const s = line.trim();+ while (i < s.length) {+ if (s[i] === ' ') { i++; continue; }+ let word = '';+ let quoted = false;+ while (i < s.length && (quoted || s[i] !== ' ')) {+ if (s[i] === '\\' && s[i + 1] === '"') { word += '"'; i += 2; continue; }+ if (s[i] === '"') { quoted = !quoted; i++; continue; }+ word += s[i++];+ }+ words.push(word);+ }+ return words;+}++/** Command + Arguments of a Task Scheduler task XML, as argv. */+export function parseWindowsTaskXml(xml: string): string[] {+ const unescape = (t: string) => t.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');+ const command = xml.match(/<Command>([\s\S]*?)<\/Command>/);+ if (!command) return [];+ const args = xml.match(/<Arguments>([\s\S]*?)<\/Arguments>/);+ return [unescape(command[1].trim()), ...(args ? splitWindowsCommandLine(unescape(args[1])) : [])];+}++/** The REG_SZ data of a `reg query` line for one value. */+export function parseRegQueryValue(output: string, valueName: string): string | null {+ const line = output.split(/\r?\n/).map((l) => l.trim()).find((l) => l.startsWith(valueName + ' ') || l.startsWith(valueName + '\t'));+ if (!line) return null;+ const m = line.match(/REG_(?:EXPAND_)?SZ\s+(.*)$/);+ return m ? m[1].trim() : null;+}+/** What the installed login service launches, or null when none / unknown platform. */export function installedServiceArgs(): string[] | null {try {if (isTermux()) return null;+ if (process.platform === 'win32') {+ const mode = getWindowsServiceMode();+ if (mode === 'task') {+ // The XML written at install is the source of truth; fall back to+ // asking Task Scheduler (UTF-16 output, decoded by the shell).+ const saved = join(getMercuryHome(), WIN_TASK_XML_FILE);+ const xml = existsSync(saved) ? readFileSync(saved, 'utf-8') : execSync(`schtasks /query /tn "${WIN_TASK_NAME}" /xml`, { encoding: 'utf-8', shell: 'cmd.exe' });+ return parseWindowsTaskXml(xml);+ }+ if (mode === 'run-key') {+ const out = execSync(`reg query "${WIN_RUN_KEY}" /v ${WIN_RUN_VALUE}`, { encoding: 'utf-8', shell: 'cmd.exe' });+ const data = parseRegQueryValue(out, WIN_RUN_VALUE);+ return data ? splitWindowsCommandLine(data) : null;+ }+ return null;+ }if (process.platform === 'darwin') {const p = join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist');return existsSync(p) ? parseLaunchAgentArgs(readFileSync(p, 'utf-8')) : null;diff --git a/src/core/agent.ts b/src/core/agent.tsindex b3194008..eca4ec0a 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1095,8 +1095,8 @@ export class Agent {}if (rawArgs === 'diff') {try {- const { execFileSync } = await import('node:child_process');- const diff = execFileSync('git', ['--no-pager', 'diff', '--no-color', 'HEAD'], { cwd: this.capabilities.getCwd(), encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });+ const { runGit } = await import('../capabilities/git/git-path.js');+ const diff = await runGit('git', ['--no-pager', 'diff', '--no-color', 'HEAD'], { cwd: this.capabilities.getCwd(), timeoutMs: 30000 });await channel.send(diff.trim() ? '```\n' + (diff.length > 20000 ? diff.slice(-20000) : diff) + '\n```' : 'Working tree is clean.', msg.channelId);} catch (err: any) {await channel.send(`git diff failed: ${err?.message || String(err)}`, msg.channelId);diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.tsindex 08b03cd4..71c9ebd2 100644--- a/src/core/commands/chat-command.ts+++ b/src/core/commands/chat-command.ts@@ -1077,8 +1077,8 @@ export async function handleChatCommand(agent: Agent, content: string, channelTyif (rawArgs === 'diff') {const cwd = agent.capabilities.getCwd();try {- const { execFileSync } = await import('node:child_process');- const diff = execFileSync('git', ['--no-pager', 'diff', '--no-color', 'HEAD'], { cwd, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });+ const { runGit } = await import('../../capabilities/git/git-path.js');+ const diff = await runGit('git', ['--no-pager', 'diff', '--no-color', 'HEAD'], { cwd, timeoutMs: 30000 });const trimmedDiff = diff.length > 20000 ? diff.slice(-20000) : diff;if (!trimmedDiff.trim()) {await channel.send('Working tree is clean — no unstaged/staged changes vs HEAD.', channelId);