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: require saved image outcomes for Antigravity usage repair

[._.]/ Adam Eivyb612fb17296d
diff --git a/server/services/agyUsageBackfill.js b/server/services/agyUsageBackfill.js
index 0c56edbfc9..1bc86133e6 100644
--- a/server/services/agyUsageBackfill.js
+++ b/server/services/agyUsageBackfill.js
@@ -8,21 +8,16 @@
*/
import { copyFile, mkdir, readdir, readFile } from 'fs/promises';
-import { homedir } from 'os';
import { join, resolve } from 'path';
import { PATHS } from '../lib/fileUtils.js';
import { familyForProvider } from '../lib/providerFamilies.js';
import { agyUsageProviderIdFromList } from './agyMediaUsage.js';
import {
galleryAgyImageUsageEvent,
- imagineEventsFromAgyTranscript,
planAgyUsageRepair,
summarizeAgyRepairAdditions,
} from './agyUsageRepair.js';
import { addDatedUsage, flushUsageLedger, getUsage, loadUsage } from './usage.js';
-import { listAgyConversations } from './usageReconciler.js';
-
-const yieldToEventLoop = () => new Promise((done) => setImmediate(done));
const faultLabel = (err) => {
if (err?.code) return String(err.code);
@@ -69,36 +64,6 @@ async function collectGallery(dataDir) {
return media;
}
-async function collectSessions(home) {
- const root = join(home, '.gemini', 'antigravity-cli');
- const media = [];
- let conversations;
- try {
- conversations = await listAgyConversations(root);
- } catch {
- return media;
- }
- for (const conversation of conversations) {
- try {
- const transcriptPath = join(root, 'brain', conversation.conversationId, '.system_generated', 'logs', 'transcript.jsonl');
- const text = await readFile(transcriptPath, 'utf8').catch(() => '');
- if (text) {
- const events = imagineEventsFromAgyTranscript({
- transcriptText: text,
- sessionId: conversation.conversationId,
- cwd: conversation.workspace,
- day: conversation.timestamp ? new Date(conversation.timestamp).toISOString().slice(0, 10) : null,
- });
- media.push(...events);
- }
- } catch {
- // One unreadable session must not abort the scan
- }
- await yieldToEventLoop();
- }
- return media;
-}
-
async function providerIdFromFile(dataDir) {
const stored = await readJson(join(dataDir, 'providers.json'), null, { label: 'providers.json' });
const list = Array.isArray(stored)
@@ -109,19 +74,19 @@ async function providerIdFromFile(dataDir) {
}
/**
- * Read the gallery and brain sessions without touching the ledger.
+ * Reconcile saved gallery outputs without touching the ledger. Transcript
+ * requests are not completion evidence, so their files are never scanned.
+ * Callers may still pass the legacy `home` option; it is intentionally ignored.
*/
export async function planAgyUsageRepairFromDisk({
- home = homedir(),
dataDir = PATHS.data,
repairIds = null,
providerId = null,
} = {}) {
const storedIds = repairIds ?? (await readJson(join(dataDir, 'usage.json'), {}, { strict: true }))?.grokRepairIds;
const gallery = await collectGallery(dataDir);
- const sessionMedia = await collectSessions(home);
return planAgyUsageRepair({
- media: [...gallery, ...sessionMedia],
+ media: gallery,
repairIds: Array.isArray(storedIds) ? storedIds : [],
providerId: providerId || await providerIdFromFile(dataDir),
});
@@ -148,7 +113,6 @@ async function backupLedger(dataDir) {
* @returns {Promise<{ added: number, images: number, backedUp: boolean, note: string|null, backupDir: string|null }>}
*/
export async function applyAgyUsageRepair({
- home = homedir(),
dataDir = PATHS.data,
providers = null,
providerId = null,
@@ -160,7 +124,6 @@ export async function applyAgyUsageRepair({
const resolvedProviderId = providerId
|| (providers ? agyUsageProviderIdFromList(providers) : await providerIdFromFile(dataDir));
const plan = await planAgyUsageRepairFromDisk({
- home,
dataDir,
repairIds: getUsage().grokRepairIds || [],
providerId: resolvedProviderId,
diff --git a/server/services/agyUsageBackfill.test.js b/server/services/agyUsageBackfill.test.js
index a46f0dbdde..f6eff88304 100644
--- a/server/services/agyUsageBackfill.test.js
+++ b/server/services/agyUsageBackfill.test.js
@@ -19,8 +19,8 @@ vi.mock('./usage.js', () => ({
flushUsageLedger: vi.fn(async () => {}),
}));
-vi.mock('../lib/fileUtils.js', () => ({
- PATHS: paths,
+vi.mock('../lib/fileUtils.js', async importOriginal => ({
+ ...await importOriginal(), PATHS: paths,
}));
const { applyAgyUsageRepair, planAgyUsageRepairFromDisk } = await import('./agyUsageBackfill.js');
@@ -61,13 +61,21 @@ describe('planAgyUsageRepairFromDisk', () => {
});
describe('applyAgyUsageRepair', () => {
- it('backs up the ledger once, writes the in-memory repair, and skips a repeat', async () => {
+ it('backs up gallery repairs, excludes request-only transcripts, and skips a repeat', async () => {
+ const logs = join(home, '.gemini', 'antigravity-cli', 'brain', 'session-request-only', '.system_generated', 'logs');
+ await mkdir(logs, { recursive: true });
+ await writeFile(join(logs, 'transcript.jsonl'), JSON.stringify({
+ type: 'PLANNER_RESPONSE', created_at: '2026-10-05T00:00:00.000Z',
+ tool_calls: [{ name: 'generate_image', args: { prompt: 'A fictional blue lighthouse' } }],
+ }));
const first = await applyAgyUsageRepair({ home, dataDir });
expect(first).toMatchObject({ added: 1, images: 1, backedUp: true });
expect(first.backupDir).toMatch(/agy-usage-/);
expect(JSON.parse(await readFile(join(first.backupDir, 'usage.json'), 'utf8')).grokRepairIds).toEqual([]);
expect(written).toHaveLength(1);
expect(written[0].repairId).toBe('gallery:job-agy-1');
+ expect(ledger.grokRepairIds).toEqual(['gallery:job-agy-1']);
+ expect(first.note).toMatch(/transcript.*not counted/i);
expect(flushUsageLedger).toHaveBeenCalledTimes(1);
const second = await applyAgyUsageRepair({ home, dataDir });
diff --git a/server/services/agyUsageRepair.js b/server/services/agyUsageRepair.js
index 91afe45bb0..8edbe675e9 100644
--- a/server/services/agyUsageRepair.js
+++ b/server/services/agyUsageRepair.js
@@ -1,64 +1,18 @@
/**
* Pure plan for repairing Antigravity image usage that was not recorded in the ledger.
*
- * Media recovered from the gallery is added as image units.
- * Session tool calls inside a PortOS `portos-agy-scratch-` directory are
- * omitted so a gallery job is not billed twice.
+ * Saved gallery outputs are added as image units. Transcript planner requests
+ * do not prove execution or output and cannot establish measured image usage.
*/
-import { parseJsonLines } from '../lib/providerTranscriptUsage.js';
import { AGY_IMAGEGEN_IMAGE_MODEL } from '../lib/imageGenCapabilities.js';
-function isPortosAgyScratch(cwd) {
- return String(cwd || '').includes('portos-agy-scratch-');
-}
-
function dayFromIso(iso) {
const ms = Date.parse(iso || '');
if (!Number.isFinite(ms)) return null;
return new Date(ms).toISOString().slice(0, 10);
}
-function inputImageCount(args) {
- if (!args || typeof args !== 'object') return 0;
- const paths = args.ImagePaths || args.imagePaths || args.image_paths || args.images;
- if (Array.isArray(paths)) return paths.length;
- if (typeof paths === 'string' && paths) return 1;
- return 0;
-}
-
-/**
- * Image generation tool calls from an Antigravity transcript outside PortOS render scratch.
- */
-export function imagineEventsFromAgyTranscript({
- transcriptText = '', sessionId = 'unknown', cwd = null, day = null,
-} = {}) {
- if (isPortosAgyScratch(cwd)) return [];
- const events = [];
- let index = 0;
- for (const entry of parseJsonLines(transcriptText)) {
- if (entry?.type !== 'PLANNER_RESPONSE' || !Array.isArray(entry?.tool_calls)) continue;
- const entryDay = dayFromIso(entry?.created_at) || day;
- if (!entryDay) continue;
- for (const call of entry.tool_calls) {
- const name = String(call?.name || '').toLowerCase();
- if (name !== 'generate_image') continue;
- const id = `session-image:${sessionId}:${index}`;
- index += 1;
- events.push({
- id,
- day: entryDay,
- model: AGY_IMAGEGEN_IMAGE_MODEL,
- images: 1,
- inputImages: inputImageCount(call?.args),
- videoSeconds: 0,
- source: 'measured',
- });
- }
- }
- return events;
-}
-
export function galleryAgyImageUsageEvent(meta) {
if (!meta || meta.mode !== 'agy' || !meta.id) return null;
const day = dayFromIso(meta.createdAt);
@@ -84,7 +38,7 @@ export function planAgyUsageRepair({
} = {}) {
const known = new Set(repairIds.filter((id) => typeof id === 'string' && id));
const additions = [];
- const notes = [];
+ const notes = ['Antigravity transcript image requests are not counted without verified completion evidence. Saved gallery outputs are counted.'];
for (const item of media) {
if (!item?.id || !item.day || known.has(item.id)) continue;
known.add(item.id);
diff --git a/server/services/agyUsageRepair.test.js b/server/services/agyUsageRepair.test.js
index 321921dd5b..cc8d9ae97e 100644
--- a/server/services/agyUsageRepair.test.js
+++ b/server/services/agyUsageRepair.test.js
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
galleryAgyImageUsageEvent,
- imagineEventsFromAgyTranscript,
planAgyUsageRepair,
summarizeAgyRepairAdditions,
} from './agyUsageRepair.js';
@@ -36,65 +35,6 @@ describe('galleryAgyImageUsageEvent', () => {
});
});
-describe('imagineEventsFromAgyTranscript', () => {
- it('ignores tool calls when running in a portos-agy-scratch directory', () => {
- const transcriptText = JSON.stringify({
- type: 'PLANNER_RESPONSE',
- created_at: '2026-10-10T12:00:00.000Z',
- tool_calls: [{ name: 'generate_image', args: { prompt: 'a cute cat' } }],
- });
-
- const events = imagineEventsFromAgyTranscript({
- transcriptText,
- sessionId: 'sess-1',
- cwd: '/tmp/portos-agy-scratch-xyz',
- });
- expect(events).toEqual([]);
- });
-
- it('extracts generate_image tool calls from outside scratch directories', () => {
- const transcriptText = [
- JSON.stringify({
- type: 'PLANNER_RESPONSE',
- created_at: '2026-10-10T12:00:00.000Z',
- tool_calls: [
- { name: 'generate_image', args: { prompt: 'a dog', imagePaths: ['img1.png', 'img2.png'] } },
- { name: 'other_tool', args: {} },
- ],
- }),
- JSON.stringify({
- type: 'PLANNER_RESPONSE',
- created_at: '2026-10-10T12:05:00.000Z',
- tool_calls: [
- { name: 'generate_image', args: { prompt: 'another dog' } },
- ],
- }),
- ].join('\n');
-
- const events = imagineEventsFromAgyTranscript({
- transcriptText,
- sessionId: 'sess-2',
- cwd: '/Users/test/projects/my-app',
- });
-
- expect(events).toHaveLength(2);
- expect(events[0]).toMatchObject({
- id: 'session-image:sess-2:0',
- day: '2026-10-10',
- images: 1,
- inputImages: 2,
- source: 'measured',
- });
- expect(events[1]).toMatchObject({
- id: 'session-image:sess-2:1',
- day: '2026-10-10',
- images: 1,
- inputImages: 0,
- source: 'measured',
- });
- });
-});
-
describe('planAgyUsageRepair', () => {
it('plans additions for unrecorded media events and skips existing repairIds', () => {
const media = [