Skip to content
43 changes: 43 additions & 0 deletions .genie/wishes/codex-plugin-dogfood-remediation/HANDOFF-20260722.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Handoff — codex-plugin-dogfood-remediation (2026-07-22)

**Wish:** `.genie/wishes/codex-plugin-dogfood-remediation/WISH.md` (APPROVED, 7 groups A–G).
**Status: Waves 1 + 2 DONE and merged to dev. Next = Wave 3 (Group E).**

## DAG
`B → A`, `B → D`, `{A,B,D} → E`, `{C,E} → F`, `F → G`. Groups B,C = Wave 1; A,D = Wave 2; E = Wave 3; F = Wave 4; G = Wave 5.

## Merged so far (all in `origin/dev`, tip was `8a92fbd6`)
| Group | PR | Verified |
|---|---|---|
| B host-observation-attestation | #2625 | 165/0 incl. live app-server proof; pre-mutation guard real |
| C managed-assets-convergence | #2626 | 403/0; byte-identical preservation, R3 intact |
| A project-route-context | #2629 | 94/0; empty-board masquerade closed; plugin Codex MCP route removed |
| D immutable-delivery-repair | #2628 | 397/0; one-shot repair + `.install-version` module |

Files landed: `src/lib/codex-host-observation.ts`, `src/fixtures/codex-role-agent-allowlist.json`, `src/lib/codex-project-mcp.ts` + `resolveProjectContext` in `src/lib/v5/mcp-tools.ts`/`mcp-server.ts`, `src/lib/install-version-marker.ts`, delivery-repair in `src/genie-commands/update.ts`/`install.ts`/`codex-delivery*.ts`. Plugin `.mcp.json` + manifest `mcpServers` DELETED (Claude's `scripts/mcp-launcher.cjs` retained).

## CARRY-FORWARD into Group E (lifecycle-truth-integration) — do these, they were deliberately deferred, not dropped
1. **A's config-layer typed states** (deferred per Decision 15): distinct classification for `untrusted-config`, `global same-key route`, `effective-layer shadowing`, `route-collision`, `route-shadowed`, `project-trust-required` — these are doctor/init diagnostics, not read-only-MCP-server states. A shipped only `project-context-unavailable`/`project-database-unavailable`/`unsupported-project-layout`.
2. **D's `uninstallInstallVersionMarker` wiring**: exported+unit-tested but NOT called by `src/genie-commands/uninstall.ts`. Behavior is already correct (`.install-version` removed by the digest-verified wholesale GENIE_HOME child removal — it's absent from `preservedGenieDirEntry`). Wire the explicit symlink-safe call **with awareness the wholesale removal is digest-verified** (removing the marker first could invalidate `scope.genieHomeRemovalDigest`), OR delete it + document. Do NOT rush this into the digest path.
3. **A's live-QA-only item (AC3)**: `codex mcp get genie --json` showing one marker-owned facade route + no plugin route — Felipe's post-merge live-QA ritual, kept out of CI.

## Group E scope (from WISH)
"lifecycle-truth-integration: wire route/context, observation, repair handoff, setup, and doctor" — integrate A+B+D contracts into setup/doctor WITHOUT changing their contracts. Complexity 5. depends-on {A,B,D} (all merged ✓).

## HOW to run a wave (the working pattern — reuse it)
`Workflow` tool, isolated worktrees, `model:'opus' effort:'max'`, `agentType:'engineer-complex'`, `isolation:'worktree'`. Pipeline: implement → adversarial `reviewer`. Engineers commit to `wish/dogfood-<G>` (NO push), report structured. Then ORCHESTRATOR:
- Re-run the group's validation YOURSELF in its worktree (`.claude/worktrees/wf_*-N`) — do not trust the report.
- **Run codex-touching tests with `codex` STRIPPED from PATH** (`PATH="$HOME/.bun/bin:/usr/bin:/bin"`) — this is the CI condition; it caught the flake.
- Strip any stray `.well-known/dev.json` (`git checkout origin/dev -- .well-known/dev.json`).
- Push, open PR to dev, then **`gh run watch` the CI to green** — the black-box **Codex Plugin Smoke** and **E2E** jobs run things the file-level review can't. Fix reds via a `fixer` (opus) with the smoke as the gate.
- `SKIP_CI_CHECK=1 git commit` is the sanctioned escape when a commit IS the CI fix.

