Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: read Gemini's settings as Gemini does, and report a file it can't load instead of retiring GEMINI.md (#377)

Brenno Ferrari70317e2a19cd
diff --git a/.claude/scripts/lib/active-hygiene.ts b/.claude/scripts/lib/active-hygiene.ts
index 28d54a9..c729882 100644
--- a/.claude/scripts/lib/active-hygiene.ts
+++ b/.claude/scripts/lib/active-hygiene.ts
@@ -148,6 +148,11 @@ export type ActiveHygieneReport = {
* wrong, in RETIRED_INSTRUCTION_FILES order (see LEFTOVER_HARM).
*/
readonly leftoverInstructionFiles: readonly string[];
+ /**
+ * .gemini/settings.json exists beside AGENTS.md but Gemini cannot load it,
+ * so Gemini refuses to start (#374). Such a file retires nothing.
+ */
+ readonly geminiSettingsBroken: boolean;
/** AGENTS.md's size once it reaches AGENTS_MD_FLAG_BYTES, else null. `sizeKb`, so a report's identity ignores it (#252). */
readonly agentsMd: { readonly sizeKb: number } | null;
};
@@ -681,7 +686,7 @@ export function scanActiveHygiene(
openLoops: findOpenLoops(root, nowMs, openLoopConfig),
inboxPressure: findInboxPressure(root, nowMs),
memoryInbox: findMemoryInbox(root, memoryRoot, nowMs),
- leftoverInstructionFiles: findLeftoverInstructionFiles(root),
+ ...instructionFileFindings(root),
agentsMd: agentsMdPastFlag(root),
};
}
@@ -733,39 +738,58 @@ function agentsMdPastFlag(root: string): { sizeKb: number } | null {
* AGENTS.md: before that, Gemini still reads GEMINI.md, and deleting it would
* cut Gemini off.
*/
-function findLeftoverInstructionFiles(root: string): string[] {
- if (!existsSync(join(root, INSTRUCTION_FILE))) return [];
- return RETIRED_INSTRUCTION_FILES.filter(
- (f) => existsSync(join(root, f)) && (f !== GEMINI_MD || geminiReadsAgentsMd(root)),
- );
-}
-
-/** Whether .gemini/settings.json lists AGENTS.md in context.fileName. */
-function geminiReadsAgentsMd(root: string): boolean {
- const names = geminiContextFiles(root);
- return names.includes(INSTRUCTION_FILE) && !names.includes(GEMINI_MD);
+function instructionFileFindings(root: string): Pick<ActiveHygieneReport, "leftoverInstructionFiles" | "geminiSettingsBroken"> {
+ if (!existsSync(join(root, INSTRUCTION_FILE))) return { leftoverInstructionFiles: [], geminiSettingsBroken: false };
+ // Read once, so the broken flag and the GEMINI.md verdict come from one parse.
+ const gemini = geminiContextFiles(root);
+ const readsAgentsMd = gemini !== "broken" && gemini.includes(INSTRUCTION_FILE) && !gemini.includes(GEMINI_MD);
+ return {
+ leftoverInstructionFiles: RETIRED_INSTRUCTION_FILES.filter(
+ (f) => existsSync(join(root, f)) && (f !== GEMINI_MD || readsAgentsMd),
+ ),
+ geminiSettingsBroken: gemini === "broken",
+ };
}
/**
- * The context files .gemini/settings.json names (context.fileName, a string
- * or a list), or [] when there is none. Gemini accepts comments and a BOM in
- * that file, so a strict JSON.parse is tried first and a narrow read of the
- * fileName value second.
+ * The context files .gemini/settings.json names, as Gemini loads it: the
+ * top-level context.fileName, else the v1 contextFileName, a string or a list;
+ * [] when there is no file, and "broken" when Gemini cannot load it. Gemini
+ * reads the file as plain utf-8 and runs JSON.parse(stripJsonComments(text)),
+ * and a failure, or a value that is not an object, is fatal: the CLI does not
+ * start (gemini-cli packages/cli/src/config/settings.ts, strip-json-comments
+ * 3.1.1, as of 51617c1, #374). So comments are fine, and a BOM or a trailing
+ * comma is not.
*/
-function geminiContextFiles(root: string): string[] {
+function geminiContextFiles(root: string): string[] | "broken" {
let text: string;
try {
- text = readFileSync(join(root, GEMINI_SETTINGS), "utf8").replace(/^\uFEFF/, "");
+ text = readFileSync(join(root, GEMINI_SETTINGS), "utf8");
} catch {
return [];
}
+ let settings: unknown;
try {
- const names = (JSON.parse(text) as { context?: { fileName?: unknown } }).context?.fileName;
- return (Array.isArray(names) ? names : [names]).filter((n): n is string => typeof n === "string");
+ settings = JSON.parse(stripJsonComments(text));
} catch {
- const value = /"fileName"\s*:\s*(\[[^\]]*\]|"[^"]*")/.exec(text)?.[1] ?? "";
- return [...value.matchAll(/"([^"]*)"/g)].map((m) => m[1]!);
+ return "broken";
}
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) return "broken";
+ const { context, contextFileName } = settings as { context?: { fileName?: unknown }; contextFileName?: unknown };
+ const names = (context !== null && typeof context === "object" ? context.fileName : undefined) ?? contextFileName;
+ return (Array.isArray(names) ? names : [names]).filter((n): n is string => typeof n === "string");
+}
+
+/**
+ * strip-json-comments 3.1.1 with its default `whitespace: true`, the version
+ * gemini-cli pins: a line comment to the end of its line and a block comment
+ * become spaces (line breaks kept), a string (where a backslash escapes the
+ * next character) is left alone, and an unterminated block comment runs to the
+ * end. Where the two differ, on an unterminated string, JSON.parse fails
+ * either way.
+ */
+function stripJsonComments(text: string): string {
+ return text.replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/g, (m) => (m.startsWith('"') ? m : m.replace(/\S/g, " ")));
}
/** What each retired file does wrong while it stays, and what to do about it. */
@@ -812,13 +836,15 @@ const claims = {
inbox: (n: number) => `${n} raw export(s) sitting in work/meetings/ for ${INBOX_PRESSURE_DAYS}+ days`,
memoryInbox: (n: number) => `${n} cross-repo memory capture(s) awaiting review`,
leftover: (file: string) => `${file} present beside AGENTS.md`,
+ geminiSettings: () => `${GEMINI_SETTINGS} doesn't parse`,
agentsMd: (sizeKb: number) => `AGENTS.md is ${sizeKb}KB`,
};
/** The claim of every finding in `report`, in the order the formatter lists them. */
export function hygieneClaims(report: ActiveHygieneReport): string[] {
- const { completedInActive, ungroupedClusters, oversizedNotes, openLoops, inboxPressure, memoryInbox, leftoverInstructionFiles, agentsMd } = report;
+ const { completedInActive, ungroupedClusters, oversizedNotes, openLoops, inboxPressure, memoryInbox, leftoverInstructionFiles, geminiSettingsBroken, agentsMd } = report;
const out: string[] = [];
+ if (geminiSettingsBroken) out.push(claims.geminiSettings());
for (const file of leftoverInstructionFiles) out.push(claims.leftover(file));
if (agentsMd !== null) out.push(claims.agentsMd(agentsMd.sizeKb));
if (completedInActive.length > 0) out.push(claims.completed(completedInActive.length));
@@ -843,6 +869,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
inboxPressure,
memoryInbox,
leftoverInstructionFiles,
+ geminiSettingsBroken,
agentsMd,
} = report;
if (
@@ -853,6 +880,7 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
inboxPressure === null &&
memoryInbox === null &&
leftoverInstructionFiles.length === 0 &&
+ !geminiSettingsBroken &&
agentsMd === null
) {
return [];
@@ -861,6 +889,11 @@ export function formatActiveHygiene(report: ActiveHygieneReport): string[] {
// First: until they are gone, an agent reads none of the rest of the
// conventions this vault ships in AGENTS.md, or loses what the user added.
+ if (geminiSettingsBroken) {
+ lines.push(
+ `⚠️ ${claims.geminiSettings()} — Gemini refuses to start until it does: a BOM, a trailing comma or a syntax error is fatal there, though comments are fine. Fix the file, and keep GEMINI.md until it parses and points Gemini at AGENTS.md.`,
+ );
+ }
for (const file of leftoverInstructionFiles) {
if (lines.length > 0) lines.push("");
const harm = LEFTOVER_HARM[file] ?? "it is a retired instruction file; move anything you added there to AGENTS.md and delete it.";
diff --git a/.claude/scripts/tests/active-hygiene.test.ts b/.claude/scripts/tests/active-hygiene.test.ts
index 1109f37..348b4a5 100644
--- a/.claude/scripts/tests/active-hygiene.test.ts
+++ b/.claude/scripts/tests/active-hygiene.test.ts
@@ -433,6 +433,7 @@ describe("scanActiveHygiene — detectors", () => {
inboxPressure: null,
memoryInbox: { count: 4, oldestDays: 2, namedOnly: 0 },
leftoverInstructionFiles: [],
+ geminiSettingsBroken: false,
agentsMd: null,
});
const text = lines.join("\n");
@@ -455,6 +456,7 @@ describe("scanActiveHygiene — detectors", () => {
inboxPressure: null,
memoryInbox: null,
leftoverInstructionFiles: [],
+ geminiSettingsBroken: false,
agentsMd: null,
});
const atCap = report(HYGIENE_LIST_CAP);
@@ -550,6 +552,7 @@ describe("formatActiveHygiene", () => {
inboxPressure: null,
memoryInbox: null,
leftoverInstructionFiles: [],
+ geminiSettingsBroken: false,
agentsMd: null,
});
const text = lines.join("\n");
@@ -655,14 +658,84 @@ describe("leftover CLAUDE.md beside AGENTS.md (#321)", () => {
});
});
- test("Gemini settings with comments or a BOM, which Gemini accepts, are still read", () => {
+ // As Gemini loads its settings (geminiContextFiles cites the source): comments
+ // are fine and count as whitespace; a BOM or a trailing comma is fatal (#374).
+ const rawSettings = (root: string, text: string): void => {
+ mkdirSync(join(root, ".gemini"), { recursive: true });
+ writeFileSync(join(root, ".gemini/settings.json"), text);
+ };
+ const scanWith = (text: string) => {
+ let report: ReturnType<typeof scanActiveHygiene> | undefined;
withFiles(["AGENTS.md", "GEMINI.md"], (root) => {
- mkdirSync(join(root, ".gemini"), { recursive: true });
- writeFileSync(
- join(root, ".gemini/settings.json"),
- '{\n // where Gemini looks\n "context": { "fileName": ["AGENTS.md"] },\n /* hooks */ "hooks": {}\n}\n',
- );
- assert.deepEqual(scanActiveHygiene(root, NOW, DEFAULTS).leftoverInstructionFiles, ["GEMINI.md"]);
+ rawSettings(root, text);
+ report = scanActiveHygiene(root, NOW, DEFAULTS);
+ });
+ return report!;
+ };
+
+ test("Gemini settings with comments and CRLF, which Gemini accepts, are still read", () => {
+ const report = scanWith('{\r\n // where Gemini looks\r\n "context": { "fileName": ["AGENTS.md"] },\r\n /* hooks */ "hooks": {}\r\n}\r\n');
+ assert.deepEqual(report.leftoverInstructionFiles, ["GEMINI.md"]);
+ assert.equal(report.geminiSettingsBroken, false);
+ });
+
+ for (const [name, text] of [
+ ["a BOM", '{ "context": { "fileName": "AGENTS.md" } }'],
+ ["a missing brace", '{ "context": { "fileName": "AGENTS.md" }'],
+ ["a trailing comma", '{ "context": { "fileName": "AGENTS.md", }, }'],
+ ["a comment inside a token, which is whitespace", '{ "debug": tr/**/ue, "context": { "fileName": "AGENTS.md" } }'],
+ ["an unterminated block comment swallowing the closing brace", '{ "context": { "fileName": "AGENTS.md" } /* never closed'],
+ ["a JSON value that is not an object", '["AGENTS.md"]'],
+ ] as const) {
+ test(`settings Gemini cannot load (${name}) name nothing, and are reported as broken`, () => {
+ const report = scanWith(text);
+ assert.deepEqual(report.leftoverInstructionFiles, [], "GEMINI.md is not retired by a file Gemini never applies");
+ assert.equal(report.geminiSettingsBroken, true);
+ });
+ }
+
+ test("a broken settings file says to fix it and keep GEMINI.md, never to delete GEMINI.md", () => {
+ const text = formatActiveHygiene(scanWith('{ "context": { "fileName": "AGENTS.md", } }')).join("\n");
+ assert.match(text, /\.gemini\/settings\.json doesn't parse — Gemini refuses to start until it does/);
+ assert.match(text, /keep GEMINI\.md/);
+ assert.doesNotMatch(text, /delete it/);
+ });
+
+ test("an unterminated block comment after a complete object still parses", () => {
+ const report = scanWith('{ "context": { "fileName": "AGENTS.md" } } /* never closed');
+ assert.deepEqual(report.leftoverInstructionFiles, ["GEMINI.md"]);
+ });
+
+ test("a commented-out fileName doesn't count, and a // inside a string is no comment", () => {
+ assert.deepEqual(
+ scanWith('{\n // was: "fileName": "AGENTS.md"\n /* "context": { "fileName": ["AGENTS.md"] } */\n "context": { "fileName": "GEMINI.md" }\n}\n').leftoverInstructionFiles,
+ [],
+ );
+ assert.deepEqual(
+ scanWith('{ "$schema": "https://example.com/s.json", "context": { "fileName": "AGENTS.md" } }').leftoverInstructionFiles,
+ ["GEMINI.md"],
+ );
+ // An escaped quote doesn't end the string, so the // after it is still inside it.
+ assert.deepEqual(
+ scanWith(String.raw`{ "note": "a 12\" ruler // not a comment", "context": { "fileName": "AGENTS.md" } }`).leftoverInstructionFiles,
+ ["GEMINI.md"],
+ );
+ });
+
+ test("only the top-level context counts, and the v1 contextFileName where context.fileName is absent", () => {
+ assert.deepEqual(scanWith('{ "mcpServers": { "x": { "context": { "fileName": "AGENTS.md" } } } }').leftoverInstructionFiles, []);
+ assert.deepEqual(scanWith('{ "contextFileName": "AGENTS.md" }').leftoverInstructionFiles, ["GEMINI.md"]);
+ assert.deepEqual(
+ scanWith('{ "contextFileName": "AGENTS.md", "context": { "fileName": "GEMINI.md" } }').leftoverInstructionFiles,
+ [],
+ "context.fileName wins over the v1 key",
+ );
+ });
+
+ test("no broken flag without AGENTS.md: a vault that hasn't upgraded gets no instruction-file findings", () => {
+ withFiles(["GEMINI.md"], (root) => {
+ rawSettings(root, "{ broken");
+ assert.equal(scanActiveHygiene(root, NOW, DEFAULTS).geminiSettingsBroken, false);
});
});
diff --git a/.claude/scripts/tests/stop-report.test.ts b/.claude/scripts/tests/stop-report.test.ts
index 111bd8d..e9f498e 100644
--- a/.claude/scripts/tests/stop-report.test.ts
+++ b/.claude/scripts/tests/stop-report.test.ts
@@ -26,6 +26,7 @@ const EVERY_FINDING: ActiveHygieneReport = {
inboxPressure: { count: 2, oldestDays: 9 },
memoryInbox: { count: 4, oldestDays: 2, namedOnly: 1 },
leftoverInstructionFiles: ["CLAUDE.md", "GEMINI.md"],
+ geminiSettingsBroken: true,
agentsMd: { sizeKb: 23 },
};
@@ -50,6 +51,7 @@ describe("stopSummary", () => {
describe("hygieneClaims", () => {
test("every finding reduces to its claim: counts, no file lists, no instructions", () => {
assert.deepEqual(hygieneClaims(EVERY_FINDING), [
+ ".gemini/settings.json doesn't parse",
"CLAUDE.md present beside AGENTS.md",
"GEMINI.md present beside AGENTS.md",
"AGENTS.md is 23KB",
@@ -72,7 +74,7 @@ describe("hygieneClaims", () => {
test("a clean report has no claims", () => {
assert.deepEqual(
- hygieneClaims({ completedInActive: [], ungroupedClusters: [], oversizedNotes: [], openLoops: [], inboxPressure: null, memoryInbox: null, leftoverInstructionFiles: [], agentsMd: null }),
+ hygieneClaims({ completedInActive: [], ungroupedClusters: [], oversizedNotes: [], openLoops: [], inboxPressure: null, memoryInbox: null, leftoverInstructionFiles: [], geminiSettingsBroken: false, agentsMd: null }),
[],
);
});