Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: never prune calendar events from a partial CLI sync payload (#5302)

[._.]/ Adam Eivy1e5c1d16cbb1
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsx
index a017e09943..b9599c9b30 100644
--- a/client/src/components/calendar/ConfigTab.jsx
+++ b/client/src/components/calendar/ConfigTab.jsx
@@ -11,6 +11,10 @@ import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import { DEFAULT_AVATAR_COLOR } from '../../themes/portosThemes';
const TYPE_ICONS = { 'outlook-calendar': Globe, 'google-calendar': Calendar };
+// A 'partial' sync (the CLI died mid-payload, so nothing was pruned) is a
+// warning, not a failure — the events that DID arrive were saved. Only 'error'
+// means the sync produced nothing.
+const SYNC_STATUS_CLASS = { partial: 'text-port-warning', error: 'text-port-error' };
const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)', 'google-calendar': 'Google Calendar' };
export default function ConfigTab({ accounts, setAccounts }) {
@@ -304,7 +308,11 @@ export default function ConfigTab({ accounts, setAccounts }) {
</div>
{account.lastSyncAt && (
<div className="text-xs text-gray-600">
- Last sync: {formatDateTime(account.lastSyncAt)} ({account.lastSyncStatus})
+ Last sync: {formatDateTime(account.lastSyncAt)} (
+ <span className={SYNC_STATUS_CLASS[account.lastSyncStatus] || ''}>
+ {account.lastSyncStatus}
+ </span>
+ )
</div>
)}
</div>
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index cf5e1f286f..c2e85e7fe1 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -21,6 +21,13 @@ import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';
import { buildCliChildEnv } from './cliChildEnv.js';
+// How much stderr to hand back to callers. Enough to carry a rate-limit banner
+// or a stack's first frames, short enough to embed in an error message or a
+// persisted sync status without dumping a whole log into the UI.
+const STDERR_TAIL_LIMIT = 500;
+
+const stderrTailOf = (stderr) => stderr.trim().slice(-STDERR_TAIL_LIMIT);
+
/**
* Resolve which CLI provider + model a feature should use from the providers
* list and the feature's stored `{ providerId, model }` config.
@@ -66,6 +73,15 @@ export function pickCliProvider(providers, config = {}) {
* live for logging/progress. Mirrors the canonical `executeCliRun` settle
* semantics — never rejects; failures come back as `{ error }`.
*
+ * A non-zero exit that still produced stdout resolves as `{ text, partial: true }`
+ * rather than an error, because a CLI that printed a usable answer before dying
+ * (rate-limit banner, context overflow, killed mid-stream) is worth parsing.
+ * **That text may be TRUNCATED.** A caller MUST gate any destructive use of
+ * `text` — pruning, replacing, or overwriting stored records against it — on
+ * `partial === false`; a truncated payload otherwise reads as "these records no
+ * longer exist" and deletes real data. `stderrTail` carries the last
+ * `STDERR_TAIL_LIMIT` chars of stderr so the caller can surface WHY it was partial.
+ *
* @param {object} args
* @param {object} args.provider - resolved CLI provider (must have `.command`)
* @param {string|null} [args.model] - model override; applied as `defaultModel` so buildCliArgs injects it
@@ -75,7 +91,7 @@ export function pickCliProvider(providers, config = {}) {
* @param {number} [args.timeoutMs] - SIGTERM after this many ms (default 300000)
* @param {(chunk: string, stream: 'stdout'|'stderr') => void} [args.onData] - live output callback
* @param {NodeJS.ProcessEnv} [args.baseEnv] - base env for the child (default process.env); the shared child-env composer filters inherited variables. Explicit provider.envVars still overlays it.
- * @returns {Promise<{ text: string, exitCode: number, stderr: string } | { error: string, exitCode?: number, stderr?: string }>}
+ * @returns {Promise<{ text: string, exitCode: number, stderr: string, partial: boolean, stderrTail: string } | { error: string, exitCode?: number, stderr?: string, stderrTail?: string }>}
*/
export function runCliProviderPrompt(args = {}) {
const { provider, model = null, prompt, cwd, extraArgs = [], timeoutMs = 300000, onData, baseEnv = process.env } = args;
@@ -146,7 +162,7 @@ export function runCliProviderPrompt(args = {}) {
const timer = setTimeout(() => {
if (!child.killed) killProcessTree(child);
- done({ error: `Provider call timed out after ${timeoutMs}ms`, text: stdout.trim(), stderr });
+ done({ error: `Provider call timed out after ${timeoutMs}ms`, text: stdout.trim(), stderr, stderrTail: stderrTailOf(stderr) });
}, timeoutMs);
// Register listeners BEFORE writing stdin so an immediate spawn failure or
@@ -173,13 +189,15 @@ export function runCliProviderPrompt(args = {}) {
child.on('close', (code) => {
const text = stdout.trim();
+ const stderrTail = stderrTailOf(stderr);
// A non-zero exit with no stdout is a hard failure; surface stderr.
// Match the historical calendar-sync rule: any stdout means partial
- // success worth returning to the parser.
+ // success worth returning to the parser — but flag it `partial` so the
+ // caller can refuse to treat a possibly-truncated payload as complete.
if (code !== 0 && !text) {
- return done({ error: (stderr.trim().slice(0, 500) || `${provider.command} exited with code ${code}`), exitCode: code, stderr });
+ return done({ error: (stderr.trim().slice(0, STDERR_TAIL_LIMIT) || `${provider.command} exited with code ${code}`), exitCode: code, stderr, stderrTail });
}
- done({ text, exitCode: code, stderr });
+ done({ text, exitCode: code, stderr, partial: code !== 0, stderrTail });
});
});
}
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index dc695e95c7..801ceec692 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -143,4 +143,46 @@ describe('runCliProviderPrompt', () => {
expect(result.text).toBe('resolved path round-trip');
expect(result.exitCode).toBe(0);
});
+
+ // #5302: a non-zero exit that still printed is returned for parsing, but the
+ // text may be truncated — callers gate destructive use on `partial === false`.
+ describe('non-zero exit agreement', () => {
+ const shell = { id: 'gemini-cli', type: 'cli', command: process.platform === 'win32' ? 'cmd' : 'sh' };
+ const shellArgs = (script) => (process.platform === 'win32' ? ['/c', script] : ['-c', script]);
+
+ it.skipIf(process.platform === 'win32')('flags stdout from a non-zero exit as partial and carries a stderr tail', async () => {
+ const result = await runCliProviderPrompt({
+ provider: shell,
+ prompt: 'ignored',
+ extraArgs: shellArgs('echo \'{"calendars":[\'; echo "rate limit reached" >&2; exit 3'),
+ });
+ expect(result.error).toBeUndefined();
+ expect(result.text).toBe('{"calendars":[');
+ expect(result.exitCode).toBe(3);
+ expect(result.partial).toBe(true);
+ expect(result.stderrTail).toContain('rate limit reached');
+ });
+
+ it.skipIf(process.platform === 'win32')('marks a clean exit as not partial', async () => {
+ const result = await runCliProviderPrompt({
+ provider: shell,
+ prompt: 'ignored',
+ extraArgs: shellArgs('echo ok'),
+ });
+ expect(result.partial).toBe(false);
+ expect(result.exitCode).toBe(0);
+ });
+
+ it.skipIf(process.platform === 'win32')('still errors on a non-zero exit with no stdout, exposing the tail', async () => {
+ const result = await runCliProviderPrompt({
+ provider: shell,
+ prompt: 'ignored',
+ extraArgs: shellArgs('echo "boom" >&2; exit 4'),
+ });
+ expect(result.error).toContain('boom');
+ expect(result.exitCode).toBe(4);
+ expect(result.stderrTail).toContain('boom');
+ expect(result.partial).toBeUndefined();
+ });
+ });
});
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index cb291c4189..5553db6667 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -71,7 +71,18 @@ export function getSyncDateRange(pastDays = 7, futureDays = 30) {
return { pastDate, futureDate };
}
-export async function pushSyncEvents(accountId, calendarId, calendarName, rawEvents, io) {
+/**
+ * Upsert a subcalendar's events into the local cache.
+ *
+ * `options.prune` (default true) removes cached events for this subcalendar
+ * that the incoming batch didn't mention — correct only when `rawEvents` is the
+ * COMPLETE set for the range. A caller working from a possibly-truncated payload
+ * (a CLI that exited non-zero mid-stream) must pass `prune: false`, or the
+ * missing tail reads as "these events were deleted upstream" and destroys real
+ * calendar data. `options.status` labels the resulting sync for the UI.
+ */
+export async function pushSyncEvents(accountId, calendarId, calendarName, rawEvents, io, options = {}) {
+ const { prune: shouldPrune = true, status = 'success' } = options;
const account = await getAccount(accountId);
if (!account) throw new Error('Account not found');
@@ -115,15 +126,19 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve
}
}
- // Prune events for this subcalendar that are no longer present
- const before = cache.events.length;
- cache.events = cache.events.filter(e =>
- e.subcalendarId !== calendarId || incomingIds.has(e.externalId)
- );
- const pruned = before - cache.events.length;
+ // Prune events for this subcalendar that are no longer present. Skipped when
+ // the caller can't vouch that `rawEvents` is complete (see options.prune).
+ let pruned = 0;
+ if (shouldPrune) {
+ const before = cache.events.length;
+ cache.events = cache.events.filter(e =>
+ e.subcalendarId !== calendarId || incomingIds.has(e.externalId)
+ );
+ pruned = before - cache.events.length;
+ }
await saveCache(accountId, cache);
- await updateSyncStatus(accountId, 'success');
+ await updateSyncStatus(accountId, status);
// Auto-log Tribe touchpoints from this subcalendar batch (#2033) — secondary
// effect, must not fail the sync; idempotent on event id.
@@ -144,11 +159,11 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve
newEvents: newCount,
updated: updatedCount,
pruned,
- status: 'success'
+ status
});
- console.log(`📅 Google push sync for ${calendarName}: ${newCount} new, ${updatedCount} updated, ${pruned} pruned`);
- return { newEvents: newCount, updated: updatedCount, pruned, total: cache.events.length, status: 'success' };
+ console.log(`📅 Google push sync for ${calendarName}: ${newCount} new, ${updatedCount} updated, ${pruned} pruned${shouldPrune ? '' : ' (prune skipped — partial payload)'}`);
+ return { newEvents: newCount, updated: updatedCount, pruned, total: cache.events.length, status };
}
const mcpSyncLock = new Map();
@@ -187,9 +202,21 @@ Include the full events arrays as returned by gcal_list_events. Output NOTHING e
const runSync = async () => {
const result = await runConfiguredMcp(prompt, io, accountId);
+ // A non-zero CLI exit that still printed something is a PARTIAL sync: the
+ // JSON may be cut off mid-array, so every calendar it does describe is
+ // treated as incomplete. Upsert what arrived, but never prune from it —
+ // absent events mean "the CLI died", not "deleted upstream".
+ const { partial, stderrTail } = result;
+ const status = partial ? 'partial' : 'success';
+
// Parse Claude's output and push events
const parsed = parseCalendarJson(result.output);
- if (!parsed) throw new ServerError('Failed to parse calendar data from Claude response', { status: 502 });
+ if (!parsed) {
+ // Carry the stderr tail so the failure names WHY the CLI produced no
+ // usable JSON instead of a bare, undiagnosable parse error.
+ const reason = stderrTail ? `: ${stderrTail}` : '';
+ throw new ServerError(`Failed to parse calendar data from Claude response${reason}`, { status: 502 });
+ }
let totalNew = 0;
let totalUpdated = 0;
@@ -198,18 +225,44 @@ Include the full events arrays as returned by gcal_list_events. Output NOTHING e
for (const cal of parsed.calendars) {
if (!cal.calendarId || !Array.isArray(cal.events)) continue;
- const syncResult = await pushSyncEvents(accountId, cal.calendarId, cal.calendarName || cal.calendarId, cal.events, null);
+ const syncResult = await pushSyncEvents(
+ accountId,
+ cal.calendarId,
+ cal.calendarName || cal.calendarId,
+ cal.events,
+ null,
+ { prune: !partial, status },
+ );
totalNew += syncResult.newEvents;
totalUpdated += syncResult.updated;
totalPruned += syncResult.pruned;
results.push({ calendarId: cal.calendarId, calendarName: cal.calendarName, ...syncResult });
}
- await updateSyncStatus(accountId, 'success');
- io?.emit('calendar:sync:completed', { accountId, newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, status: 'success', method: 'mcp' });
- console.log(`📅 MCP sync complete for ${account.name}: ${totalNew} new, ${totalUpdated} updated, ${totalPruned} pruned across ${results.length} calendars`);
+ await updateSyncStatus(accountId, status);
+ io?.emit('calendar:sync:completed', {
+ accountId,
+ newEvents: totalNew,
+ updated: totalUpdated,
+ pruned: totalPruned,
+ status,
+ method: 'mcp',
+ ...(partial ? { reason: stderrTail || `CLI exited with code ${result.exitCode}` } : {}),
+ });
+ if (partial) {
+ console.warn(`⚠️ MCP sync PARTIAL for ${account.name} (exit ${result.exitCode}): ${totalNew} new, ${totalUpdated} updated, prune skipped across ${results.length} calendars`);
+ } else {
+ console.log(`📅 MCP sync complete for ${account.name}: ${totalNew} new, ${totalUpdated} updated, ${totalPruned} pruned across ${results.length} calendars`);
+ }
- return { newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, calendars: results, status: 'success' };
+ return {
+ newEvents: totalNew,
+ updated: totalUpdated,
+ pruned: totalPruned,
+ calendars: results,
+ status,
+ ...(partial ? { reason: stderrTail || `CLI exited with code ${result.exitCode}` } : {}),
+ };
};
return runSync().catch(async (error) => {
@@ -258,9 +311,20 @@ Output NOTHING else — just the JSON array.`;
const result = await runConfiguredMcp(prompt, io, accountId);
+ // Discovery REPLACES the stored subcalendar list, so a truncated array would
+ // silently drop calendars (and their enabled/goal wiring). A partial payload
+ // is never good enough to merge — fail loudly with the CLI's own reason.
+ if (result.partial) {
+ const reason = result.stderrTail || `CLI exited with code ${result.exitCode}`;
+ throw new ServerError(`Calendar discovery returned a partial response — not merging: ${reason}`, { status: 502 });
+ }
+
// Parse the calendar list from Claude's output
const match = result.output.match(/\[[\s\S]*\]/);
- if (!match) throw new ServerError('Failed to parse calendar list from Claude response', { status: 502 });
+ if (!match) {
+ const reason = result.stderrTail ? `: ${result.stderrTail}` : '';
+ throw new ServerError(`Failed to parse calendar list from Claude response${reason}`, { status: 502 });
+ }
const calendars = safeJSONParse(match[0], null);
if (!Array.isArray(calendars)) throw new ServerError('Invalid calendar list format', { status: 502 });
@@ -312,5 +376,13 @@ async function runConfiguredMcp(prompt, io, accountId) {
if (result.error) {
throw new ServerError(result.error, { status: 502 });
}
- return { output: result.text, exitCode: result.exitCode };
+ // `partial` means the CLI exited non-zero but still printed something — the
+ // payload may be truncated mid-JSON. Callers MUST NOT let a partial payload
+ // drive a destructive operation (see pushSyncEvents' prune option).
+ return {
+ output: result.text,
+ exitCode: result.exitCode,
+ partial: result.partial === true,
+ stderrTail: result.stderrTail || '',
+ };
}
diff --git a/server/services/calendarGoogleSync.test.js b/server/services/calendarGoogleSync.test.js
new file mode 100644
index 0000000000..88955565c4
--- /dev/null
+++ b/server/services/calendarGoogleSync.test.js
@@ -0,0 +1,179 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// The CLI exit-status contract (#5302): runCliProviderPrompt hands back stdout
+// even when the child exited non-zero, flagged `partial`. These tests pin the
+// service boundary's obligation NOT to let a possibly-truncated payload drive a
+// destructive prune — the failure mode is silently deleting real calendar
+// events from the local cache and then recording the sync as a success.
+vi.mock('../lib/cliProviderRun.js', () => ({
+ pickCliProvider: vi.fn(() => ({ provider: { id: 'claude-code', type: 'cli', command: 'claude' }, model: null })),
+ runCliProviderPrompt: vi.fn(),
+}));
+
+vi.mock('./calendarAccounts.js', () => ({
+ getAccount: vi.fn(),
+ updateSyncStatus: vi.fn(async () => ({})),
+ updateSubcalendars: vi.fn(async () => ({})),
+ mergeDiscoveredSubcalendars: vi.fn((existing, discovered) => discovered),
+}));
+
+vi.mock('./calendarSync.js', () => ({
+ loadCache: vi.fn(),
+ saveCache: vi.fn(async () => {}),
+ logCalendarTouchpoints: vi.fn(async () => {}),
+ recordCalendarActivity: vi.fn(async () => {}),
+}));
+
+vi.mock('./providers.js', () => ({ getAllProviders: vi.fn(async () => ({ providers: {} })) }));
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+
+import { mcpSyncAccount, mcpDiscoverCalendars } from './calendarGoogleSync.js';
+import { runCliProviderPrompt } from '../lib/cliProviderRun.js';
+import { getAccount, updateSyncStatus, updateSubcalendars } from './calendarAccounts.js';
+import { loadCache, saveCache } from './calendarSync.js';
+
+const ACCOUNT_ID = '22222222-2222-2222-2222-222222222222';
+const CAL_ID = '[email protected]';
+
+const account = () => ({
+ id: ACCOUNT_ID,
+ name: 'Example Account',
+ type: 'google-calendar',
+ subcalendars: [{ calendarId: CAL_ID, name: 'Work', enabled: true, dormant: false }],
+});
+
+// One event already cached that the (truncated) response will NOT mention —
+// the exact record a prune would destroy.
+const cachedEvents = () => [
+ {
+ id: 'cached-1',
+ externalId: 'gcal-deadbeef0001',
+ apiId: 'upstream-1',
+ title: 'Standing 1:1',
+ subcalendarId: CAL_ID,
+ },
+];
+
+const rawEvent = (id, summary) => ({
+ id,
+ summary,
+ start: { dateTime: '2026-03-02T10:00:00Z' },
+ end: { dateTime: '2026-03-02T11:00:00Z' },
+});
+
+const savedCache = () => saveCache.mock.calls.at(-1)[1];
+
+describe('mcpSyncAccount CLI exit-status agreement (#5302)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAccount.mockResolvedValue(account());
+ loadCache.mockResolvedValue({ events: cachedEvents() });
+ });
+
+ it('prunes cache-only events on a clean exit 0 and records success', async () => {
+ runCliProviderPrompt.mockResolvedValue({
+ text: JSON.stringify({ calendars: [{ calendarId: CAL_ID, calendarName: 'Work', events: [rawEvent('upstream-2', 'Design review')] }] }),
+ exitCode: 0,
+ partial: false,
+ stderrTail: '',
+ });
+
+ const result = await mcpSyncAccount(ACCOUNT_ID, null);
+
+ expect(result.status).toBe('success');
+ expect(result.pruned).toBe(1);
+ expect(updateSyncStatus).toHaveBeenCalledWith(ACCOUNT_ID, 'success');
+ // The stale cached event is gone; only the incoming one survives.
+ expect(savedCache().events.map((e) => e.title)).toEqual(['Design review']);
+ });
+
+ it('upserts but NEVER prunes when the CLI exited non-zero with usable stdout', async () => {
+ runCliProviderPrompt.mockResolvedValue({
+ text: JSON.stringify({ calendars: [{ calendarId: CAL_ID, calendarName: 'Work', events: [rawEvent('upstream-2', 'Design review')] }] }),
+ exitCode: 1,
+ partial: true,
+ stderrTail: 'rate limit reached, stream aborted',
+ });
+
+ const result = await mcpSyncAccount(ACCOUNT_ID, null);
+
+ expect(result.status).toBe('partial');
+ expect(result.newEvents).toBe(1);
+ expect(result.pruned).toBe(0);
+ expect(result.reason).toContain('rate limit reached');
+ expect(updateSyncStatus).toHaveBeenCalledWith(ACCOUNT_ID, 'partial');
+ // Both the pre-existing event and the newly-seen one remain — a truncated
+ // payload must never read as "these events were deleted upstream".
+ expect(savedCache().events.map((e) => e.title).sort()).toEqual(['Design review', 'Standing 1:1']);
+ });
+
+ it('surfaces the partial status over the socket so the UI can warn', async () => {
+ runCliProviderPrompt.mockResolvedValue({
+ text: JSON.stringify({ calendars: [{ calendarId: CAL_ID, calendarName: 'Work', events: [] }] }),
+ exitCode: 143,
+ partial: true,
+ stderrTail: 'killed mid-stream',
+ });
+ const io = { emit: vi.fn() };
+
+ await mcpSyncAccount(ACCOUNT_ID, io);
+
+ expect(io.emit).toHaveBeenCalledWith(
+ 'calendar:sync:completed',
+ expect.objectContaining({ accountId: ACCOUNT_ID, status: 'partial', reason: 'killed mid-stream' }),
+ );
+ });
+
+ it('carries the stderr tail into the parse failure instead of a bare message', async () => {
+ runCliProviderPrompt.mockResolvedValue({
+ text: 'I could not reach the calendar API.',
+ exitCode: 1,
+ partial: true,
+ stderrTail: 'MCP server not connected',
+ });
+
+ await expect(mcpSyncAccount(ACCOUNT_ID, null)).rejects.toMatchObject({
+ status: 502,
+ message: expect.stringContaining('MCP server not connected'),
+ });
+ expect(saveCache).not.toHaveBeenCalled();
+ expect(updateSyncStatus).toHaveBeenCalledWith(ACCOUNT_ID, 'error');
+ });
+});
+
+describe('mcpDiscoverCalendars CLI exit-status agreement (#5302)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAccount.mockResolvedValue(account());
+ });
+
+ it('merges the discovered list on a clean exit 0', async () => {
+ runCliProviderPrompt.mockResolvedValue({
+ text: JSON.stringify([{ id: CAL_ID, name: 'Work', color: '#123456' }]),
+ exitCode: 0,
+ partial: false,
+ stderrTail: '',
+ });
+
+ const result = await mcpDiscoverCalendars(ACCOUNT_ID, null);
+
+ expect(result.status).toBe('success');
+ expect(updateSubcalendars).toHaveBeenCalled();
+ });
+
+ it('refuses to merge a partial list — a truncated array would drop calendars', async () => {
+ runCliProviderPrompt.mockResolvedValue({
+ // Well-formed enough to parse, but the process died: the array may be short.
+ text: JSON.stringify([{ id: CAL_ID, name: 'Work' }]),
+ exitCode: 1,
+ partial: true,
+ stderrTail: 'context window exceeded',
+ });
+
+ await expect(mcpDiscoverCalendars(ACCOUNT_ID, null)).rejects.toMatchObject({
+ status: 502,
+ message: expect.stringContaining('context window exceeded'),
+ });
+ expect(updateSubcalendars).not.toHaveBeenCalled();
+ });
+});