## Hard-won gotchas (cost us fix loops this session)
- **CI has NO `codex` binary and NO network.** Any test spawning `codex` must do a synchronous `execFileSync('codex',['--version'])` preflight and skip; never let an async spawn `'error'` (ENOENT) throw unhandled at module load (that aborts the whole file — Group B's first CI fail).
- **Readonly SQLite opens must carry `busy_timeout`.** Raw `new Database(p,{readonly:true})` bypasses `sqlite-open.ts`'s `BUSY_TIMEOUT_MS` → flaky "database is locked" under concurrent writers (Group A's HIGH). Import `BUSY_TIMEOUT_MS`; checkpoint (`wal_checkpoint(TRUNCATE)`) writers before readers in tests.
- **Plugin health ≠ Codex MCP provider anymore.** A removed the plugin MCP route; `proveCodexPluginHealth`/`parseCodexPluginSnapshot`/`codex-mcp-health-session.ts` were reconciled so health = installed+enabled+version+canonical-root+payload+working launcher, and the throwaway-cwd health probe now accepts A's typed `project-context-*` errors as healthy. Don't regress this.
- Discipline reminders: reviewer ≠ engineer; verify every subagent claim with your own runs; Felipe merges PRs himself (present them, don't merge); the roadmap board + this wish are the trackers.

## Separately open (not this wish)
- `stable-release-security-gate` wish still blocks STABLE promotion.
- codex-plugin-update-handoff live homolog dogfood ritual (Felipe's) gates that wish → SHIPPED.
169 changes: 168 additions & 1 deletion src/genie-commands/doctor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,17 @@ describe('doctorCommand', () => {
});
});

/**
* Group E: mark a project trusted in the isolated CODEX_HOME global config so
* the route-layer classifier can claim route health for it.
*/
function trustProjectInCodexConfig(root: string): void {
const configPath = join(process.env.CODEX_HOME as string, 'config.toml');
mkdirSync(dirname(configPath), { recursive: true });
const existing = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
writeFileSync(configPath, `${existing}[projects."${root}"]\ntrust_level = "trusted"\n`);
}

