iOfficeAI/OfficeCLI · error · ArgumentException

Malformed path segment '{part}'. Bracket '[' is not closed.

Error message

Malformed path segment '{part}'. Bracket '[' is not closed. Expected format: name[index] or name[@attr=value].

What it means

Thrown by the GenericXmlQuery path parser when a path segment contains a '[' but no matching ']'. This guard (BUG-R36-01 fix) prevents a negative-length range crash that previously occurred when slicing part[(bracketIdx+1)..^1] on an unclosed bracket like 'slide['.

Source

Thrown at src/officecli/Core/GenericXmlQuery.cs:251

    /// <summary>
    /// Parse a path string like "a/b[1]/c[2]" into segments of (Name, Index).
    /// Index is 1-based. If no index specified, Index is null.
    /// </summary>
    public static List<(string Name, int? Index)> ParsePathSegments(string path)
    {
        var segments = new List<(string Name, int? Index)>();
        foreach (var part in path.Trim('/').Split('/'))
        {
            if (string.IsNullOrEmpty(part)) continue;
            var bracketIdx = part.IndexOf('[');
            if (bracketIdx >= 0)
            {
                // BUG-R36-01 fix: when ']' is missing (e.g. "slide[") the expression
                // part[(bracketIdx+1)..^1] produces a negative-length range crash.
                // Detect and reject unclosed brackets with a clean ArgumentException.
                var closingIdx = part.IndexOf(']', bracketIdx + 1);
                if (closingIdx < 0)
                    throw new ArgumentException($"Malformed path segment '{part}'. Bracket '[' is not closed. Expected format: name[index] or name[@attr=value].");
                var name = PathAliases.Resolve(part[..bracketIdx]);
                var indexStr = part[(bracketIdx + 1)..^1];
                if (!int.TryParse(indexStr, out var idx))
                    // A predicate in the index slot (row[Score>0], row[not(V)])
                    // means the caller reached the single-node path navigator
                    // with a FILTER. get is one-node-by-path by contract;
                    // point at the verbs that run the selector engine.
                    throw new ArgumentException(AttributeFilter.IsContentFilterPath($"[{indexStr}]")
                        ? $"'{part}' is a predicate, but this verb navigates by position and expects a numeric index (e.g. {part[..part.IndexOf('[')]}[2]). Predicates work on 'query' (read) and 'set'/'remove' (mutate matched elements)."
                        : $"Invalid path index '{indexStr}' in segment '{part}'. Expected a numeric index.");
                if (idx < 1)
                    throw new ArgumentException($"Invalid path index '{idx}' in segment '{part}'. Index must be >= 1.");
                segments.Add((name, idx));
            }
            else
            {
                segments.Add((PathAliases.Resolve(part), null));
            }

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Close the bracket: use name[index] or name[@attr=value].
  2. Validate the path string has balanced '[' and ']' before calling the navigator.
  3. If you intended a predicate filter, ensure it is fully closed and use the correct verb (query/set/remove).

Example fix

// before
Get(xml, "slides/slide[1"); // missing ]
// after
Get(xml, "slides/slide[1]");
Defensive patterns

Strategy: validation

Validate before calling

static bool BracketsClosed(string segment)
{
    int b = segment.IndexOf('[');
    return b < 0 || segment.IndexOf(']', b + 1) >= 0;
}

Try / catch

try { Get(xml, path); }
catch (ArgumentException ex) when (ex.Message.Contains("Bracket '[' is not closed"))
{ /* add the missing ']' */ }

Prevention

When it happens

Trigger: Calling a get/query path navigator with a segment such as 'slide[' or 'row[Score>0' — a '[' with no following ']'. The parser looks for ']' after the '[' and throws if none is found.

Common situations: Truncated path string; a predicate missing its closing bracket; user input that dropped the ']'; building paths by string concatenation with an off-by-one.

Understand the failure class

Related errors


AI-assisted analysis of iOfficeAI/OfficeCLI@1ced45e900 (2026-08-13). Data as JSON: /api/errors/2e71d8541e6590a6. Report an issue: GitHub.