section 7: Phase 7: Entity saves replace the matching v1 entry in the s

This commit is contained in:
Chris Scott committed 2026-11-02 10:32:28 -05:00
1 parent 48ca38c4e3
commit 19d4ae25b6
2 files changed
+364 -10

No files matched your search

+193 -10
View File
@@ -3,7 +3,7 @@ import { promises as fs } from 'fs'
import { readFile, readdir, rename, rm, stat } from 'fs/promises'
import path from 'path'
import { isDeepStrictEqual } from 'node:util'
import { applyEdits, modify, type JSONPath } from 'jsonc-parser'
import { applyEdits, findNodeAtLocation, modify, parseTree, type Edit, type JSONPath } from 'jsonc-parser'
import { getConfigPath, getOpenCodeConfigHome, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
import {
DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
@@ -148,11 +148,30 @@ interface AppliedOpenCodeConfigSourceFileState {
previousMode: number | undefined
}
interface OpenCodeConfigPathOperation {
export interface OpenCodeConfigPathOperation {
path: JSONPath
value: unknown
}
interface OpenCodeConfigV1EntityPath {
v2Path: string[]
v1Path: string[]
named: boolean
}
interface OpenCodeConfigV1EntityRemoval {
path: JSONPath
container?: JSONPath
}
const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [
{ v2Path: ['agents'], v1Path: ['agent'], named: true },
{ v2Path: ['commands'], v1Path: ['command'], named: true },
{ v2Path: ['providers'], v1Path: ['provider'], named: true },
{ v2Path: ['mcp', 'servers'], v1Path: ['mcp'], named: true },
{ v2Path: ['permissions'], v1Path: ['permission'], named: false },
]
interface OpenCodeConfigSnapshotEnvelopeSource {
name: OpenCodeConfigRestorableSourceName
rawContent: string
@@ -187,18 +206,40 @@ function hasOwn(object: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(object, key)
}
function hasOpenCodeConfigPath(content: Record<string, unknown>, jsonPath: JSONPath): boolean {
function readOpenCodeConfigPath(
content: Record<string, unknown>,
jsonPath: JSONPath,
): { found: boolean; value: unknown } {
let current: unknown = content
for (const segment of jsonPath) {
if (typeof segment === 'number') {
if (!Array.isArray(current) || segment < 0 || segment >= current.length) return false
if (!Array.isArray(current) || segment < 0 || segment >= current.length) {
return { found: false, value: undefined }
}
current = current[segment]
continue
}
if (!isPlainObject(current) || !hasOwn(current, segment)) return false
if (!isPlainObject(current) || !hasOwn(current, segment)) return { found: false, value: undefined }
current = current[segment]
}
return true
return { found: true, value: current }
}
function hasOpenCodeConfigPath(content: Record<string, unknown>, jsonPath: JSONPath): boolean {
return readOpenCodeConfigPath(content, jsonPath).found
}
function readPatchedOpenCodeConfigPath(
patch: Record<string, unknown>,
jsonPath: readonly string[],
): { found: boolean; value: unknown } {
let current: unknown = patch
for (const segment of jsonPath) {
if (current === null) return { found: true, value: null }
if (!isPlainObject(current) || !hasOwn(current, segment)) return { found: false, value: undefined }
current = current[segment]
}
return { found: true, value: current }
}
function defineOwnConfigValue(target: Record<string, unknown>, key: string, value: unknown): void {
@@ -459,7 +500,136 @@ function collectOpenCodeConfigPathOperations(
return operations
}
function applyOpenCodeConfigPathOperations(
function collectOpenCodeConfigV1EntityRemovals(
patch: Record<string, unknown>,
): OpenCodeConfigV1EntityRemoval[] {
const removals: OpenCodeConfigV1EntityRemoval[] = []
for (const mapping of V1_ENTITY_PATHS) {
const patched = readPatchedOpenCodeConfigPath(patch, mapping.v2Path)
if (!patched.found) continue
if (!mapping.named || patched.value === null) {
removals.push({ path: mapping.v1Path })
continue
}
if (!isPlainObject(patched.value)) continue
for (const name of Object.keys(patched.value)) {
removals.push({ path: [...mapping.v1Path, name], container: mapping.v1Path })
}
}
return removals
}
function findOpenCodeConfigSeparatorComma(rawContent: string, start: number, end: number): number {
let index = start
while (index < end) {
if (rawContent.startsWith('//', index)) {
const newline = rawContent.indexOf('\n', index)
if (newline < 0 || newline >= end) return -1
index = newline + 1
continue
}
if (rawContent.startsWith('/*', index)) {
const close = rawContent.indexOf('*/', index + 2)
if (close < 0 || close >= end) return -1
index = close + 2
continue
}
if (rawContent[index] === ',') return index
index += 1
}
return -1
}
function findOpenCodeConfigLineEnd(rawContent: string, offset: number): number | null {
let index = offset
while (index < rawContent.length && (rawContent[index] === ' ' || rawContent[index] === '\t')) {
index += 1
}
if (rawContent.startsWith('\r\n', index)) return index + 2
if (rawContent[index] === '\n') return index + 1
return null
}
function buildOpenCodeConfigCommentPreservingRemovalEdits(
rawContent: string,
jsonPath: JSONPath,
): Edit[] | null {
const root = parseTree(rawContent)
const node = root ? findNodeAtLocation(root, jsonPath) : undefined
const property = node?.parent
const container = property?.parent
if (!property || !container?.children) return null
const index = container.children.indexOf(property)
const previous = index > 0 ? container.children[index - 1] : undefined
const next = container.children[index + 1]
const propertyEnd = property.offset + property.length
const lineStart = rawContent.lastIndexOf('\n', property.offset - 1) + 1
const aloneOnLine = rawContent.slice(lineStart, property.offset).trim() === ''
const removeStart = aloneOnLine ? lineStart : property.offset
if (next) {
const separatorOffset = findOpenCodeConfigSeparatorComma(rawContent, propertyEnd, next.offset)
if (separatorOffset < 0) return null
if (rawContent.slice(propertyEnd, separatorOffset).includes('/')) {
return [
{ offset: removeStart, length: propertyEnd - removeStart, content: '' },
{ offset: separatorOffset, length: 1, content: '' },
]
}
const lineEnd = aloneOnLine ? findOpenCodeConfigLineEnd(rawContent, separatorOffset + 1) : null
const removeEnd = lineEnd ?? separatorOffset + 1
return [{ offset: removeStart, length: removeEnd - removeStart, content: '' }]
}
const edits: Edit[] = []
if (previous) {
const separatorOffset = findOpenCodeConfigSeparatorComma(
rawContent,
previous.offset + previous.length,
property.offset,
)
if (separatorOffset < 0) return null
edits.push({ offset: separatorOffset, length: 1, content: '' })
}
const lineEnd = aloneOnLine ? findOpenCodeConfigLineEnd(rawContent, propertyEnd) : null
const removeEnd = lineEnd ?? propertyEnd
edits.push({ offset: removeStart, length: removeEnd - removeStart, content: '' })
return edits
}
function removeOpenCodeConfigProperty(rawContent: string, jsonPath: JSONPath): string {
const edits = buildOpenCodeConfigCommentPreservingRemovalEdits(rawContent, jsonPath)
if (!edits) return rawContent
return applyEdits(rawContent, edits)
}
function collectEmptyOpenCodeConfigContainers(
rawContent: string,
removals: OpenCodeConfigV1EntityRemoval[],
): JSONPath[] {
const parsed = parseJsonc(rawContent)
if (!isPlainObject(parsed)) return []
const containers: JSONPath[] = []
const visited = new Set<string>()
for (const removal of removals) {
if (!removal.container) continue
const key = removal.container.join('\0')
if (visited.has(key)) continue
visited.add(key)
const container = readOpenCodeConfigPath(parsed, removal.container)
if (isPlainObject(container.value) && Object.keys(container.value).length === 0) {
containers.push(removal.container)
}
}
return containers
}
/**
* Applies path edits to raw JSONC config text, preserving comments and formatting.
*/
export function applyOpenCodeConfigEdits(
rawContent: string,
operations: OpenCodeConfigPathOperation[],
): string {
@@ -532,14 +702,27 @@ export async function updateOpenCodeConfigFile(
const mode = options.mode ?? 'replace'
const operations = collectOpenCodeConfigPathOperations(content, snapshot.content, mode)
const v1EntityRemovals = mode === 'merge' ? collectOpenCodeConfigV1EntityRemovals(content) : []
assertValidOpenCodeConfig(
mode === 'merge' ? mergeOpenCodeConfigValues(snapshot.content, content, { deleteNullValues: true }) : content,
)
const originalText = targetSource?.rawContent ?? '{}\n'
assertNoShadowedOpenCodeConfigRemovals(operations, targetSource, snapshot.sources, targetName)
const updatedText = applyOpenCodeConfigPathOperations(originalText, operations)
assertNoShadowedOpenCodeConfigRemovals(
[...operations, ...v1EntityRemovals.map((removal) => ({ path: removal.path, value: undefined }))],
targetSource,
snapshot.sources,
targetName,
)
let updatedText = applyOpenCodeConfigEdits(originalText, operations)
for (const removal of v1EntityRemovals) {
updatedText = removeOpenCodeConfigProperty(updatedText, removal.path)
}
for (const container of collectEmptyOpenCodeConfigContainers(updatedText, v1EntityRemovals)) {
updatedText = removeOpenCodeConfigProperty(updatedText, container)
}
if (updatedText !== originalText) {
assertValidOpenCodeConfig(parseJsonc(updatedText))
@@ -761,7 +944,7 @@ export async function foldLegacyConfigJsonSource(): Promise<boolean> {
const operations = collectOpenCodeConfigPathOperations(legacyContent, lowestPrecedenceSource.content, 'replace')
.filter((operation) => operation.value !== undefined && !hasOpenCodeConfigPath(lowestPrecedenceSource.content, operation.path))
if (operations.length > 0) {
const updatedText = applyOpenCodeConfigPathOperations(lowestPrecedenceSource.rawContent, operations)
const updatedText = applyOpenCodeConfigEdits(lowestPrecedenceSource.rawContent, operations)
assertValidOpenCodeConfig(parseJsonc(updatedText))
await writeFileAtomic(lowestPrecedenceSource.path, updatedText, { mode: await existingFileMode(lowestPrecedenceSource.path) })
}
@@ -790,6 +790,177 @@ describe('opencode-config-file', () => {
await expect(deleteOpenCodeConfigFile()).resolves.toBe(false)
})
describe('v1 entity replacement', () => {
it.each([
{
label: 'agents',
v1Content: { agent: { reviewer: { description: 'Legacy reviewer' } } },
patch: { agents: { reviewer: { description: 'New reviewer' } } },
expected: { agents: { reviewer: { description: 'New reviewer' } } },
},
{
label: 'commands',
v1Content: { command: { build: { template: 'legacy template' } } },
patch: { commands: { build: { template: 'new template' } } },
expected: { commands: { build: { template: 'new template' } } },
},
{
label: 'providers',
v1Content: { provider: { example: { name: 'Legacy provider' } } },
patch: { providers: { example: { name: 'Example provider' } } },
expected: { providers: { example: { name: 'Example provider' } } },
},
{
label: 'mcp servers',
v1Content: { mcp: { linear: { type: 'remote', url: 'https://legacy.example.com' } } },
patch: { mcp: { servers: { linear: { type: 'remote', url: 'https://current.example.com' } } } },
expected: { mcp: { servers: { linear: { type: 'remote', url: 'https://current.example.com' } } } },
},
{
label: 'permissions',
v1Content: { permission: { edit: 'deny' } },
patch: { permissions: [{ action: 'edit', resource: '*', effect: 'deny' }] },
expected: { permissions: [{ action: 'edit', resource: '*', effect: 'deny' }] },
},
])('replaces the v1 $label entry when saving its v2 entity', async ({ v1Content, patch, expected }) => {
const raw = `{\n // keep this comment\n ${JSON.stringify(v1Content).slice(1, -1)}\n}\n`
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
const updated = await updateOpenCodeConfigFile(patch, { mode: 'merge' })
expect(updated.content).toEqual(expected)
const onDisk = await readFile(sourcePath('opencode.json'), 'utf8')
expect(onDisk).toContain('// keep this comment')
})
it('keeps a comment that leads the sibling after the removed v1 container', async () => {
const raw = '{\n // lead\n "agent": {"reviewer":{"description":"Legacy reviewer"}},\n // theme comment\n "theme": "dark"\n}\n'
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
const updated = await updateOpenCodeConfigFile(
{ agents: { reviewer: { description: 'New reviewer' } } },
{ mode: 'merge' },
)
expect(updated.content).toEqual({
theme: 'dark',
agents: { reviewer: { description: 'New reviewer' } },
})
const onDisk = await readFile(sourcePath('opencode.json'), 'utf8')
expect(onDisk).toContain('// lead')
expect(onDisk).toContain('// theme comment')
expect(onDisk).not.toContain('"agent"')
})
it('keeps the following sibling comment when the v1 container has no leading comment', async () => {
const raw = '{\n "agent": {"reviewer":{"description":"Legacy reviewer"}},\n // theme comment\n "theme": "dark"\n}\n'
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
await updateOpenCodeConfigFile({ agents: { reviewer: { description: 'New reviewer' } } }, { mode: 'merge' })
const onDisk = await readFile(sourcePath('opencode.json'), 'utf8')
expect(onDisk).toContain('// theme comment')
expect(onDisk).not.toContain('"agent"')
})
it('keeps a comment that leads the next sibling inside the v1 container', async () => {
const raw = [
'{',
' "agent": {',
' "reviewer": { "description": "Legacy reviewer" }, // keep',
' "keeper": { "description": "Keeper" }',
' }',
'}',
].join('\n')
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
const updated = await updateOpenCodeConfigFile(
{ agents: { reviewer: { description: 'New reviewer' } } },
{ mode: 'merge' },
)
expect(updated.content).toEqual({
agent: { keeper: { description: 'Keeper' } },
agents: { reviewer: { description: 'New reviewer' } },
})
const onDisk = await readFile(sourcePath('opencode.json'), 'utf8')
expect(onDisk).toContain('// keep')
expect(onDisk).not.toContain('Legacy reviewer')
})
it('removes both definitions when the v2 entity is patched with null', async () => {
const raw = JSON.stringify({
agent: { reviewer: { description: 'Legacy reviewer' } },
agents: { reviewer: { description: 'Current reviewer' } },
}, null, 2)
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
const updated = await updateOpenCodeConfigFile({ agents: { reviewer: null } }, { mode: 'merge' })
expect(updated.content).toEqual({ agents: {} })
const onDisk = JSON.parse(await readFile(sourcePath('opencode.json'), 'utf8')) as Record<string, unknown>
expect(onDisk).toEqual({ agents: {} })
expect(onDisk).not.toHaveProperty('agent')
})
it('keeps the v2 definition when the same entity exists in both shapes', async () => {
const raw = JSON.stringify({
agent: { reviewer: { description: 'Legacy reviewer' } },
agents: { reviewer: { description: 'Current reviewer' } },
}, null, 2)
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
const updated = await updateOpenCodeConfigFile(
{ agents: { reviewer: { description: 'Current reviewer' } } },
{ mode: 'merge' },
)
expect(updated.content).toEqual({ agents: { reviewer: { description: 'Current reviewer' } } })
const onDisk = await readFile(sourcePath('opencode.json'), 'utf8')
expect(JSON.parse(onDisk)).toEqual({ agents: { reviewer: { description: 'Current reviewer' } } })
expect(onDisk).not.toContain('Legacy reviewer')
})
it('keeps other v1 entities in the container', async () => {
const raw = JSON.stringify({
agent: {
reviewer: { description: 'Legacy reviewer' },
keeper: { description: 'Keeper' },
},
}, null, 2)
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
const updated = await updateOpenCodeConfigFile(
{ agents: { reviewer: { description: 'New reviewer' } } },
{ mode: 'merge' },
)
expect(updated.content).toEqual({
agent: { keeper: { description: 'Keeper' } },
agents: { reviewer: { description: 'New reviewer' } },
})
const onDisk = JSON.parse(await readFile(sourcePath('opencode.json'), 'utf8')) as Record<string, unknown>
expect(onDisk).toHaveProperty('agent.keeper')
})
it('rejects the save when the v1 entity only a lower-priority source defines', async () => {
const lower = JSON.stringify({ agent: { reviewer: { description: 'Legacy reviewer' } } })
const target = '{"theme":"dark"}'
await writeFile(sourcePath('opencode.json'), lower, 'utf8')
await writeFile(sourcePath('opencode.jsonc'), target, 'utf8')
const error = await updateOpenCodeConfigFile(
{ agents: { reviewer: { description: 'New reviewer' } } },
{ mode: 'merge' },
).catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(OpenCodeConfigShadowedRemovalError)
expect((error as OpenCodeConfigShadowedRemovalError).paths).toEqual(['agent.reviewer'])
expect((error as OpenCodeConfigShadowedRemovalError).sources).toEqual(['opencode.json'])
await expect(readFile(sourcePath('opencode.jsonc'), 'utf8')).resolves.toBe(target)
})
})
describe('restoreLegacyOpenCodeConfigBackup', () => {
const backupPath = (configPath: string) => `${configPath}.ocm-sandbox-backup`