fix: guard the Assistant config conversion and place agent permission fallbacks after catch-all rules (OM-179)

The Assistant v1-to-v2 conversion now skips the write when OpenCode returns no converted assistant agent for a customized v1 one, or when the converted config fails validation, and it shares a file lock with ensureAssistantMode so the two never overwrite each other.

A new agent wildcard permission rule is inserted after the last catch-all * * rule instead of before it, so the catch-all cannot override it. The event subscription also counts each received event as stream activity.
This commit is contained in:
Chris Scott committed 2026-11-05 16:16:49 -05:00
1 parent 84aa8dbeac
commit 64e87ba1ea
5 files changed
+158 -67

No files matched your search

+83 -65
View File
@@ -23,6 +23,7 @@ import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, V1_ENTITY_PATHS
import { readConfigValueAtPath, restoreOpenCodeConfigReferences } from './opencode-config-references'
import { readOpenCodeConfigDocuments } from './opencode-config-effective'
import { logger } from '../utils/logger'
import { withFileLock } from '../utils/atomic-json'
const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
@@ -1199,35 +1200,35 @@ export async function ensureAssistantMode(
await writeFileContent(agentsMdPath, agentsMdContent)
}
const existingOpenCodeJsonContent = opencodeJsonExists ? await readFileContent(opencodeJsonPath) : undefined
const parsedOpenCodeConfig = existingOpenCodeJsonContent === undefined
? undefined
: parseAssistantOpenCodeConfig(existingOpenCodeJsonContent)
const hasV1OpenCodeConfig = parsedOpenCodeConfig !== undefined && hasAssistantV1OpenCodeConfig(parsedOpenCodeConfig)
const existingOpenCodeConfig = parsedOpenCodeConfig as OpenCodeConfigInfo | undefined
const opencodeJsonUpdated = await withFileLock(opencodeJsonPath, async () => {
const existingOpenCodeJsonContent = opencodeJsonExists ? await readFileContent(opencodeJsonPath) : undefined
const parsedOpenCodeConfig = existingOpenCodeJsonContent === undefined
? undefined
: parseAssistantOpenCodeConfig(existingOpenCodeJsonContent)
const hasV1OpenCodeConfig = parsedOpenCodeConfig !== undefined && hasAssistantV1OpenCodeConfig(parsedOpenCodeConfig)
const existingOpenCodeConfig = parsedOpenCodeConfig as OpenCodeConfigInfo | undefined
let opencodeJsonUpdated = false
if (!opencodeJsonExists || overwriteOpenCodeConfig) {
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
opencodeJsonUpdated = true
} else if (!hasV1OpenCodeConfig) {
if (existingOpenCodeConfig !== undefined) {
const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingOpenCodeConfig)
? mergeAssistantOpenCodeConfig(existingOpenCodeConfig)
: existingOpenCodeConfig
const updatedConfig = assistantOpenCodeConfigHasGeneratedAgentPersona(repairedConfig)
? stripGeneratedAssistantAgentPersona(repairedConfig)
: repairedConfig
if (updatedConfig !== existingOpenCodeConfig) {
await writeFileContent(opencodeJsonPath, JSON.stringify(updatedConfig, null, 2))
opencodeJsonUpdated = true
}
} else {
if (!opencodeJsonExists || overwriteOpenCodeConfig) {
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
opencodeJsonUpdated = true
return true
}
}
if (hasV1OpenCodeConfig) return false
if (existingOpenCodeConfig === undefined) {
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
return true
}
const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingOpenCodeConfig)
? mergeAssistantOpenCodeConfig(existingOpenCodeConfig)
: existingOpenCodeConfig
const updatedConfig = assistantOpenCodeConfigHasGeneratedAgentPersona(repairedConfig)
? stripGeneratedAssistantAgentPersona(repairedConfig)
: repairedConfig
if (updatedConfig === existingOpenCodeConfig) return false
await writeFileContent(opencodeJsonPath, JSON.stringify(updatedConfig, null, 2))
return true
})
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR))
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_AGENTS_DIR))
@@ -1492,52 +1493,69 @@ function restoreAssistantAgentReferences(
* keeping comments and formatting. The file is left untouched when OpenCode is unreachable.
*/
export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Promise<boolean> {
const assistantDir = getAssistantModeDirectory()
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
try {
const assistantDir = getAssistantModeDirectory()
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
if (!await fileExists(opencodeJsonPath)) return false
const rawContent = await readFileContent(opencodeJsonPath)
const rawConfig = parseAssistantOpenCodeConfig(rawContent)
if (rawConfig === undefined || !hasAssistantV1OpenCodeConfig(rawConfig)) return false
const documents = await readOpenCodeConfigDocuments(api, assistantDir)
const documentInfo = documents.get(path.resolve(opencodeJsonPath))
if (documentInfo === undefined) return false
const v1Assistants = readConfigValueAtPath(rawConfig, ASSISTANT_V1_AGENT_PATH)
const v1AssistantAgent = isRecord(v1Assistants) ? v1Assistants[ASSISTANT_DEFAULT_AGENT_NAME] : undefined
const setOperations: OpenCodeConfigPathOperation[] = [
{
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
value: restoreAssistantAgentReferences(
resolveConvertedAssistantAgent(
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
v1AssistantAgent,
),
documentInfo,
rawConfig,
),
},
]
if (documentInfo.permissions !== undefined) {
setOperations.push({ path: ['permissions'], value: documentInfo.permissions })
}
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) {
updatedText = removeOpenCodeConfigProperty(updatedText, removalPath)
}
await writeFileContent(opencodeJsonPath, updatedText)
return true
return await withFileLock(opencodeJsonPath, () => convertAssistantOpenCodeConfigFile(api, assistantDir, opencodeJsonPath))
} catch (error) {
logger.warn('Skipped the Assistant OpenCode config conversion:', error)
return false
}
}
async function convertAssistantOpenCodeConfigFile(
api: OpenCodeApi,
assistantDir: string,
opencodeJsonPath: string,
): Promise<boolean> {
if (!await fileExists(opencodeJsonPath)) return false
const rawContent = await readFileContent(opencodeJsonPath)
const rawConfig = parseAssistantOpenCodeConfig(rawContent)
if (rawConfig === undefined || !hasAssistantV1OpenCodeConfig(rawConfig)) return false
const documents = await readOpenCodeConfigDocuments(api, assistantDir)
const documentInfo = documents.get(path.resolve(opencodeJsonPath))
if (documentInfo === undefined) return false
const v1Assistants = readConfigValueAtPath(rawConfig, ASSISTANT_V1_AGENT_PATH)
const v1AssistantAgent = isRecord(v1Assistants) ? v1Assistants[ASSISTANT_DEFAULT_AGENT_NAME] : undefined
if (isRecord(v1AssistantAgent) && documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] === undefined) {
logger.warn('Skipped the Assistant OpenCode config conversion: OpenCode returned no converted assistant agent')
return false
}
const setOperations: OpenCodeConfigPathOperation[] = [
{
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
value: restoreAssistantAgentReferences(
resolveConvertedAssistantAgent(
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
v1AssistantAgent,
),
documentInfo,
rawConfig,
),
},
]
if (documentInfo.permissions !== undefined) {
setOperations.push({ path: ['permissions'], value: documentInfo.permissions })
}
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) {
updatedText = removeOpenCodeConfigProperty(updatedText, removalPath)
}
const validation = validateOpenCodeConfig(parseJsonc(updatedText))
if (!validation.success) {
logger.warn('Skipped the Assistant OpenCode config conversion: the converted config is invalid', validation.issues)
return false
}
await writeFileContent(opencodeJsonPath, updatedText)
return true
}
export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeStatus> {
const assistantDir = getAssistantModeDirectory()
@@ -106,6 +106,7 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
})
for await (const event of stream) {
lastActivityAt = Date.now()
if (closed || token !== loopToken) break
if (!opened && event.type === 'server.connected') {
opened = true
@@ -951,6 +951,40 @@ describe('convertAssistantOpenCodeConfigToV2', () => {
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false)
expect(calls).toBe(0)
})
it('leaves a customized v1 assistant untouched when OpenCode returns no converted agent', async () => {
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
await writeFile(opencodeJsonPath, v1Config)
const api = createConfigApi((assistantDir) => [{
type: 'document',
path: path.join(assistantDir, 'opencode.json'),
info: { default_agent: 'assistant', permissions: convertedPermissions },
}])
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false)
expect(await readFile(opencodeJsonPath, 'utf8')).toBe(v1Config)
})
it('leaves the file untouched when the converted config is invalid', async () => {
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
await writeFile(opencodeJsonPath, v1Config)
const api = createConfigApi((assistantDir) => [{
type: 'document',
path: path.join(assistantDir, 'opencode.json'),
info: {
default_agent: 'assistant',
permissions: [{ action: 'shell', resource: '*', effect: 'sometimes' }],
agents: { assistant: { mode: 'primary', system: 'Converted prompt' } },
},
}])
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(false)
expect(await readFile(opencodeJsonPath, 'utf8')).toBe(v1Config)
})
})
describe('assistant-mode end-to-end', () => {
@@ -341,6 +341,39 @@ describe('AgentDialog', () => {
])
})
it('places a new wildcard rule after a catch-all rule and before later exceptions', async () => {
const onSubmit = vi.fn()
const user = userEvent.setup()
render(
<AgentDialog
open
onOpenChange={vi.fn()}
onSubmit={onSubmit}
editingAgent={{
name: 'reviewer',
agent: {
system: 'Review code',
permissions: [
{ action: '*', resource: '*', effect: 'allow' },
{ action: 'shell', resource: 'git status', effect: 'allow' },
],
},
}}
/>,
)
await user.click(screen.getByRole('combobox', { name: 'Shell' }))
await user.click(screen.getByRole('option', { name: 'Deny' }))
await user.click(screen.getByRole('button', { name: 'Update' }))
const agent = onSubmit.mock.calls[0][1]
expect(agent.permissions).toEqual([
{ action: '*', resource: '*', effect: 'allow' },
{ action: 'shell', resource: '*', effect: 'deny' },
{ action: 'shell', resource: 'git status', effect: 'allow' },
])
})
it('writes no permissions for a prompt-only save of an agent without permission rules', async () => {
const onSubmit = vi.fn()
const user = userEvent.setup()
@@ -48,7 +48,8 @@ const permissionEffect = (
* Applies the form effects to the managed wildcard rules in place, so the rule
* order OpenCode resolves with last-match-wins stays unchanged. An `inherit`
* effect removes the action's wildcard rules so the global permission applies;
* any other effect prepends a wildcard rule when the action has none yet.
* any other effect adds a wildcard rule when the action has none yet, placed
* after the last catch-all `* *` rule so that rule cannot override it.
*/
const withManagedPermissionEffects = (
permissions: OpenCodePermissionRule[] | undefined,
@@ -64,7 +65,11 @@ const withManagedPermissionEffects = (
const effect = effects[action]
return effect === 'inherit' || actionsWithWildcard.has(action) ? [] : [{ action, resource: '*', effect }]
})
return [...fallbacks, ...updated]
const fallbackIndex = updated.reduce(
(index, rule, currentIndex) => (rule.action === '*' && rule.resource === '*' ? currentIndex + 1 : index),
0,
)
return [...updated.slice(0, fallbackIndex), ...fallbacks, ...updated.slice(fallbackIndex)]
}
const optionalNumber = (value: string): number | undefined => {