fix(global-discover): bucket Codex sessions by originator

Every Codex rollout counted as one undifferentiated codex bucket, so
/retro global could not tell interactive Codex Desktop work from
codex_exec runs or Claude Code-driven calls. Normalize
session_meta.payload.originator into desktop, exec, claude_code or
other (missing, unknown and non-string values), report the split per
repo as codex_originators and globally as tools.codex.originators, and
print it in the summary. Existing totals are unchanged. Adopts #1488.
Refs #1315.

Co-authored-by: 0xDevNinja <manmit0x@gmail.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
committed 2026-10-08 06:22:57 +00:00
1 parent 04359a12de
commit 2fa0ec1733
2 files changed
+130 -4

No files matched your search

+41 -4
View File
@@ -17,9 +17,13 @@ import { canonicalRemote } from "../lib/remote-identity";
// ── Types ──────────────────────────────────────────────────────────────────
type CodexOriginator = "desktop" | "exec" | "claude_code" | "other";
type CodexOriginatorCounts = Record<CodexOriginator, number>;
interface Session {
tool: "claude_code" | "codex" | "gemini";
cwd: string;
codexOriginator?: CodexOriginator;
}
interface Repo {
@@ -27,6 +31,7 @@ interface Repo {
remote: string;
paths: string[];
sessions: { claude_code: number; codex: number; gemini: number };
codex_originators: CodexOriginatorCounts;
}
interface DiscoveryResult {
@@ -35,7 +40,7 @@ interface DiscoveryResult {
repos: Repo[];
tools: {
claude_code: { total_sessions: number; repos: number };
codex: { total_sessions: number; repos: number };
codex: { total_sessions: number; repos: number; originators: CodexOriginatorCounts };
gemini: { total_sessions: number; repos: number };
};
total_sessions: number;
@@ -283,6 +288,30 @@ export function extractCwdFromJsonl(filePath: string): string | null {
return null;
}
// Separates interactive Codex Desktop work from codex exec runs and Claude
// Code-driven calls. Missing, unknown and non-string values count as "other",
// so the buckets always sum to the Codex session total.
function normalizeCodexOriginator(raw: unknown): CodexOriginator {
if (typeof raw !== "string") return "other";
const value = raw.trim().toLowerCase();
if (value === "codex desktop" || value === "codex_desktop") return "desktop";
if (value === "codex_exec" || value === "codex exec") return "exec";
if (value === "claude code" || value === "claude_code") return "claude_code";
return "other";
}
function countCodexOriginators(sessions: Session[]): CodexOriginatorCounts {
const counts: CodexOriginatorCounts = { desktop: 0, exec: 0, claude_code: 0, other: 0 };
for (const s of sessions) {
if (s.tool === "codex") counts[s.codexOriginator ?? "other"]++;
}
return counts;
}
function formatCodexOriginators(o: CodexOriginatorCounts): string {
return `desktop=${o.desktop}, exec=${o.exec}, claude_code=${o.claude_code}, other=${o.other}`;
}
function scanCodex(since: Date): Session[] {
const sessionsDir = process.env.CODEX_SESSIONS_DIR || join(homedir(), ".codex", "sessions");
if (!existsSync(sessionsDir)) return [];
@@ -332,7 +361,11 @@ function scanCodex(since: Date): Session[] {
if (!firstLine) continue;
const meta = JSON.parse(firstLine);
if (meta.type === "session_meta" && meta.payload?.cwd) {
sessions.push({ tool: "codex", cwd: meta.payload.cwd });
sessions.push({
tool: "codex",
cwd: meta.payload.cwd,
codexOriginator: normalizeCodexOriginator(meta.payload.originator),
});
}
} catch {
console.error(`Warning: could not parse Codex session ${filePath}`);
@@ -503,6 +536,7 @@ async function resolveAndDeduplicate(sessions: Session[]): Promise<Repo[]> {
remote,
paths: data.paths,
sessions: sessionCounts,
codex_originators: countCodexOriginators(data.sessions),
});
}
@@ -545,13 +579,15 @@ async function main() {
const codexRepos = new Set(repos.filter((r) => r.sessions.codex > 0).map((r) => r.remote)).size;
const geminiRepos = new Set(repos.filter((r) => r.sessions.gemini > 0).map((r) => r.remote)).size;
const codexOriginators = countCodexOriginators(codexSessions);
const result: DiscoveryResult = {
window: since,
start_date: startDate,
repos,
tools: {
claude_code: { total_sessions: ccSessions.length, repos: ccRepos },
codex: { total_sessions: codexSessions.length, repos: codexRepos },
codex: { total_sessions: codexSessions.length, repos: codexRepos, originators: codexOriginators },
gemini: { total_sessions: geminiSessions.length, repos: geminiRepos },
},
total_sessions: allSessions.length,
@@ -564,13 +600,14 @@ async function main() {
// Summary format
console.log(`Window: ${since} (since ${startDate})`);
console.log(`Sessions: ${allSessions.length} total (CC: ${ccSessions.length}, Codex: ${codexSessions.length}, Gemini: ${geminiSessions.length})`);
if (codexSessions.length > 0) console.log(` Codex originators: ${formatCodexOriginators(codexOriginators)}`);
console.log(`Repos: ${repos.length} unique`);
console.log("");
for (const repo of repos) {
const total = repo.sessions.claude_code + repo.sessions.codex + repo.sessions.gemini;
const tools = [];
if (repo.sessions.claude_code > 0) tools.push(`CC:${repo.sessions.claude_code}`);
if (repo.sessions.codex > 0) tools.push(`Codex:${repo.sessions.codex}`);
if (repo.sessions.codex > 0) tools.push(`Codex:${repo.sessions.codex} (${formatCodexOriginators(repo.codex_originators)})`);
if (repo.sessions.gemini > 0) tools.push(`Gemini:${repo.sessions.gemini}`);
console.log(` ${repo.name} (${total} sessions) — ${tools.join(", ")}`);
console.log(` Remote: ${repo.remote}`);
+89
View File
@@ -291,6 +291,95 @@ describe("gstack-global-discover", () => {
});
});
describe("codex originator buckets", () => {
let tmpDir: string;
let codexDir: string;
let repoDir: string;
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), "gstack-codex-orig-"));
const now = new Date();
const y = now.getFullYear().toString();
const m = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
codexDir = join(tmpDir, "codex-home", "sessions", y, m, d);
mkdirSync(codexDir, { recursive: true });
repoDir = join(tmpDir, "fake-repo");
mkdirSync(repoDir);
spawnSync("git", ["init", "-q"], { cwd: repoDir, stdio: "pipe", timeout: 30_000 });
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
// Pass no argument to omit originator from the payload.
function writeCodex(...originator: unknown[]) {
const payload: Record<string, unknown> = { id: `t-${Math.random()}`, timestamp: new Date().toISOString(), cwd: repoDir };
if (originator.length) payload.originator = originator[0];
const name = `rollout-${new Date().toISOString().replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2)}.jsonl`;
writeFileSync(join(codexDir, name), JSON.stringify({ timestamp: new Date().toISOString(), type: "session_meta", payload }) + "\n");
}
function discover(format: "json" | "summary" = "json") {
const r = spawnSync("bun", ["run", scriptPath, "--since", "1h", "--format", format], {
encoding: "utf-8",
timeout: 30_000,
env: { ...process.env, CODEX_SESSIONS_DIR: join(tmpDir, "codex-home", "sessions") },
});
expect(r.status).toBe(0);
return r.stdout;
}
const originators = () => JSON.parse(discover()).tools.codex.originators;
test("Codex Desktop goes to desktop", () => {
writeCodex("Codex Desktop");
expect(originators()).toEqual({ desktop: 1, exec: 0, claude_code: 0, other: 0 });
});
test("codex_exec goes to exec", () => {
writeCodex("codex_exec");
expect(originators()).toEqual({ desktop: 0, exec: 1, claude_code: 0, other: 0 });
});
test("Claude Code goes to claude_code", () => {
writeCodex("Claude Code");
expect(originators()).toEqual({ desktop: 0, exec: 0, claude_code: 1, other: 0 });
});
test("surrounding whitespace and case are ignored", () => {
writeCodex(" CODEX DESKTOP ");
expect(originators()).toEqual({ desktop: 1, exec: 0, claude_code: 0, other: 0 });
});
test("missing, null, numeric and unknown originators go to other", () => {
writeCodex();
writeCodex(null);
writeCodex(42);
writeCodex("future-agent");
const json = JSON.parse(discover());
expect(json.tools.codex.total_sessions).toBe(4);
expect(json.tools.codex.originators).toEqual({ desktop: 0, exec: 0, claude_code: 0, other: 4 });
});
test("per-repo and global buckets sum to the codex total and print in the summary", () => {
writeCodex("Codex Desktop");
writeCodex("codex_exec");
writeCodex("codex_exec");
writeCodex("Claude Code");
writeCodex();
const json = JSON.parse(discover());
const sum = (o: Record<string, number>) => Object.values(o).reduce((a, b) => a + b, 0);
expect(json.tools.codex.total_sessions).toBe(5);
expect(sum(json.tools.codex.originators)).toBe(5);
const repo = json.repos.find((r: { paths: string[] }) => r.paths.includes(repoDir));
expect(repo.codex_originators).toEqual({ desktop: 1, exec: 2, claude_code: 1, other: 1 });
expect(sum(repo.codex_originators)).toBe(repo.sessions.codex);
expect(discover("summary")).toContain("Codex originators: desktop=1, exec=2, claude_code=1, other=1");
});
});
describe("discovery output structure", () => {
test("repos have required fields", () => {
const result = spawnSync(