diff --git a/src/fixtures/codex-role-agent-allowlist.json b/src/fixtures/codex-role-agent-allowlist.json new file mode 100644 index 000000000..00ebe5592 --- /dev/null +++ b/src/fixtures/codex-role-agent-allowlist.json @@ -0,0 +1,62 @@ +[ + { + "name": "genie-engineer-complex.toml", + "type": "regular", + "mode": "0644", + "digest": "62ecc570f1d77783511a9e7f0aa67b3a65d8bba292963409a02c7712c93ebc3b" + }, + { + "name": "genie-engineer-standard.toml", + "type": "regular", + "mode": "0644", + "digest": "dc746813b9b4b6aa984c17fa2fd75d4dbe34eba08494a174c0715da07aa9dd30" + }, + { + "name": "genie-engineer-trivial.toml", + "type": "regular", + "mode": "0644", + "digest": "249deced5a02eb2cbe3303db566992d1336c75d853967f851bf1d0e85b6b0f47" + }, + { + "name": "genie-final-gate.toml", + "type": "regular", + "mode": "0644", + "digest": "10ef070db8aace75bd80ef9e060a6ec601e3768f177fdd843f4db11035738f7e" + }, + { + "name": "genie-fixer.toml", + "type": "regular", + "mode": "0644", + "digest": "b3c1f407d4a3a2cfe204dee7b4a9c038e1a8f4644c446fcfa23f4a681bf0c7b3" + }, + { + "name": "genie-reviewer.toml", + "type": "regular", + "mode": "0644", + "digest": "55bb2dea3da381f4d6ea210869f9a26ac1eed825097085a9bfa0f41a005c8d14" + }, + { + "name": "genie-reviewer.toml", + "type": "regular", + "mode": "0644", + "digest": "91f40a07905834716311419375581e3245544a77eac3d93d082842652c6452bf" + }, + { + "name": "genie-reviewer.toml", + "type": "regular", + "mode": "0644", + "digest": "c7008dcaa1e31b46e2bb05ca13afb2e918ee483422c84386a1c8997485bcfea7" + }, + { + "name": "genie-reviewer.toml", + "type": "regular", + "mode": "0644", + "digest": "f0bf69fa70dc9e014305f155a024c4dadb6caf48ce217b8c31119506e244f844" + }, + { + "name": "genie-scout.toml", + "type": "regular", + "mode": "0644", + "digest": "03a9fb3ca0e5f36c69c8f934d37adce1bae736e4c3895b144a0001ad31b1ba59" + } +] diff --git a/src/genie-commands/doctor.ts b/src/genie-commands/doctor.ts index c9309bd56..e8eb0ec79 100644 --- a/src/genie-commands/doctor.ts +++ b/src/genie-commands/doctor.ts @@ -72,6 +72,7 @@ import { hasDuplicateSkillsExternalDirsKeys, resolveProductSkillsRoot } from '.. import { resolveOmniRuntimeConfig } from '../lib/omni-config.js'; import { CANONICAL_GENIE_SKILL_NAMES, + type CodexAgentDisplayState, inspectCodexAgentOwnership, inspectCodexFallbackTier, } from '../lib/runtime-integrations.js'; @@ -400,20 +401,38 @@ function codexPluginCheck(state: CodexPluginProbe): CheckResult { function codexAgentCheck(): CheckResult { const report = inspectCodexAgentOwnership(resolveCodexDir()); + const total = report.expectedDeliveredTotal; + const count = (state: CodexAgentDisplayState): number => + report.entries.filter((entry) => entry.state === state).length; const counts = { - clean: report.entries.filter((entry) => entry.ownership === 'managed-clean').length, - modified: report.entries.filter((entry) => entry.ownership === 'managed-modified').length, - user: report.entries.filter((entry) => entry.ownership === 'user-owned').length, - absent: report.entries.filter((entry) => entry.ownership === 'absent').length, + managed: count('managed'), + stale: count('stale'), + adoptable: count('adoptable-historical'), + collision: count('collision'), + personal: count('personal'), + absent: count('absent'), }; - const healthy = report.status === 'valid' && counts.clean === 7 && counts.modified === 0 && counts.absent === 0; + // Personal files are the operator's own unrelated agents — present is healthy. + // Every other non-managed state (stale/adoptable/collision/absent) is actionable. + const healthy = + report.status === 'valid' && + counts.managed === total && + counts.stale === 0 && + counts.adoptable === 0 && + counts.collision === 0 && + counts.absent === 0; + const suggestion = + counts.adoptable > 0 || counts.stale > 0 || counts.managed < total + ? 'Run `genie setup --codex` to adopt and refresh delivered role agents; personal and collision files are never overwritten.' + : 'Review collision role agents (modified/symlinked/lookalike); Genie will not overwrite them, then run `genie setup --codex`.'; return { name: 'Codex Genie role agents', status: healthy ? 'pass' : 'warn', - detail: `inventory ${report.status}; clean=${counts.clean}/7, modified=${counts.modified}, user-owned=${counts.user}, absent=${counts.absent}${report.error ? ` (${report.error})` : ''}`, - suggestion: healthy - ? undefined - : 'Review modified/user-owned collisions, then run `genie setup --codex`; Genie will not overwrite them.', + detail: + `inventory ${report.status}; managed=${counts.managed}/${total}, stale=${counts.stale}, ` + + `adoptable=${counts.adoptable}, collision=${counts.collision}, personal=${counts.personal}, absent=${counts.absent}; ` + + `reviewer digest ${report.reviewerDigest.slice(0, 12)}${report.error ? ` (${report.error})` : ''}`, + suggestion: healthy ? undefined : suggestion, }; } diff --git a/src/genie-commands/uninstall.test.ts b/src/genie-commands/uninstall.test.ts index e2255d0b3..a4e6f76d9 100644 --- a/src/genie-commands/uninstall.test.ts +++ b/src/genie-commands/uninstall.test.ts @@ -2068,6 +2068,7 @@ describe('durable runtime integration allowlist', () => { name: 'genie-later.toml', path: '/tmp/genie-later.toml', ownership: 'managed-clean', + state: 'managed', }, ], }, @@ -2162,6 +2163,8 @@ describe('uninstall ownership and work detection', () => { inventoryPath: join(root, 'inventory.json'), status: 'missing' as const, entries: [], + expectedDeliveredTotal: 7, + reviewerDigest: 'c7008dcaa1e31b46e2bb05ca13afb2e918ee483422c84386a1c8997485bcfea7', }), inspectRuntimeClientAvailability: () => ({ codex: false, diff --git a/src/lib/runtime-integrations.test.ts b/src/lib/runtime-integrations.test.ts index 972eeeedc..4de067e85 100644 --- a/src/lib/runtime-integrations.test.ts +++ b/src/lib/runtime-integrations.test.ts @@ -11,6 +11,7 @@ import { realpathSync, rmSync, symlinkSync, + utimesSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -24,9 +25,14 @@ import { import { REQUIRED_GENIE_MCP_TOOLS } from './codex-mcp-health-session.js'; import type { CodexPluginProbe } from './codex-project-mcp.js'; import { + CANONICAL_CODEX_REVIEWER_DIGEST, + CANONICAL_CODEX_ROLE_AGENT_DIGESTS, + CANONICAL_CODEX_ROLE_AGENT_MODE, + CANONICAL_CODEX_ROLE_AGENT_NAMES, CANONICAL_GENIE_SKILL_NAMES, type CodexHealthProof, type CodexPluginOnlyDeps, + EXPECTED_CODEX_ROLE_AGENT_TOTAL, type InstallIntegrationsOptions, type IntegrationResult, type ProveCodexPluginHealthOptions, @@ -34,6 +40,8 @@ import { claudePluginState, clearIntegrationConsentTransition, codexPluginState, + codexRoleAdoptionAllowed, + codexRoleAgentTupleKey, commitIntegrationConsentTransition, convergeClaudePlugin, convergeCodexPlugin, @@ -43,6 +51,8 @@ import { inspectRuntimeIntegrationEvidence, installCodexAgents, installRuntimeIntegrations as installRuntimeIntegrationsWithPhysicalVerification, + loadHistoricalRoleAgentProfiles, + loadHistoricalRoleAgentTupleKeys, parseClaudePluginState, parseCodexPluginState, persistIntegrationConsent, @@ -2919,3 +2929,397 @@ describe('inspectCodexFallbackTier (shared doctor/uninstall classifier — read- expect(report.preservedCollisions).toEqual([]); }); }); + +// ── Group C: managed-assets-convergence ───────────────────────────────────── +// Adopt delivered Codex role agents + inventory without claiming or damaging +// user-owned files. Real role bytes come straight from the committed bundle so +// the frozen allowlist is exercised against the exact profiles it must recognize. + +const REAL_CODEX_AGENTS_DIR = resolve(import.meta.dir, '..', '..', 'plugins', 'genie', 'codex-agents'); + +function sha256Hex(bytes: Buffer | string): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +/** Byte-exact buffer comparison (avoids the SharedArrayBuffer-union friction of `toEqual` on raw reads). */ +function expectSameBytes(actual: Buffer, expected: Buffer): void { + expect(actual.equals(expected)).toBe(true); +} + +function realRoleNames(): string[] { + return readdirSync(REAL_CODEX_AGENTS_DIR) + .filter((name) => name.endsWith('.toml')) + .sort(); +} + +function realRoleBytes(name: string): Buffer { + return readFileSync(join(REAL_CODEX_AGENTS_DIR, name)); +} + +/** A temp bundle carrying the exact current role profiles at canonical mode 0644. */ +function makeRealCodexBundle(): string { + const bundleRoot = canonicalTempDir('genie-real-bundle-'); + const dest = join(bundleRoot, 'plugins', 'genie', 'codex-agents'); + mkdirSync(dest, { recursive: true }); + for (const name of realRoleNames()) { + const path = join(dest, name); + writeFileSync(path, realRoleBytes(name), { mode: 0o644 }); + chmodSync(path, 0o644); + } + return bundleRoot; +} + +function seedRoleFile(codexHome: string, name: string, bytes: Buffer | string, mode = 0o644): string { + const path = join(codexHome, 'agents', name); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, bytes, { mode }); + chmodSync(path, mode); + return path; +} + +/** The (name, mode, digest) allowlist key for a file exactly as it currently sits on disk. */ +function liveTupleKey(codexHome: string, name: string): string { + const path = join(codexHome, 'agents', name); + const stat = lstatSync(path); + return codexRoleAgentTupleKey(name, stat.mode & 0o7777, sha256Hex(readFileSync(path))); +} + +function stateByName(codexHome: string): Map { + return new Map(inspectCodexAgentOwnership(codexHome).entries.map((entry) => [entry.name, entry.state])); +} + +/** Real-installer convergence options (no injected installAgents, so adoption is exercised end-to-end). */ +function realConvergeOptions(input: { + codexHome: string; + genieHome: string; + bundleRoot: string; + deps?: Partial; +}) { + return { + runner: (() => ({ exitCode: 0, stdout: '{}', stderr: '' })) as never, + command: '/fixture/codex', + bundleRoot: input.bundleRoot, + expectedVersion: VERSION, + installIfAbsent: true, + statePath: join(input.genieHome, '.integration-refresh-codex.json'), + codexHome: input.codexHome, + genieHome: input.genieHome, + deps: { + converge: () => healthyPluginResult(), + probe: () => healthyCodexProbe(), + prove: () => healthyCodexProof(), + runSession: () => ({ ok: true, detail: 'ok', tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }), + fallbackSkillsDir: canonicalTempDir('genie-fallback-conv-'), + ...input.deps, + } as CodexPluginOnlyDeps, + }; +} + +describe('codex role-agent frozen historical allowlist (Group C)', () => { + test('CANONICAL role digests/mode match the committed bundle bytes exactly (parity gate)', () => { + const onDisk = realRoleNames(); + expect(onDisk).toEqual([...CANONICAL_CODEX_ROLE_AGENT_NAMES]); + expect(EXPECTED_CODEX_ROLE_AGENT_TOTAL).toBe(onDisk.length); + for (const name of CANONICAL_CODEX_ROLE_AGENT_NAMES) { + expect(sha256Hex(realRoleBytes(name))).toBe(CANONICAL_CODEX_ROLE_AGENT_DIGESTS[name]); + expect(lstatSync(join(REAL_CODEX_AGENTS_DIR, name)).mode & 0o7777).toBe(CANONICAL_CODEX_ROLE_AGENT_MODE); + } + expect(CANONICAL_CODEX_REVIEWER_DIGEST).toBe(CANONICAL_CODEX_ROLE_AGENT_DIGESTS['genie-reviewer.toml']); + }); + + test('the frozen allowlist is well-formed, covers every current profile, and carries historical reviewers', () => { + const profiles = loadHistoricalRoleAgentProfiles(); + expect(profiles.every((profile) => profile.type === 'regular' && profile.mode === 0o644)).toBe(true); + const keys = loadHistoricalRoleAgentTupleKeys(); + // Every current delivered profile is a member (a current-version fan-out is adoptable). + for (const name of CANONICAL_CODEX_ROLE_AGENT_NAMES) { + expect(keys.has(codexRoleAgentTupleKey(name, 0o644, CANONICAL_CODEX_ROLE_AGENT_DIGESTS[name]))).toBe(true); + } + // The reviewer legitimately fanned several profiles across releases; the union must recognize them. + const reviewerProfiles = profiles.filter((profile) => profile.name === 'genie-reviewer.toml'); + expect(reviewerProfiles.length).toBeGreaterThan(1); + const reviewerDigests = new Set(reviewerProfiles.map((profile) => profile.digest)); + expect(reviewerDigests.has(CANONICAL_CODEX_REVIEWER_DIGEST)).toBe(true); + // A known older reviewer profile (the introduction commit) stays recognizable as the "stale" case. + expect(reviewerDigests.has('91f40a07905834716311419375581e3245544a77eac3d93d082842652c6452bf')).toBe(true); + }); + + test('codexRoleAdoptionAllowed requires an explicit committed codex/all consent', () => { + expect(codexRoleAdoptionAllowed({ selection: 'codex', state: 'committed', revision: 1 })).toBe(true); + expect(codexRoleAdoptionAllowed({ selection: 'all', state: 'committed', revision: 1 })).toBe(true); + // Legacy auto default, sibling client, opt-out, and in-flight transitions never unlock adoption. + expect(codexRoleAdoptionAllowed({ selection: 'auto', state: 'committed', revision: 0 })).toBe(false); + expect(codexRoleAdoptionAllowed({ selection: 'claude', state: 'committed', revision: 1 })).toBe(false); + expect(codexRoleAdoptionAllowed({ selection: 'none', state: 'committed', revision: 1 })).toBe(false); + expect( + codexRoleAdoptionAllowed({ + selection: 'codex', + state: 'pending', + revision: 2, + previousSelection: 'auto', + transitionToken: 'a'.repeat(32), + }), + ).toBe(false); + }); +}); + +describe('installCodexAgents historical adoption (Group C)', () => { + test('live-shape 0/7 inventory: consent adopts every delivered role and refreshes the stale reviewer', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-liveshape-'); + const names = realRoleNames(); + const currentReviewer = realRoleBytes('genie-reviewer.toml'); + // The observed state: seven fanned files, NO inventory, and one older-but-genuine reviewer profile. + const staleReviewer = Buffer.concat([currentReviewer, Buffer.from('\n# older delivered profile\n')]); + for (const name of names) { + seedRoleFile(codexHome, name, name === 'genie-reviewer.toml' ? staleReviewer : realRoleBytes(name)); + } + // Two unrelated personal agents that must survive byte-, mode-, and timestamp-identically. + const personalPath = seedRoleFile(codexHome, 'genie-my-notes.toml', 'name = "my_notes"\n', 0o644); + const personalBytes = readFileSync(personalPath); + utimesSync(personalPath, new Date('2020-01-02T03:04:05Z'), new Date('2020-01-02T03:04:05Z')); + const personalMtime = lstatSync(personalPath).mtimeMs; + const nonRolePath = seedRoleFile(codexHome, 'genie-scratch.txt', 'scratch\n', 0o600); + + // The stale reviewer is a genuine historical profile, so inject its live identity into the allowlist. + const historical = new Set([...loadHistoricalRoleAgentTupleKeys(), liveTupleKey(codexHome, 'genie-reviewer.toml')]); + const result = installCodexAgents( + bundle, + codexHome, + {}, + { adoptHistorical: true, historicalTupleKeys: historical }, + ); + + expect(result.adoptedLegacy?.sort()).toEqual([...names]); + expect(result.installed).toBe(names.length); + expect(result.skippedUserOwned).toEqual([]); + // The reviewer was refreshed to the delivered profile; every role is now one managed surface. + expectSameBytes(readFileSync(join(codexHome, 'agents', 'genie-reviewer.toml')), currentReviewer); + const report = inspectCodexAgentOwnership(codexHome); + expect(report.expectedDeliveredTotal).toBe(EXPECTED_CODEX_ROLE_AGENT_TOTAL); + expect(report.reviewerDigest).toBe(CANONICAL_CODEX_REVIEWER_DIGEST); + expect(report.entries.filter((entry) => entry.state === 'managed').map((entry) => entry.name)).toEqual([...names]); + // Personal files untouched: bytes, permissions, and timestamps preserved. + expectSameBytes(readFileSync(personalPath), personalBytes); + expect(lstatSync(personalPath).mode & 0o7777).toBe(0o644); + expect(lstatSync(personalPath).mtimeMs).toBe(personalMtime); + expect(stateByName(codexHome).get('genie-my-notes.toml')).toBe('personal'); + expect(existsSync(nonRolePath)).toBe(true); + }); + + test('adoption of a byte-identical current profile records inventory without any refresh write', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-adopt-current-'); + seedRoleFile(codexHome, 'genie-scout.toml', realRoleBytes('genie-scout.toml')); + const before = lstatSync(join(codexHome, 'agents', 'genie-scout.toml')).mtimeMs; + // Only converge scout by pointing the bundle's other names away is unnecessary: absent targets install fresh. + const result = installCodexAgents(bundle, codexHome, {}, { adoptHistorical: true }); + expect(result.adoptedLegacy).toEqual(['genie-scout.toml']); + // scout adopted (no rewrite — mtime stable), the other six installed fresh. + expect(lstatSync(join(codexHome, 'agents', 'genie-scout.toml')).mtimeMs).toBe(before); + expect(stateByName(codexHome).get('genie-scout.toml')).toBe('managed'); + }); + + test('without adoptHistorical, an exact historical profile stays user-owned but reports adoptable-historical', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-noadopt-'); + seedRoleFile(codexHome, 'genie-reviewer.toml', realRoleBytes('genie-reviewer.toml')); + const result = installCodexAgents(bundle, codexHome); // default convergence: adoption OFF + expect(result.adoptedLegacy).toBeUndefined(); + expect(result.skippedUserOwned).toContain('genie-reviewer.toml'); + // Reporting never requires consent: the file is visibly adoptable, but untouched. + expect(stateByName(codexHome).get('genie-reviewer.toml')).toBe('adoptable-historical'); + expectSameBytes( + readFileSync(join(codexHome, 'agents', 'genie-reviewer.toml')), + realRoleBytes('genie-reviewer.toml'), + ); + }); + + test('adoptHistorical never adopts a lookalike, wrong-mode, symlink, or non-historical collision', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-collision-'); + // Sentinel lookalike: managed header but content Genie never shipped. + const lookalike = '# Managed by Genie. Remove with `genie uninstall`.\nname = "genie_reviewer"\n# hand-tuned\n'; + const reviewerPath = seedRoleFile(codexHome, 'genie-reviewer.toml', lookalike); + // Exact current profile but at the wrong mode — an identity mismatch, not an exact tuple. + const scoutPath = seedRoleFile(codexHome, 'genie-scout.toml', realRoleBytes('genie-scout.toml'), 0o600); + // A symlink at a role path is never followed or replaced. + const fixerPath = join(codexHome, 'agents', 'genie-fixer.toml'); + mkdirSync(dirname(fixerPath), { recursive: true }); + symlinkSync(join(codexHome, 'outside-target.toml'), fixerPath); + + const result = installCodexAgents(bundle, codexHome, {}, { adoptHistorical: true }); + + expect(result.adoptedLegacy).toBeUndefined(); + expect(result.skippedUserOwned.sort()).toEqual(['genie-fixer.toml', 'genie-reviewer.toml', 'genie-scout.toml']); + // Nothing was overwritten, adopted, or deleted. + expect(readFileSync(reviewerPath, 'utf8')).toBe(lookalike); + expectSameBytes(readFileSync(scoutPath), realRoleBytes('genie-scout.toml')); + expect(lstatSync(scoutPath).mode & 0o7777).toBe(0o600); + expect(lstatSync(fixerPath).isSymbolicLink()).toBe(true); + const states = stateByName(codexHome); + expect(states.get('genie-reviewer.toml')).toBe('collision'); + expect(states.get('genie-scout.toml')).toBe('collision'); + expect(states.get('genie-fixer.toml')).toBe('collision'); + }); + + test('repeated adoption convergence is idempotent and produces no duplicate surfaces or transactions', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-idem-'); + const names = realRoleNames(); + for (const name of names) seedRoleFile(codexHome, name, realRoleBytes(name)); + + const first = installCodexAgents(bundle, codexHome, {}, { adoptHistorical: true }); + expect(first.adoptedLegacy?.sort()).toEqual([...names]); + + const second = installCodexAgents(bundle, codexHome, {}, { adoptHistorical: true }); + // Already inventory-owned: nothing left to adopt, no writes, no duplicates. + expect(second).toEqual({ + installed: names.length, + skippedUserOwned: [], + keptModified: [], + removed: [], + backedUp: [], + }); + expect( + readdirSync(join(codexHome, 'agents')) + .filter((name) => name.endsWith('.toml')) + .sort(), + ).toEqual([...names]); + expect(() => recoverCodexAgentTransactions(codexHome)).not.toThrow(); + }); + + test('an interrupted adoption transaction recovers to the converged state and stays idempotent', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-interrupt-'); + const names = realRoleNames(); + const currentReviewer = realRoleBytes('genie-reviewer.toml'); + const staleReviewer = Buffer.concat([currentReviewer, Buffer.from('\n# older\n')]); + for (const name of names) { + seedRoleFile(codexHome, name, name === 'genie-reviewer.toml' ? staleReviewer : realRoleBytes(name)); + } + const historical = new Set([...loadHistoricalRoleAgentTupleKeys(), liveTupleKey(codexHome, 'genie-reviewer.toml')]); + + expect(() => + installCodexAgents( + bundle, + codexHome, + { + afterCommit() { + throw new Error('injected crash after durable commit'); + }, + }, + { adoptHistorical: true, historicalTupleKeys: historical }, + ), + ).toThrow('injected crash after durable commit'); + + // The commit was durable; recovery finishes cleanup and the reviewer is refreshed. + recoverCodexAgentTransactions(codexHome); + expectSameBytes(readFileSync(join(codexHome, 'agents', 'genie-reviewer.toml')), currentReviewer); + const report = inspectCodexAgentOwnership(codexHome); + expect(report.status).toBe('valid'); + expect(report.entries.filter((entry) => entry.state === 'managed').map((entry) => entry.name)).toEqual([...names]); + expect(installCodexAgents(bundle, codexHome, {}, { adoptHistorical: true }).adoptedLegacy).toBeUndefined(); + }); + + test('inspectCodexAgentOwnership distinguishes managed, stale, and absent states with delivered totals', () => { + // A bundle whose reviewer is an older profile so the managed install is clean-but-stale. + const staleBundle = makeRealCodexBundle(); + const stalePath = join(staleBundle, 'plugins', 'genie', 'codex-agents', 'genie-reviewer.toml'); + writeFileSync(stalePath, Buffer.concat([realRoleBytes('genie-reviewer.toml'), Buffer.from('# older\n')]), { + mode: 0o644, + }); + chmodSync(stalePath, 0o644); + const codexHome = canonicalTempDir('genie-codex-states-'); + installCodexAgents(staleBundle, codexHome); // fresh managed install of six current + one stale profile + rmSync(join(codexHome, 'agents', 'genie-scout.toml')); // recorded but now missing on disk + + const report = inspectCodexAgentOwnership(codexHome); + const states = new Map(report.entries.map((entry) => [entry.name, entry.state])); + expect(states.get('genie-reviewer.toml')).toBe('stale'); // managed-clean but not the delivered digest + expect(states.get('genie-scout.toml')).toBe('absent'); + expect(states.get('genie-fixer.toml')).toBe('managed'); + expect(report.expectedDeliveredTotal).toBe(EXPECTED_CODEX_ROLE_AGENT_TOTAL); + expect(report.reviewerDigest).toBe(CANONICAL_CODEX_REVIEWER_DIGEST); + }); +}); + +describe('convergeCodexPluginOnly role adoption + fallback (Group C)', () => { + test('an enabled plugin adopts delivered roles under committed codex consent', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-conv-enabled-'); + const genieHome = canonicalTempDir('genie-home-conv-enabled-'); + const names = realRoleNames(); + for (const name of names) seedRoleFile(codexHome, name, realRoleBytes(name)); + persistIntegrationConsent('codex', genieHome); + + const outcome = convergeCodexPluginOnly(realConvergeOptions({ codexHome, genieHome, bundleRoot: bundle })); + expect(outcome?.proof).not.toBeNull(); + expect(outcome?.agents.adoptedLegacy?.sort()).toEqual([...names]); + expect(stateByName(codexHome).size).toBe(names.length); + expect(inspectCodexAgentOwnership(codexHome).entries.every((entry) => entry.state === 'managed')).toBe(true); + }); + + test('convergence does NOT adopt without committed codex consent (a committed sibling client is not consent)', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-conv-noconsent-'); + const genieHome = canonicalTempDir('genie-home-conv-noconsent-'); + const names = realRoleNames(); + for (const name of names) seedRoleFile(codexHome, name, realRoleBytes(name)); + persistIntegrationConsent('claude', genieHome); + + const outcome = convergeCodexPluginOnly(realConvergeOptions({ codexHome, genieHome, bundleRoot: bundle })); + expect(outcome?.agents.adoptedLegacy).toBeUndefined(); + expect(outcome?.agents.skippedUserOwned.sort()).toEqual([...names]); + // Files remain exactly as fanned — visibly adoptable, never claimed. + expect(inspectCodexAgentOwnership(codexHome).entries.every((entry) => entry.state === 'adoptable-historical')).toBe( + true, + ); + }); + + test('a disabled plugin still installs the fallback role set (R3) and adopts under consent', () => { + const bundle = makeRealCodexBundle(); + const names = realRoleNames(); + const disabledDeps: Partial = { + converge: () => ({ ...healthyPluginResult(), preservedDisabled: true }), + probe: () => ({ ...healthyCodexProbe(), enabled: false, usable: false }), + }; + + // Fresh home: the disabled path restores the fallback roles with no health proof. + const freshHome = canonicalTempDir('genie-codex-conv-disabled-fresh-'); + const freshGenie = canonicalTempDir('genie-home-conv-disabled-fresh-'); + const fresh = convergeCodexPluginOnly( + realConvergeOptions({ codexHome: freshHome, genieHome: freshGenie, bundleRoot: bundle, deps: disabledDeps }), + ); + expect(fresh?.proof).toBeNull(); + expect(fresh?.agents.installed).toBe(names.length); + expect( + readdirSync(join(freshHome, 'agents')) + .filter((name) => name.endsWith('.toml')) + .sort(), + ).toEqual([...names]); + + // Legacy home under consent: the disabled path adopts the exact historical profiles too. + const legacyHome = canonicalTempDir('genie-codex-conv-disabled-legacy-'); + const legacyGenie = canonicalTempDir('genie-home-conv-disabled-legacy-'); + for (const name of names) seedRoleFile(legacyHome, name, realRoleBytes(name)); + persistIntegrationConsent('all', legacyGenie); + const legacy = convergeCodexPluginOnly( + realConvergeOptions({ codexHome: legacyHome, genieHome: legacyGenie, bundleRoot: bundle, deps: disabledDeps }), + ); + expect(legacy?.agents.adoptedLegacy?.sort()).toEqual([...names]); + }); + + test('an explicit deps override forces adoption independently of the consent file', () => { + const bundle = makeRealCodexBundle(); + const codexHome = canonicalTempDir('genie-codex-conv-override-'); + const genieHome = canonicalTempDir('genie-home-conv-override-'); + const names = realRoleNames(); + for (const name of names) seedRoleFile(codexHome, name, realRoleBytes(name)); + // No consent persisted, but the override unlocks adoption deterministically for tests. + const outcome = convergeCodexPluginOnly( + realConvergeOptions({ codexHome, genieHome, bundleRoot: bundle, deps: { adoptHistoricalRoleAgents: true } }), + ); + expect(outcome?.agents.adoptedLegacy?.sort()).toEqual([...names]); + }); +}); diff --git a/src/lib/runtime-integrations.ts b/src/lib/runtime-integrations.ts index d28171fab..171414d35 100644 --- a/src/lib/runtime-integrations.ts +++ b/src/lib/runtime-integrations.ts @@ -22,6 +22,7 @@ import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join, relative, resolve } from 'node:path'; import { Worker } from 'node:worker_threads'; +import historicalRoleAgentAllowlist from '../fixtures/codex-role-agent-allowlist.json'; import { CODEX_FALLBACK_RETIREMENT_ROOT, type CodexFallbackOwnership, @@ -210,6 +211,18 @@ export function readIntegrationConsent(genieHome = resolveGenieHome()): Integrat return readIntegrationConsentState(genieHome).selection; } +/** + * Whether committed Codex consent authorizes adopting an exact frozen historical + * role profile. Adoption is a privileged claim on a previously user-owned file, + * so it requires an EXPLICIT committed `codex`/`all` selection — never the legacy + * `auto` default and never an in-flight `pending` transition. This is the sole + * consent gate the role-agent convergence consults; an exact allowlist match is + * still additionally required before any file is adopted. + */ +export function codexRoleAdoptionAllowed(consent: IntegrationConsentState): boolean { + return consent.state === 'committed' && (consent.selection === 'codex' || consent.selection === 'all'); +} + /** Publish explicit maintenance consent before the first external setup mutation. */ export function beginIntegrationConsentTransition( selection: IntegrationSelection, @@ -652,6 +665,104 @@ const CODEX_AGENT_NAME_RE = /^genie-[A-Za-z0-9][A-Za-z0-9_-]*\.toml$/; const CODEX_AGENT_SENTINEL = '# Managed by Genie.'; const CODEX_AGENT_INVENTORY_MODE = 0o600; +/** + * The exact set of role agents the current Genie bundle fans into + * `~/.codex/agents/`, with each role's canonical current content digest and the + * physical mode every historical installer wrote (git-tracked 0644, preserved by + * the install tarball). These are the *current* delivered profiles: doctor reports + * this expected total and the reviewer digest, and the read-only ownership inspector + * uses them to distinguish an up-to-date managed role from a stale one. A + * parity test (`runtime-integrations.test.ts`) binds this map to the real + * `plugins/genie/codex-agents/*.toml` bytes so a role edit that forgets to update + * the frozen allowlist fails the gate rather than silently drifting. + */ +export const CANONICAL_CODEX_ROLE_AGENT_MODE = 0o644; + +export const CANONICAL_CODEX_ROLE_AGENT_DIGESTS: Readonly> = Object.freeze({ + 'genie-engineer-complex.toml': '62ecc570f1d77783511a9e7f0aa67b3a65d8bba292963409a02c7712c93ebc3b', + 'genie-engineer-standard.toml': 'dc746813b9b4b6aa984c17fa2fd75d4dbe34eba08494a174c0715da07aa9dd30', + 'genie-engineer-trivial.toml': '249deced5a02eb2cbe3303db566992d1336c75d853967f851bf1d0e85b6b0f47', + 'genie-final-gate.toml': '10ef070db8aace75bd80ef9e060a6ec601e3768f177fdd843f4db11035738f7e', + 'genie-fixer.toml': 'b3c1f407d4a3a2cfe204dee7b4a9c038e1a8f4644c446fcfa23f4a681bf0c7b3', + 'genie-reviewer.toml': 'c7008dcaa1e31b46e2bb05ca13afb2e918ee483422c84386a1c8997485bcfea7', + 'genie-scout.toml': '03a9fb3ca0e5f36c69c8f934d37adce1bae736e4c3895b144a0001ad31b1ba59', +}); + +/** The exact expected delivered role-agent filenames, name-sorted. */ +export const CANONICAL_CODEX_ROLE_AGENT_NAMES: readonly string[] = Object.freeze( + Object.keys(CANONICAL_CODEX_ROLE_AGENT_DIGESTS).sort(), +); + +/** The current reviewer profile digest doctor surfaces so an operator can spot a stale reviewer. */ +export const CANONICAL_CODEX_REVIEWER_DIGEST = CANONICAL_CODEX_ROLE_AGENT_DIGESTS['genie-reviewer.toml'] as string; + +/** The number of delivered role agents; doctor reports live coverage against this. */ +export const EXPECTED_CODEX_ROLE_AGENT_TOTAL = CANONICAL_CODEX_ROLE_AGENT_NAMES.length; + +/** + * One frozen historical profile: the exact identity (name + regular file type + + * mode + content digest) of a role-agent file a Genie release legitimately fanned + * into `~/.codex/agents/`. The allowlist is the union across releases (the reviewer + * carries several), so a legacy install whose reviewer is an older-but-genuine + * profile is still recognizable. Membership alone never authorizes a write — see + * {@link installCodexAgents}: adoption additionally requires committed Codex consent. + */ +export interface RoleAgentHistoricalProfile { + name: string; + type: 'regular'; + mode: number; + digest: string; +} + +/** Ownership proof key for a historical role profile: (name, mode, content digest). */ +export function codexRoleAgentTupleKey(name: string, mode: number, digest: string): string { + return `${name}\0${mode}\0${digest}`; +} + +function parseHistoricalRoleAgentMode(raw: unknown): number | null { + if (typeof raw !== 'string' || !/^0?[0-7]{3,4}$/.test(raw)) return null; + const mode = Number.parseInt(raw, 8); + return Number.isSafeInteger(mode) && mode >= 0 && mode <= 0o7777 ? mode : null; +} + +/** + * Load and validate the frozen historical role-agent allowlist. A malformed + * fixture is a build defect, not a runtime condition to tolerate, so this throws + * rather than silently degrading adoption into "recognize nothing". + */ +export function loadHistoricalRoleAgentProfiles(): RoleAgentHistoricalProfile[] { + const raw = historicalRoleAgentAllowlist as unknown; + if (!Array.isArray(raw)) throw new Error('codex role-agent allowlist must be a JSON array'); + const seen = new Set(); + return raw.map((entry, index) => { + const name = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'name') : undefined; + const type = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'type') : undefined; + const digest = typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'digest') : undefined; + const mode = parseHistoricalRoleAgentMode( + typeof entry === 'object' && entry !== null ? Reflect.get(entry, 'mode') : undefined, + ); + if ( + typeof name !== 'string' || + !CODEX_AGENT_NAME_RE.test(name) || + type !== 'regular' || + mode === null || + typeof digest !== 'string' || + !/^[a-f0-9]{64}$/.test(digest) + ) { + throw new Error(`codex role-agent allowlist entry ${index} is malformed`); + } + const key = codexRoleAgentTupleKey(name, mode, digest); + if (seen.has(key)) throw new Error(`codex role-agent allowlist entry ${index} is a duplicate tuple`); + seen.add(key); + return { name, type, mode, digest }; + }); +} + +/** The frozen allowlist as an ownership-key set: `name\0mode\0digest` for every legitimate historical profile. */ +export function loadHistoricalRoleAgentTupleKeys(): ReadonlySet { + return new Set(loadHistoricalRoleAgentProfiles().map((p) => codexRoleAgentTupleKey(p.name, p.mode, p.digest))); +} + export type RegularRoleFileIdentity = { kind: 'regular'; mode: number; digest: string }; type RoleFileIdentity = @@ -678,10 +789,28 @@ type ReadCodexAgentInventory = LegacyCodexAgentInventory | CodexAgentInventory; export type CodexAgentOwnership = 'absent' | 'user-owned' | 'managed-clean' | 'managed-modified'; +/** + * Human-facing delivery state of one role-agent file, distinct from the + * mutation-authority {@link CodexAgentOwnership}. This is the vocabulary doctor + * and the ownership report speak so an operator can tell a healthy managed role + * from one that is merely adoptable, stale, or a collision Genie will not touch: + * + * - `managed` — inventory-owned, clean, byte-identical to the current profile. + * - `stale` — inventory-owned and clean, but an older profile than the current delivery. + * - `adoptable-historical`— no inventory, yet an exact frozen historical profile; adoptable under committed consent. + * - `collision` — a genie-named file that looks managed (modified-managed, sentinel lookalike, + * symlink, or other non-regular) but is NOT an exact match; reported, never touched. + * - `personal` — a genie-named file with no Genie provenance signal; the user's own, left untouched. + * - `absent` — recorded in inventory but no longer on disk. + */ +export type CodexAgentDisplayState = 'managed' | 'stale' | 'adoptable-historical' | 'collision' | 'personal' | 'absent'; + export interface CodexAgentOwnershipEntry { name: string; path: string; ownership: CodexAgentOwnership; + /** Read-only delivery state for inventory/doctor output (managed/adoptable/collision/stale/personal). */ + state: CodexAgentDisplayState; /** Live physical identity when the entry is a regular file; drives identity-bound uninstall. */ identity?: RegularRoleFileIdentity; } @@ -690,6 +819,10 @@ export interface CodexAgentOwnershipReport { inventoryPath: string; status: 'missing' | 'valid' | 'corrupt'; entries: CodexAgentOwnershipEntry[]; + /** The exact number of role agents the current Genie bundle delivers (coverage denominator). */ + expectedDeliveredTotal: number; + /** The current canonical reviewer profile digest, surfaced so operators can spot a stale reviewer. */ + reviewerDigest: string; error?: string; } @@ -791,6 +924,61 @@ function classifyCodexAgentFile( return roleFileIdentityEquals(actual, safeLegacyIdentity) ? 'managed-clean' : 'managed-modified'; } +/** Read the head of a role file to detect the managed sentinel without a full re-hash. */ +function roleFileHasManagedSentinel(path: string): boolean { + try { + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) return false; + const fd = openSync(path, 'r'); + try { + const buffer = Buffer.allocUnsafe(CODEX_AGENT_SENTINEL.length); + const read = readSync(fd, buffer, 0, buffer.length, 0); + return buffer.subarray(0, read).toString('utf8') === CODEX_AGENT_SENTINEL; + } finally { + closeSync(fd); + } + } catch { + return false; + } +} + +/** + * Read-only display classification of one role file (never mutates, never reads + * inventory a second time). This is the reporting analog of the mutation-authority + * {@link classifyCodexAgentFile}: it maps an entry to the operator-facing + * {@link CodexAgentDisplayState}. Adoptability is a pure identity fact here — the + * committed-consent gate lives in {@link installCodexAgents}, so doctor can show + * "adoptable-historical" without implying anything was (or will be) written. + */ +function classifyCodexAgentDisplayState( + path: string, + name: string, + recorded: RecordedCodexAgent | undefined, + historical: ReadonlySet, + canonicalDigests: Readonly>, +): CodexAgentDisplayState { + const actual = physicalRoleFileIdentity(path); + if (actual.kind === 'absent') return 'absent'; + if (recorded !== undefined) { + const ownership = classifyCodexAgentFile(path, recorded); + if (ownership === 'absent') return 'absent'; + if (ownership === 'managed-modified') return 'collision'; + // managed-clean: current if it matches the delivered profile, otherwise stale. + const canonical = canonicalDigests[name]; + if (actual.kind === 'regular' && canonical !== undefined && actual.digest !== canonical) return 'stale'; + return 'managed'; + } + // No inventory record. Bytes never grant ownership, so the most a file can earn + // is "adoptable" (exact frozen historical identity) — everything else is left + // exactly where it is and only classified for reporting. + if (actual.kind === 'regular') { + if (historical.has(codexRoleAgentTupleKey(name, actual.mode, actual.digest))) return 'adoptable-historical'; + return roleFileHasManagedSentinel(path) ? 'collision' : 'personal'; + } + // Symlink / directory / other / unreadable at a role path: never safe to act on. + return 'collision'; +} + /** Shared digest-backed classifier for setup/update, doctor, and uninstall. */ export function inspectCodexAgentOwnership(codexHome = getCodexHome()): CodexAgentOwnershipReport { const state = readCodexAgentInventory(codexHome); @@ -799,10 +987,13 @@ export function inspectCodexAgentOwnership(codexHome = getCodexHome()): CodexAge if (existsSync(agentsDir)) { for (const name of readdirSync(agentsDir)) if (CODEX_AGENT_NAME_RE.test(name)) names.add(name); } + const historical = loadHistoricalRoleAgentTupleKeys(); return { inventoryPath: inventoryPath(codexHome), status: state.status, error: state.error, + expectedDeliveredTotal: EXPECTED_CODEX_ROLE_AGENT_TOTAL, + reviewerDigest: CANONICAL_CODEX_REVIEWER_DIGEST, entries: [...names].sort().map((name) => { const path = join(agentsDir, name); // Surface the same physical identity the classifier reads so the uninstall @@ -812,6 +1003,13 @@ export function inspectCodexAgentOwnership(codexHome = getCodexHome()): CodexAge name, path, ownership: classifyCodexAgentFile(path, state.inventory.files[name]), + state: classifyCodexAgentDisplayState( + path, + name, + state.inventory.files[name], + historical, + CANONICAL_CODEX_ROLE_AGENT_DIGESTS, + ), ...(identity.kind === 'regular' ? { identity } : {}), }; }), @@ -1605,6 +1803,49 @@ interface CodexAgentInstallPlan { writes: Map; removals: string[]; expected: Map; + /** Whether committed Codex consent has unlocked adoption of exact frozen historical profiles. */ + adopt: boolean; + /** Frozen historical allowlist keys (`name\0mode\0digest`) recognized for adoption. */ + historical: ReadonlySet; +} + +/** Role-agent convergence policy inputs, distinct from failure-injection {@link CodexAgentTransactionOptions}. */ +export interface CodexRoleAgentConvergenceOptions { + /** + * Adopt an exact frozen historical profile found on disk without inventory. + * Adoption is a privileged claim on a previously user-owned file, so it defaults + * OFF and callers pass `true` only after committed Codex consent + * ({@link codexRoleAdoptionAllowed}). An exact allowlist match is still required. + */ + adoptHistorical?: boolean; + /** Frozen historical allowlist keys; defaults to the shipped fixture. Injectable for deterministic tests. */ + historicalTupleKeys?: ReadonlySet; +} + +/** + * Resolve the ownership record convergence should treat a role file under. A live + * inventory record always wins. Otherwise, ONLY when committed Codex consent has + * unlocked adoption AND the file is an exact frozen historical profile (name + + * regular type + mode + digest), adopt it: record its current on-disk identity as + * if already managed so the ordinary convergence refreshes a stale profile to the + * delivered one and writes the inventory inside the same backup-first transaction. + * Bytes never grant ownership, so any other inventory-free file stays user-owned. + */ +function resolveCodexRoleAgentRecord( + targetPath: string, + name: string, + plan: CodexAgentInstallPlan, +): RecordedCodexAgent | undefined { + const recorded = plan.recorded.files[name]; + if (recorded !== undefined) return recorded; + if (!plan.adopt) return undefined; + const live = physicalRoleFileIdentity(targetPath); + if (live.kind !== 'regular' || !plan.historical.has(codexRoleAgentTupleKey(name, live.mode, live.digest))) { + return undefined; + } + plan.result.adoptedLegacy = plan.result.adoptedLegacy ?? []; + plan.result.adoptedLegacy.push(name); + return { identity: live }; } function collectCurrentCodexAgentPayloads( @@ -1624,7 +1865,7 @@ function collectCurrentCodexAgentPayloads( if (sourceIdentity.kind !== 'regular') { throw new Error(`Codex role-agent source is not a regular readable file: ${sourcePath}`); } - const recorded = plan.recorded.files[name]; + const recorded = resolveCodexRoleAgentRecord(targetPath, name, plan); const ownership = classifyCodexAgentFile(targetPath, recorded, sourceIdentity); if (ownership === 'user-owned') { // Bytes are not an ownership capability. An inventory-free file remains @@ -1681,6 +1922,7 @@ export function installCodexAgents( bundleRoot: string, codexHome = getCodexHome(), transactionOptions: CodexAgentTransactionOptions = {}, + convergence: CodexRoleAgentConvergenceOptions = {}, ): CodexAgentInstallResult { const source = join(bundleRoot, 'plugins', 'genie', 'codex-agents'); if (!existsSync(source)) throw new Error(`Codex agents are missing from bundle: ${source}`); @@ -1707,6 +1949,8 @@ export function installCodexAgents( writes: new Map(), removals: [], expected: new Map(), + adopt: convergence.adoptHistorical === true, + historical: convergence.historicalTupleKeys ?? loadHistoricalRoleAgentTupleKeys(), }; const sourceNames = readdirSync(source) .filter((name) => CODEX_AGENT_NAME_RE.test(name)) @@ -2918,10 +3162,25 @@ export interface CodexPluginOnlyDeps { /** Live Codex user-skills tier; defaults to resolveAgentsSkillsDir() (env-isolated in tests). */ fallbackSkillsDir?: string; probeCwd?: string; + /** + * Explicit adoption override for tests. When omitted, adoption is derived from + * committed Codex consent read from `options.genieHome` (adoption stays OFF when + * no genieHome is supplied). Only the DEFAULT role-agent installer honors this; + * an injected `installAgents` seam is called with its original 2-arg signature. + */ + adoptHistoricalRoleAgents?: boolean; + /** Consent reader seam; defaults to {@link readIntegrationConsentState}. */ + readConsentState?: (genieHome: string) => IntegrationConsentState; } export interface ConvergeCodexPluginOnlyOptions extends ConvergePluginOptions { deps?: CodexPluginOnlyDeps; + /** + * GENIE_HOME used to read committed Codex consent for role-agent adoption. When + * present and consent is a committed `codex`/`all` selection, exact frozen + * historical profiles are adopted during convergence; otherwise adoption is off. + */ + genieHome?: string; } export interface CodexPluginOnlyResult { @@ -2954,7 +3213,14 @@ export function convergeCodexPluginOnly(options: ConvergeCodexPluginOnlyOptions) const deps = options.deps ?? {}; const codexHome = options.codexHome ?? getCodexHome(); const fallbackSkillsDir = deps.fallbackSkillsDir ?? resolveAgentsSkillsDir(); - const installAgents = deps.installAgents ?? installCodexAgents; + // Adoption is off unless committed Codex consent explicitly unlocks it. An + // injected installAgents seam keeps its original 2-arg signature (ordering + // tests are unaffected); only the default installer receives the adoption flag. + const adopt = resolveConvergenceRoleAdoption(options, deps); + const runInstallAgents = (): CodexAgentInstallResult => + deps.installAgents + ? deps.installAgents(options.bundleRoot, codexHome) + : installCodexAgents(options.bundleRoot, codexHome, {}, { adoptHistorical: adopt }); const plugin = (deps.converge ?? convergeCodexPlugin)(options); if (plugin === null) return null; @@ -2972,7 +3238,10 @@ export function convergeCodexPluginOnly(options: ConvergeCodexPluginOnlyOptions) const snapshot = (deps.probe ?? probeCodexGeniePlugin)({ codexHome, cwd: deps.probeCwd ?? process.cwd() }); if (plugin.preservedDisabled === true) { - const agents = installAgents(options.bundleRoot, codexHome); + // R3: a deliberately disabled plugin still installs the fallback role TOMLs + // (before any health proof) — adoption of exact historical profiles applies + // here too, since role agents are CLI-owned and independent of plugin health. + const agents = runInstallAgents(); return { result: { ...plugin, snapshot }, proof: null, @@ -3023,7 +3292,7 @@ export function convergeCodexPluginOnly(options: ConvergeCodexPluginOnlyOptions) } } - const agents = installAgents(options.bundleRoot, codexHome); + const agents = runInstallAgents(); return { result: { ...plugin, snapshot, retiredFallbacks: retired, preservedCollisions, preservedUnrecognized }, proof, @@ -3034,6 +3303,18 @@ export function convergeCodexPluginOnly(options: ConvergeCodexPluginOnlyOptions) }; } +/** + * Resolve whether this convergence adopts exact frozen historical role profiles. + * An explicit deps override wins (tests); otherwise adoption is derived from + * committed Codex consent read from `genieHome`, and stays OFF when no genieHome + * is supplied so direct/unwired callers never silently claim user files. + */ +function resolveConvergenceRoleAdoption(options: ConvergeCodexPluginOnlyOptions, deps: CodexPluginOnlyDeps): boolean { + if (deps.adoptHistoricalRoleAgents !== undefined) return deps.adoptHistoricalRoleAgents; + if (options.genieHome === undefined) return false; + return codexRoleAdoptionAllowed((deps.readConsentState ?? readIntegrationConsentState)(options.genieHome)); +} + function emptyAgentInstallResult(): CodexAgentInstallResult { return { installed: 0, skippedUserOwned: [], keptModified: [], removed: [], backedUp: [] }; } @@ -3260,6 +3541,9 @@ function installCodexIntegration( codexHome, verifyCodexPayload, deps, + // stateDir is GENIE_HOME on every production install/setup path; role-agent + // adoption reads committed Codex consent from it (off unless committed codex/all). + genieHome: stateDir, }); if (outcome === null) throw new Error('Codex plugin convergence returned no result for explicit install'); const plugin = outcome.result;