Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 190 additions & 8 deletions pkgs/opencode-config-normalize/normalize.sh
Original file line number Diff line number Diff line change
Expand Up @@ -322,11 +322,198 @@ def delete_top_level_entry(text, key):
k = comment_at


def line_comment_at_end(fragment):
# True when fragment ends inside a // line comment: a joining
# comma appended after it would be swallowed by the comment.
# String- and block-comment-aware so // inside a string value or a
# /* */ comment does not misfire (#3179). The whole fragment is
# scanned while tracking block-comment state (Codex P2 on PR
# #4644): a multiline block comment whose final line holds a URL
# (e.g. "a" /* note\nhttps://example.com */) must not have its
# // mistaken for a live line comment.
in_str = False
in_block = False
in_line = False
i, n = 0, len(fragment)
while i < n:
c = fragment[i]
if in_line:
if c == '\n':
in_line = False
i += 1
continue
if in_block:
if c == '*' and fragment[i + 1:i + 2] == '/':
in_block = False
i += 2
continue
i += 1
continue
if in_str:
if c == '\\' and i + 1 < n:
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
elif c == '/' and fragment[i + 1:i + 2] == '/':
in_line = True
i += 2
continue
elif c == '/' and fragment[i + 1:i + 2] == '*':
in_block = True
i += 2
continue
i += 1
if in_block:
return True # unterminated block comment: fail closed
return in_line


def strip_trailing_element_comma(fragment):
# Remove the trailing element-separator comma (the one before the
# closing bracket), skipping over trailing comments, so a legacy
# array like ["a", /* keep */] splices without a doubled comma
# (Codex P2 on PR #4644: the naive endswith(',') check missed the
# comma hidden behind the block comment and the merge wrongly
# failed closed on input the old code repaired). Only a comma
# followed solely by whitespace/comments is removed; a comma inside
# a string, a comment, or a nested array/object is never touched.
# Returns the fragment unchanged when there is no trailing comma.
last_comma = -1
i = 0
n = len(fragment)
depth = 0
in_str = False
in_line = False
in_block = False
while i < n:
c = fragment[i]
if in_line:
if c == '\n':
in_line = False
i += 1
continue
if in_block:
if c == '*' and fragment[i + 1:i + 2] == '/':
in_block = False
i += 2
continue
i += 1
continue
if in_str:
if c == '\\' and i + 1 < n:
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
elif c == '/' and fragment[i + 1:i + 2] == '/':
in_line = True
i += 2
continue
elif c == '/' and fragment[i + 1:i + 2] == '*':
in_block = True
i += 2
continue
elif c in '[{':
depth += 1
elif c in ']}':
depth -= 1
elif c == ',' and depth == 0:
last_comma = i
i += 1
if last_comma < 0:
return fragment
tail = fragment[last_comma + 1:]
k = 0
m = len(tail)
while k < m:
if tail[k] in ' \t\r\n':
k += 1
continue
if tail.startswith('//', k):
nl = tail.find('\n', k)
k = m if nl < 0 else nl + 1
continue
if tail.startswith('/*', k):
end = tail.find('*/', k + 2)
if end < 0:
return fragment # unterminated: leave alone, fail closed
k = end + 2
continue
return fragment # real content after the comma: not trailing
return fragment[:last_comma] + tail


def splice_plugin_merge(text, legacy_has_elements=True):
# Both-present plugin+plugins merge (#4639) as a textual element
# splice: the legacy elements move into the `plugins` array (legacy
# first, native appended — the fork's encoded.plugins order) and the
# v1 `plugin` entry is dropped, all without re-serialising, so
# comments inside both arrays survive byte-identical. Returns the new
# text, or None when the splice cannot be done comment-safely (e.g. a
# // line comment trailing the last legacy element would swallow the
# joining comma); the caller then exits 1 with the file
# byte-identical — a repair tool must never be a data-loss path
# (#2364). legacy_has_elements reports whether the legacy array
# holds actual elements (vs comments only): a comment-only legacy
# array needs no joining comma, and emitting one would be a leading
# syntax error (Codex P2 on PR #4644: [/* disabled */] + ["b"]
# wrongly failed closed on input the old code repaired).
legacy_span = find_value_span(text, 'plugin')
native_span = find_value_span(text, 'plugins')
if legacy_span is None or native_span is None:
return None
lvs, lve = legacy_span
nvs, nve = native_span
legacy_text = text[lvs:lve]
native_text = text[nvs:nve]
if not (legacy_text.startswith('[') and legacy_text.endswith(']')):
return None
if not (native_text.startswith('[') and native_text.endswith(']')):
return None
legacy_inner = legacy_text[1:-1].strip()
native_inner = native_text[1:-1].strip()
if legacy_inner and native_inner:
if legacy_has_elements:
core = strip_trailing_element_comma(legacy_inner).rstrip()
if line_comment_at_end(core):
return None
inner = core + ',\n' + native_inner
else:
inner = legacy_inner + '\n' + native_inner
elif legacy_inner:
inner = legacy_inner
else:
inner = None
if inner is None:
merged = native_text # nothing to move: keep native bytes verbatim
elif line_comment_at_end(inner):
# A // comment runs to end of line: the closing bracket goes on
# its own line so it is not swallowed by the comment.
merged = '[' + inner + '\n]'
else:
merged = '[' + inner + ']'
text = text[:nvs] + merged + text[nve:]
return delete_top_level_entry(text, 'plugin')