describe('Codex doctor lifecycle results', () => {
test('a timed-out plugin query is a structured hard failure, not a false pass', async () => {
const checks = await checkCodexIntegration(process.cwd(), {
Expand All @@ -182,6 +193,7 @@ describe('Codex doctor lifecycle results', () => {
test('missing configured Node is actionable and never displaces the fallback', async () => {
const root = mkdtempSync(join(tmpdir(), 'doctor-node-availability-'));
try {
trustProjectInCodexConfig(root);
reconcileCodexProjectMcp(
root,
{ cliAvailable: true, status: 'ok', installed: true, enabled: false, usable: false, detail: 'disabled' },
Expand Down Expand Up @@ -212,6 +224,7 @@ describe('Codex doctor lifecycle results', () => {
const priorCodexHome = process.env.CODEX_HOME;
process.env.CODEX_HOME = join(root, 'codex-home');
try {
trustProjectInCodexConfig(root);
expect(existsSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.codex-plugin', 'plugin.json'))).toBe(
true,
);
Expand Down Expand Up @@ -1776,13 +1789,27 @@ function docRegPresent(version = DOC_T): QueryFact {
function docCachePresent(digest = DOC_DIGEST): PhysicalCacheFact {
return { kind: 'present', digest, identity: '10:200' };
}
/** A matching authenticated delivery record binding the canonical target (Group E delivery gate). */
function docDeliveryPresent(): CodexActivationSnapshot['delivery'] {
return {
status: 'present',
record: {
schemaVersion: 1,
deliveryId: 'c'.repeat(32),
targetVersion: DOC_T,
canonicalPayloadSha256: DOC_DIGEST,
channel: 'stable',
deliveredAt: '2026-07-12T00:00:00.000Z',
},
};
}
function docCurrentSnapshot(): CodexActivationSnapshot {
return {
canonical: docOkCanonical(),
query: docRegPresent(),
cache: docCachePresent(),
receipt: { status: 'absent' },
delivery: { status: 'absent' },
delivery: docDeliveryPresent(),
intent: { status: 'absent' },
receiptConsumed: false,
observationWitness: { before: docFamily(), after: docFamily() },
Expand Down Expand Up @@ -1915,3 +1942,143 @@ describe('doctor --json integrationSummary (Group D)', () => {
expect(source.includes('acquireLifecycleLease')).toBe(false);
});
});

describe('Group E lifecycle truth (doctor)', () => {
test('current state with an ABSENT delivery record presents delivery-incomplete, exit 1, recovery command', async () => {
const missingRecord = { ...docCurrentSnapshot(), delivery: { status: 'absent' as const } };
const { output, exitCode } = await captureDoctor(() =>
doctorCommand({ json: true }, doctorDepsWith(missingRecord)),
);
const json = JSON.parse(output) as DoctorJson;
expect(json.integrationSummary?.codexPlugin).toMatchObject({
state: 'delivery-incomplete',
deliveryComplete: false,
actionRequired: true,
mutationAuthority: 'none',
});
expect(json.integrationSummary?.codexPlugin.recovery).toContain('genie update');
expect(exitCode).toBe(1);
});

test('an INVALID record and a MISMATCHED record present the same consistent delivery-incomplete state', async () => {
const invalid = { ...docCurrentSnapshot(), delivery: { status: 'invalid' as const, detail: 'corrupt' } };
const mismatched = {
...docCurrentSnapshot(),
delivery: {
status: 'present' as const,
record: {
schemaVersion: 1 as const,
deliveryId: 'c'.repeat(32),
targetVersion: DOC_OLD,
canonicalPayloadSha256: DOC_DIGEST,
channel: 'stable',
deliveredAt: '2026-07-12T00:00:00.000Z',
},
},
};
for (const snapshot of [invalid, mismatched]) {
const { output, exitCode } = await captureDoctor(() => doctorCommand({ json: true }, doctorDepsWith(snapshot)));
const json = JSON.parse(output) as DoctorJson;
expect(json.integrationSummary?.codexPlugin.state).toBe('delivery-incomplete');
expect(json.integrationSummary?.codexPlugin.deliveryComplete).toBe(false);
expect(exitCode).toBe(1);
}
});

test('a harder exit-1 state (query-failed) keeps its own presentation; deliveryComplete still false', async () => {
const queryFailedNoRecord = { ...docQueryFailedSnapshot(), delivery: { status: 'absent' as const } };
const { output, exitCode } = await captureDoctor(() =>
doctorCommand({ json: true }, doctorDepsWith(queryFailedNoRecord)),
);
const json = JSON.parse(output) as DoctorJson;
expect(json.integrationSummary?.codexPlugin.state).toBe('query-failed');
expect(json.integrationSummary?.codexPlugin.deliveryComplete).toBe(false);
expect(exitCode).toBe(1);
});

test('matching record keeps current green: exit 0, deliveryComplete true (regression anchor)', async () => {
const { output, exitCode } = await captureDoctor(() =>
doctorCommand({ json: true }, doctorDepsWith(docCurrentSnapshot())),
);
const json = JSON.parse(output) as DoctorJson;
expect(json.integrationSummary?.codexPlugin).toMatchObject({ state: 'current', deliveryComplete: true });
expect(exitCode).toBe(0);
});

test('unified host path: one canned query feeds advisory rider AND a non-query-failed summary (Decision 11)', async () => {
const calls: string[][] = [];
const stdout = JSON.stringify({
installed: [{ pluginId: 'genie@automagik', version: '5.260722.1', enabled: true }],
});
const { output } = await captureDoctor(() =>
doctorCommand(
{ json: true },
{
root: join(isolatedHome, 'repo'),
databaseRoot: join(isolatedHome, 'repo'),
bunVersion: '1.3.10',
bunPath: '/usr/bin/bun',
codexHost: {
which: () => process.execPath,
codexHome: join(isolatedHome, 'codex'),
runner: (command, args) => {
calls.push([command, ...args]);
return {
exitCode: 0,
stdout,
stderr: '\x1b[33mWARN: PATH advisory\x1b[0m',
};
},
},
},
),
);
// Exactly one spawn fed the probe AND (via replay) the activation snapshot.
expect(calls).toEqual([[process.execPath, 'plugin', 'list', '--json']]);
const json = JSON.parse(output) as DoctorJson;
const cli = json.checks.find((check) => check.name === 'Codex CLI') as
| { name: string; status: string; advisory?: string; detail?: string }
| undefined;
expect(cli?.advisory).toBe('WARN: PATH advisory');
expect(cli?.detail).toContain('advisory: WARN: PATH advisory');
// The advisory did NOT flip the fail-closed activation parser to query-failed.
expect(json.integrationSummary?.codexPlugin.state).not.toBe('query-failed');
// One ANSI-free JSON document: the raw advisory's escape bytes never reach stdout.
expect(output).not.toContain('\x1b[33m');
});

test('project context: ok / database-unavailable / unsupported-layout map to pass / warn / fail', async () => {
const base = {
effectiveLaunchCwd: '/repo',
worktreeConfigRoot: '/repo',
gitCommonDir: '/repo/.git',
genieStorageRoot: '/repo',
dbPath: '/repo/.genie/genie.db',
};
const cases = [
{ context: { kind: 'ok' as const, ...base }, status: 'pass' },
{
context: { kind: 'project-database-unavailable' as const, effectiveLaunchCwd: '/repo', detail: 'no db' },
status: 'warn',
},
{
context: { kind: 'unsupported-project-layout' as const, effectiveLaunchCwd: '/repo', detail: 'bare repo' },
status: 'fail',
},
];
for (const { context, status } of cases) {
const { output } = await captureDoctor(() =>
doctorCommand({ json: true }, { ...doctorDepsWith(null), projectContext: context }),
);
const json = JSON.parse(output) as DoctorJson;
const check = json.checks.find((c) => c.name === 'Codex project context');
expect(check?.status).toBe(status);
}
});

test('injected root without injected context skips the context check (unit-test seam, not a repo)', async () => {
const { output } = await captureDoctor(() => doctorCommand({ json: true }, doctorDepsWith(null)));
const json = JSON.parse(output) as DoctorJson;
expect(json.checks.find((c) => c.name === 'Codex project context')).toBeUndefined();
});
});
Loading
Loading