# plugin -> plugins. When `plugins` is absent this is a bare key rename
# (array contents are byte-preserved, comments included). When both
# spellings are present, merge the way the fork does — legacy entries
# first, native entries appended (normalize.ts: encoded.plugins =
# [...legacyPlugins, ...nativePlugins]) — then drop the v1 entry. A raw
# [...legacyPlugins, ...nativePlugins]) — then drop the v1 entry. The
# merge is a textual element splice, not a re-serialise, so comments
# inside both arrays survive; shapes that cannot be spliced
# comment-safely fail closed with exit 1 and the file byte-identical
# (#4639). A raw
# text search can hit "plugin": inside an earlier comment and leave the
# live key unrepaired (PR #4312 review), so all splices go through the
# string/comment-aware locators, and any splice that cannot be done
Expand All @@ -344,14 +531,9 @@ if 'plugin' in doc:
native = doc.get('plugins')
if not isinstance(legacy, list) or not isinstance(native, list):
sys.exit(1) # unmergeable shapes: leave the file untouched
span = find_value_span(out, 'plugins')
if span is None:
sys.exit(1)
vs, ve = span
out = out[:vs] + json.dumps(legacy + native) + out[ve:]
out = delete_top_level_entry(out, 'plugin')
out = splice_plugin_merge(out, bool(legacy))
if out is None:
sys.exit(1)
sys.exit(1) # not spliceable comment-safely: fail closed
changed = True

# agent -> agents: fold the v1 `agent` map into `agents` (existing
Expand Down
96 changes: 96 additions & 0 deletions pkgs/opencode-config-normalize/normalize_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,102 @@ EOF
check duplicate-last "$tmp/duplicate-last.fixture" \
'{"$schema":"https://opencode.ai/config.json","agents":{"build":{"model":"anthropic/claude-sonnet-4-5"}}}' 0

# Case 19: plugin + plugins both present with comments inside BOTH
# arrays (#4639) — the merge is a textual element splice, so every
# comment survives byte-identical instead of the arrays being
# re-serialised.
cat >"$tmp/plugins-merge-comments.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json",
// file-level note
"plugin": [
/* legacy note */
"opencode-plugin-a"
],
"plugins": [
// native note
"opencode-plugin-b"
// trailing native
]
}
EOF
check plugins-merge-comments "$tmp/plugins-merge-comments.fixture" \
'{"$schema":"https://opencode.ai/config.json","plugins":["opencode-plugin-a","opencode-plugin-b"]}' 0
for needle in '/* legacy note */' '// native note' '// trailing native' '// file-level note'; do
grep -qF "$needle" "$tmp/plugins-merge-comments.jsonc" || {
echo "FAIL plugins-merge-comments: lost comment: $needle"
failures=$((failures + 1))
}
done

# Case 20: a // line comment trailing the last legacy element (#4639
# boundary) — the joining comma would be swallowed by the comment, so
# the merge fails closed: exit 1 with the file byte-identical.
cat >"$tmp/plugins-merge-trailing-comment.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json",
"plugin": [
"opencode-plugin-a" // trailing legacy note
],
"plugins": [
"opencode-plugin-b"
]
}
EOF
check plugins-merge-trailing-comment "$tmp/plugins-merge-trailing-comment.fixture" '' 1

# Case 21 (Codex P2 on PR #4644): a trailing comma before a trailing
# block comment is still the legacy array's element separator. Remove
# that comma while preserving the comment, then perform the merge.
cat >"$tmp/plugins-merge-trailing-block-comment.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["opencode-plugin-a", /* keep trailing block */],
"plugins": ["opencode-plugin-b"]
}
EOF
check plugins-merge-trailing-block-comment "$tmp/plugins-merge-trailing-block-comment.fixture" \
'{"$schema":"https://opencode.ai/config.json","plugins":["opencode-plugin-a","opencode-plugin-b"]}' 0
grep -qF '/* keep trailing block */' "$tmp/plugins-merge-trailing-block-comment.jsonc" || {
echo "FAIL plugins-merge-trailing-block-comment: lost trailing block comment"
failures=$((failures + 1))
}

# Case 22 (Codex P2 on PR #4644): legacy array holds only a comment,
# e.g. [/* disabled */] — no joining comma is emitted, so the merge
# succeeds and the comment survives instead of failing closed.
cat >"$tmp/plugins-merge-comment-only-legacy.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json",
"plugin": [/* disabled */],
"plugins": ["opencode-plugin-b"]
}
EOF
check plugins-merge-comment-only-legacy "$tmp/plugins-merge-comment-only-legacy.fixture" \
'{"$schema":"https://opencode.ai/config.json","plugins":["opencode-plugin-b"]}' 0
grep -qF '/* disabled */' "$tmp/plugins-merge-comment-only-legacy.jsonc" || {
echo "FAIL plugins-merge-comment-only-legacy: lost legacy comment"
failures=$((failures + 1))
}

# Case 23 (Codex P2 on PR #4644): multiline block comment with a URL on
# its final line inside the legacy array — the // in the URL is inside
# /* */, not a live line comment, so the merge succeeds.
cat >"$tmp/plugins-merge-url-comment.fixture" <<'EOF'
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["opencode-plugin-a" /* note
https://example.com/docs */],
"plugins": ["opencode-plugin-b"]
}
EOF
check plugins-merge-url-comment "$tmp/plugins-merge-url-comment.fixture" \
'{"$schema":"https://opencode.ai/config.json","plugins":["opencode-plugin-a","opencode-plugin-b"]}' 0
grep -qF 'https://example.com/docs */' "$tmp/plugins-merge-url-comment.jsonc" || {
echo "FAIL plugins-merge-url-comment: lost block comment"
failures=$((failures + 1))
}

if [ "$failures" -ne 0 ]; then
echo "normalize_test: $failures failure(s)"
exit 1
Expand Down
Loading