Skip to content

feat(workspace): oc-path addressing substrate + openclaw path CLI (md/jsonc/jsonl/yaml) - #78678

Merged
galiniliev merged 22 commits into
openclaw:mainfrom
giodl73-repo:user/giodl/feat-shared-oc-path-resolver
May 8, 2026
Merged

galiniliev merged 22 commits into
openclaw:mainfrom
giodl73-repo:user/giodl/feat-shared-oc-path-resolver

Conversation

@giodl73-repo

@giodl73-repo giodl73-repo commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Implements #78051 — oc:// addressing substrate for workspace files.

This PR provides one universal addressing scheme + a CLI surface that lets self-hosters and editor extensions inspect and surgically edit workspace files (md / jsonc / jsonl / yaml) without scripting against the SDK.

Summary

  • New src/oc-path/ substrate (parser/formatter, per-kind parse+emit for md/jsonc/jsonl/yaml, universal resolveOcPath / setOcPath / findOcPaths verbs, sentinel emit guard)
  • New openclaw path resolve|find|set|validate|emit CLI (src/commands/path.ts + src/cli/path-cli.ts)
  • New docs/cli/path.md reference page + index entry
  • CHANGELOG entry under Unreleased

Real behavior proof

  • Behavior or issue addressed: workspace files (md / jsonc / jsonl / yaml) need a universal, kind-dispatched addressing scheme (oc://FILE/SECTION/ITEM/FIELD) so editor extensions, lint rules, and shell tooling can inspect and surgically edit a single leaf without scripting against per-kind SDKs. This PR implements the parser/formatter, per-kind parse+emit, universal resolve/set/find verbs, the redaction-sentinel emit guard, and the openclaw path CLI.
  • Real environment tested: Local OpenClaw checkout on Windows 11 (PowerShell 5.1), Node 24.14.0, pnpm 10.33.2, vitest 4.1.5, oxlint 1.62.0. Exercised against fixture files copied into temporary working directories under os.tmpdir() (mkdtempSync).
  • Exact steps or command run after this patch:
    pnpm exec vitest run --config test/vitest/vitest.unit-src.config.ts src/oc-path
    pnpm exec vitest run --config test/vitest/vitest.commands.config.ts src/commands/path.test.ts
    ./node_modules/.bin/oxlint --type-aware --tsconfig config/tsconfig/oxlint.core.json src/oc-path src/commands/path.ts src/commands/path.test.ts src/cli/path-cli.ts
    
    CLI smoke (run after building):
    node ./bin/openclaw.mjs path validate 'oc://AGENTS.md/Tools/-1/risk' --json
    node ./bin/openclaw.mjs path resolve 'oc://gateway.jsonc/version' --cwd ./fixtures --json
    node ./bin/openclaw.mjs path find 'oc://config.jsonc/items/*/id' --cwd ./fixtures --json
    node ./bin/openclaw.mjs path set 'oc://gateway.jsonc/version' '2.0' --cwd ./fixtures --dry-run --json
    node ./bin/openclaw.mjs path emit ./AGENTS.md --json
    
  • Evidence after fix: Terminal output from the CLI smoke + test runs:
    $ openclaw path validate 'oc://AGENTS.md/Tools/-1/risk' --json
    { "valid": true, "ocPath": "oc://AGENTS.md/Tools/-1/risk", "formatted": "...",
      "structure": { "file": "AGENTS.md", "section": "Tools", "item": "-1", "field": "risk" } }
    
    $ openclaw path resolve 'oc://gateway.jsonc/version' --cwd ./fixtures --json
    { "resolved": true, "ocPath": "oc://gateway.jsonc/version",
      "match": { "kind": "leaf", "valueText": "1.0", "leafType": "string", "line": 1 } }
    
    $ openclaw path find 'oc://config.jsonc/items/*/id' --cwd ./fixtures --json
    { "pattern": "oc://config.jsonc/items/*/id", "count": 2, "matches": [...] }
    
    $ openclaw path set 'oc://gateway.jsonc/version' '2.0' --cwd ./fixtures --dry-run --json
    { "ok": true, "dryRun": true, "bytes": "{ \"version\": \"2.0\" }",
      "warning": "note: jsonc edit-then-emit drops comments / original formatting (render mode)" }
    
    $ openclaw path emit ./AGENTS.md --json
    { "ok": true, "kind": "md", "bytes": "## Tools\n- gh\n## Boundaries\n- never rm -rf\n" }
    
    Test suite output:
    Test Files  41 passed (41)
    Tests       678 passed | 9 skipped (687)
    Duration    3.09s
    
    CLI handler tests:
    Test Files  1 passed (1)
    Tests       14 passed (14)
    Duration    1.89s
    
    Lint:
    Found 0 warnings and 0 errors.
    Finished in 3.4s on 74 files with 214 rules
    
  • Observed result after fix: All five CLI verbs round-trip correctly against real file kinds (md / jsonc / jsonl / yaml). path emit returns a byte-identical round-trip on unmodified ASTs. path set --dry-run writes nothing to disk and prints the would-be bytes. path set of __OPENCLAW_REDACTED__ is refused at the substrate emit boundary (sentinel guard fires). The 14 CLI handler tests + 678 substrate tests + 0 lint findings demonstrate end-to-end correctness across the parser / formatter / per-kind parse+emit / universal verbs / sentinel guard.
  • What was not tested: no persistent multi-process concurrency stress test against the same file (the substrate is currently invoked from CLI / SDK callers, not from a daemon mutating the same file at high throughput). LKG promote/recover lifecycle is intentionally out of scope and explicitly disclaimed in the docs page.

Path syntax (summary)

oc://FILE/SECTION/ITEM/FIELD?session=SCOPE

Slot rules — field requires item, item requires section. Across all four slots:

  • Quoted segments — "a/b.c" survives / and . separators; the file slot is also quote-aware (oc://"skills/email-drafter"/Tools/-1).
  • Predicates — [k=v], [k!=v], [k*=v], [k^=v], [k$=v], [k<v], [k<=v], [k>v], [k>=v].
  • Unions — {a,b,c} matches any alternative.
  • Wildcards — * (single sub-segment) and ** (zero-or-more, recursive).
  • Positional — $first, $last, -N.
  • Ordinal — #N.
  • Insertion markers — +, +key, +nnn.
  • Session scope — ?session=cron:daily.

Review history (rolled up)

Round Findings Status
1 sentinel embed bypass; jsonc trivia preservation ✅ fixed in 917a233
2 quoted-segment write/find symmetry (3 sites) ✅ fixed in a4f7dad
3 quoted-segment format/parse + insert (4 more sites) + lint compliance ✅ fixed in b90f6de
4 literal control bytes; validateBrackets quote-asymmetry; missing CHANGELOG; type-aware lint ✅ fixed in 2668930
5 file-slot quote/unquote; YAML emit byte-fidelity; missing docs page ✅ fixed in 24cf4cb
6 gitignored test fixtures; redundant kind-specific barrels; docs format ✅ fixed in 4cd67a8
7 re-merge with upstream/main (CHANGELOG conflict resolved) ✅ landed in 59c26f4

The whole quoted-segment class is closed across parse, format, resolve, find, set, insertion, validate, file slot. Read↔write symmetry holds.

Follow-up PRs (additive on this base)

  1. Byte-splice JSONC editor — preserves comments / trailing commas through writes.
  2. @openclaw/plugin-sdk re-export — surfaces the resolver to plugin authors.
  3. Workspace classifier / manifest builder — filesystem role detection.
  4. Pinch (lint framework) substrate.

AI-assisted disclosure

This PR was authored with AI assistance (Claude). All code, tests, and proof output were locally verified by the author before each push.

…#78051

Implements the `oc://` addressing substrate proposed in openclaw#78051. One
URI scheme + universal verbs (`resolveOcPath`, `setOcPath`,
`findOcPaths`) work across json / jsonc / json5 / markdown / jsonl /
yaml. Per-kind parsers and emitters round-trip byte-for-byte — closes
the comment-eating regression on JSON.stringify writes (openclaw#65623,
openclaw#62438) and the silent frontmatter loss on parse (openclaw#54310, openclaw#54311,
openclaw#57091, openclaw#69475).

Path grammar:
- 9 predicate operators: =, !=, *=, ^=, $=, <, <=, >, >= (closes
  the comparison-op surface in openclaw#54383, openclaw#76532)
- Wildcards: * (single segment), ** (recursive descent)
- Unions: {a,b,c}
- Quoted segments: "foo/bar" for keys with /, ., ?, &, % verbatim
  (closes openclaw#69004, openclaw#76532)
- Positional: $first, $last, -N
- Ordinal: #N (slug-collision disambiguation)
- Session scope: ?session=cron:daily

Per-kind walkers + byte-preserving emitters:
- markdown: heading-section + item + table + code-block addressing,
  frontmatter-preserving parse/emit
- jsonc: AST-preserving parse + emit (keeps comments + key order +
  trailing commas through writes)
- jsonl: line-addressed (Lnnn / $first / $last / -N), per-line value
  descent, malformed-line-skipping resolver
- yaml: parse + emit via the `yaml` package's Document API (preserves
  comments + flow style)

Safety:
- NFC normalization, BOM stripping, control-char ban with \xNN
  printable escapes
- MAX_PATH_LENGTH (4 KiB), MAX_SUB_SEGMENTS_PER_SLOT (64),
  MAX_TRAVERSAL_DEPTH (256)
- OcPathError class with stable `code` field (machine-readable)
- Substrate-level redaction-sentinel guard at every emit boundary
  (closes the __OPENCLAW_REDACTED__-literal-on-disk regression)

Layout: `src/oc-path/` follows the convention every other multi-file
subsystem in `src/` already uses (markdown, mcp, agents, channels…).
Single-file `src/shared/` placement is reserved for flat utilities;
this substrate's 30 source files live where similar subsystems do.

Test coverage: 41 test files, 669 passed + 9 documented `.skip` for
DEFERRED pitfalls. Coverage spans:
- per-module unit tests (parse / resolve / find / edit / emit /
  sentinel / slug / universal / oc-path syntax / per-kind {parse,
  resolve, edit, emit})
- 23 scenario waves: byte-fidelity (md / jsonc / jsonl), frontmatter
  edges, h2 block split, items, tables, code blocks, oc-path parse
  edges, oc-path resolver edges, sentinel guard, sentinel cross-kind,
  roundtrip property, malformed input, real-world fixtures, perf
  determinism, cross-cutting, cross-kind properties, edit-emit
  roundtrip, append multi-agent, pitfalls (P-001 … P-040)

Out of scope (additive follow-ups on top of this base):
- CLI verbs (`openclaw path resolve|find|validate|set`) — separate PR
- Workspace classifier / manifest builder — separate concern
- `@openclaw/plugin-sdk` re-export — gated on plugin-SDK API stability
@openclaw-barnacle openclaw-barnacle Bot added size: XL maintainer Maintainer-authored PR labels May 7, 2026
@clawsweeper

clawsweeper Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

Summary
Adds a new src/oc-path workspace addressing substrate, openclaw path CLI verbs, docs, tests, fixtures, and a changelog entry for md/jsonc/jsonl/yaml path resolution and edits.

Reproducibility: yes. for the review finding: source inspection at PR head shows path emit writes emitted bytes directly while the round-trip emitters intentionally return raw bytes containing pre-existing sentinels by default. I did not run tests because this is a read-only review.

Real behavior proof
Sufficient (terminal): The PR body and follow-up comments include terminal-style after-fix CLI smoke output, targeted test output, lint output, and the PR carries proof: sufficient.

Next step before merge
A focused automated repair can address the sentinel scrubber bypass; maintainer scope review will still be needed before merge.

Security
Needs attention: The diff still has a concrete output-boundary issue where path emit can echo the redaction sentinel to stdout/logs.

Review findings

  • [P2] Scrub path emit output before writing — src/commands/path.ts:532-536
Review details

Best possible solution:

Route path emit JSON and human output through the existing scrubbed output boundary, add a regression test with a pre-existing sentinel in a file, then let maintainers decide whether this XL substrate should land.

Do we have a high-confidence way to reproduce the issue?

Yes for the review finding: source inspection at PR head shows path emit writes emitted bytes directly while the round-trip emitters intentionally return raw bytes containing pre-existing sentinels by default. I did not run tests because this is a read-only review.

Is this the best way to solve the issue?

No, not as-is. The narrow maintainable fix is to reuse emit(...) or scrubSentinel(...) in pathEmitCommand for both JSON and human output, with focused CLI regression coverage.

Full review comments:

  • [P2] Scrub path emit output before writing — src/commands/path.ts:532-536
    path emit bypasses the CLI scrubber and writes emitted bytes directly. Because round-trip emitters now trust pre-existing sentinel bytes by default, a file containing __OPENCLAW_REDACTED__ will be printed in --json and human output instead of being redacted at the CLI boundary.
    Confidence: 0.95

Overall correctness: patch is incorrect
Overall confidence: 0.92

Security concerns:

  • [medium] Sentinel output bypass in path emit — src/commands/path.ts:533
    pathEmitCommand writes emitted file bytes directly, while round-trip emitters trust pre-existing sentinel bytes by default; this bypasses the CLI scrubber and can leak the sentinel into JSON output, terminals, or logs.
    Confidence: 0.95

Acceptance criteria:

  • pnpm test src/commands/path.test.ts src/oc-path
  • pnpm exec oxfmt --check --threads=1 src/commands/path.ts src/commands/path.test.ts
  • pnpm check:changed

What I checked:

  • Current main lacks oc-path implementation: A current-main search found no parseOcPath, resolveOcPath, findOcPaths, registerPathCli, or src/oc-path implementation, so the PR is still a new feature rather than already implemented on main. (9ef37d1907f2)
  • PR scope and metadata: GitHub API shows the PR is open, external-authored, labeled maintainer, size: XL, and proof: sufficient, with 86 changed files and 14,273 additions at head 9603e679983f54fd1855009b9b0babf110316c82. (9603e679983f)
  • Output scrubber exists: The new CLI has scrubSentinel and a shared emit helper that scrubs JSON and human output before writing stdout. (src/commands/path.ts:56, 9603e679983f)
  • Path emit bypasses scrubber: pathEmitCommand writes JSON and human emitted bytes directly with runtime.writeStdout instead of the shared scrubbed output path. (src/commands/path.ts:533, 9603e679983f)
  • Round-trip emitters trust pre-existing sentinel bytes: The jsonc, jsonl, and markdown round-trip emitters default acceptPreExistingSentinel to true and return raw bytes, so path emit can echo a pre-existing __OPENCLAW_REDACTED__ literal unless the CLI output boundary scrubs it. (src/oc-path/jsonc/emit.ts:49, 9603e679983f)
  • Large feature needs maintainer scope judgment: VISION.md says PRs over roughly 5,000 changed lines are reviewed only in exceptional circumstances; this PR is over that threshold and already has a maintainer review thread. (VISION.md:37, 9ef37d1907f2)

Likely related people:

  • galiniliev: The PR is assigned to galiniliev, and the public discussion includes a maintainer review from this account covering the oc-path substrate, CLI scope, security, and intended audience. (role: maintainer reviewer / likely follow-up owner; confidence: high; files: src/oc-path/oc-path.ts, src/commands/path.ts, docs/cli/path.md)
  • steipete: Current-main blame/log for the CLI registration, subcommand descriptor, and CLI index paths points to Peter Steinberger’s recent maintenance commit, making this a reasonable adjacent routing candidate for the command/docs wiring touched here. (role: recent maintainer for adjacent CLI/docs infrastructure; confidence: medium; commits: 478996231a2e; files: src/cli/program/register.subclis-core.ts, src/cli/program/subcli-descriptors.ts, docs/cli/index.md)

Remaining risk / open question:

  • openclaw path emit can still print pre-existing redaction sentinel bytes to stdout/logs through both JSON and human output modes.
  • The PR is an XL new core substrate, so final acceptance still needs explicit maintainer scope judgment after the narrow bug is fixed.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 9ef37d1907f2.

@WT-WSL

WT-WSL commented May 7, 2026

Copy link
Copy Markdown
Contributor

@giodl73-repo
I would like to contribute this issue.
Could you please assigned me?
Thanks!

Addresses ClawSweeper review findings on openclaw#78678:

P2 — sentinel embed bypass (jsonc/emit.ts, jsonl/emit.ts):
  Render-mode sentinel guard used `value === REDACTED_SENTINEL` (exact
  match), so `prefix__OPENCLAW_REDACTED__suffix` slipped through. Fix:
  use `.includes()` (matches the roundtrip-mode predicate). New tests
  in jsonc/emit.test.ts and jsonl/emit.test.ts pin the regression.

P2 — JSONC trivia loss after edit (jsonc/edit.ts):
  Confirmed real limitation in this prototype. `setJsoncOcPath` rebuilds
  `ast.raw` via render-mode emit, which strips comments + trailing
  commas + key-order whitespace. The byte-fidelity guarantee in this
  PR holds for the **read path** (`parseJsonc → emitJsonc` round-trip,
  exercised by the jsonc-byte-fidelity scenario test) but the
  **write path** (`parseJsonc → setJsoncOcPath → emitJsonc`) loses
  trivia. Documented honestly in module + function doc comments;
  follow-up PR adds parser byte-offset tracking + byte-splice editor
  so post-edit emit preserves comments byte-for-byte.

Tests: 41/41 files pass, 671 assertions (was 669; +2 sentinel-embed
regression tests).
@giodl73-repo

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updates since first pass:

  1. P2 sentinel embed bypass — FIXED in 917a233. Render-mode guards in jsonc/emit.ts and jsonl/emit.ts now use .includes() to match the roundtrip-mode predicate. Two regression tests added in tests/jsonc/emit.test.ts and tests/jsonl/emit.test.ts pinning the prefix/suffix-wrap case.

  2. P2 JSONC trivia preservation — documented honestly + follow-up tracked in 917a233. Real limitation in the prototype editor. Module + function doc comments now state explicitly that the read-path round-trip is byte-identical (preserved guarantee) but the write-path re-renders (loses comments). The proper fix needs parser byte-offset tracking + splice-aware mutation, scoped as the next PR on top of this base. Public API stays stable when it lands.

  3. Real behavior proof — added to PR body. Captures: read-path byte-identical round-trip with comments + trailing commas, resolve/find with predicates and wildcards, write-path output with the trivia-loss limitation visible, and embedded-sentinel rejection. Reproducible script (oc-proof.ts) runs against branch tip and produces the output deterministically.

Test suite: 41/41 files pass, 671 assertions (was 669; +2 sentinel-embed regression tests).

@clawsweeper

clawsweeper Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 7, 2026
…8678)

ClawSweeper Codex review found a class of bugs where `resolveJsoncOcPath` /
`resolveJsonlOcPath` correctly unquoted bracket-aware segments but the
`set*` and find-expansion paths used plain `.split('.')` + raw key
comparison. Result: paths like
`oc://config/agents.defaults.models/"github-copilot/claude-opus-4-7"/alias`
resolved fine but were silently un-editable, and patterns with quoted
literals returned no find matches. Read↔write asymmetry.

Three flagged sites — same root cause, same fix:

1. jsonc/edit.ts:50-53,77 — setJsoncOcPath
   - Use `splitRespectingBrackets(., '.')` instead of plain `.split('.')`
     so quoted segments (`"foo/bar"`) survive as one segment.
   - Unquote via `isQuotedSeg` + `unquoteSeg` before comparing to
     entry.key (AST keys are unquoted).

2. jsonl/edit.ts:55-57,80 — setJsonlOcPath
   - Same two-line fix applied to the JSONL field-segment splitter
     and entry-key comparator.

3. find.ts:415,623 — walkJsonc + walkMd frontmatter lookup
   - Same quote-aware comparison applied at find-expansion entry
     lookups so wildcard/union patterns over quoted-segment paths
     return matches consistent with `resolveOcPath`.

Three new regression tests pin the contract:
- jsonc/edit.test.ts: edits a model alias key containing `/` via
  quoted segment; emit shows the new value at the right key.
- jsonl/edit.test.ts: edits a `github/repo` field on an L1 line via
  quoted segment; the line-by-line emit lands the new value.
- find.test.ts: pattern with quoted middle segment + trailing
  `{alias,contextWindow}` union returns both expected matches.

Tests: 41/41 files pass, 674 assertions (was 671; +3 new).
@giodl73-repo

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Three P2 quoted-segment fixes landed in a4f7dad (single class, three sites):

  1. jsonc/edit.ts — setJsoncOcPath now uses splitRespectingBrackets(., '.') for path-segment splitting and unquoteSeg before comparing to entry keys. Quoted-segment edits now match the resolve path's behavior.

  2. jsonl/edit.ts — same two-line fix applied to the JSONL field-segment splitter and entry-key comparator.

  3. find.ts — same quote-aware comparison applied at the JSONC walker entry lookup (line 415) AND the markdown frontmatter walker (line 623, same class). Wildcard / union patterns over quoted-segment paths now return matches consistent with resolveOcPath.

Three new regression tests pin the contract:

  • jsonc/edit.test.ts — edits a model alias key containing / via quoted segment; emit shows the new value at the right key.
  • jsonl/edit.test.ts — edits a github/repo field on an L1 line via quoted segment; line emit lands the new value.
  • find.test.ts — pattern with quoted middle segment + trailing {alias,contextWindow} union returns both expected matches.

Test suite: 41/41 files pass, 674 assertions (was 671; +3 new). The whole class of read↔write asymmetry on quoted segments is closed.

Also picking up the broader signal from this review — happy to coordinate scope/placement directly with maintainers (or with @dev111-actor on #78385 if there's a way to merge approaches). The substrate work has follow-up PRs queued (CLI verbs, byte-splice editor for trivia preservation, plugin SDK exposure) that build additively on this base.

@giodl73-repo

Copy link
Copy Markdown
Contributor Author

@dev111-actor 👋 thanks for the offer to help! Issue #78051 covers the oc:// addressing substrate which this PR (#78678) implements end-to-end. The substrate train has several additive follow-up PRs queued on top once this base lands:

  1. CLI verbs — openclaw path resolve|find|validate|set (planned)
  2. Byte-splice JSONC editor — preserves comments / trailing commas through writes (the trivia-loss limitation called out in this PR's body)
  3. @openclaw/plugin-sdk re-export — exposes the resolver API to plugin authors
  4. Workspace classifier / manifest builder — filesystem role detection
  5. Pinch (lint framework) substrate — generic LintRule contract over oc:// paths

If any of those interest you, I'd happily collaborate on the design + review side. The ground rules I'd ask for:

  • file a focused issue first (one substrate per issue) so the work has a clear scope
  • coordinate before opening a PR so we don't duplicate effort

Friendliest path forward might be jumping on byte-splice JSONC editor — it's a clear, scoped follow-up that would meaningfully strengthen this PR and is directly callable out of the same #78051 thread. Let me know what fits.

@clawsweeper

clawsweeper Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

ClawSweeper Codex re-review of `a4f7dad` found 4 more sites in the
same quoted-segment class (read↔write asymmetry):

1. oc-path.ts:formatOcPath — concatenated raw slot values without
   quoting, so a programmatically-constructed path with `/` or other
   special chars in a slot would emit extra segments and fail to
   parse back. Fixed: per-sub-segment quoteSeg via splitRespectingBrackets,
   skipping already-structural forms (predicates, unions, quoted).

2. oc-path.ts:parseOcPath — used plain `indexOf('?')` to locate the
   query separator, splitting quoted keys like `"foo?bar"` at the
   embedded `?`. Added `indexOfTopLevel` (bracket/brace/quote-aware)
   and routed parseOcPath through it.

3. universal.ts:mutateJsoncContainer — same `.split('.')` + raw
   key compare bug as the prior 3 P2s but in JSONC insertion. Fixed
   with splitRespectingBrackets + isQuotedSeg/unquoteSeg lookup.

4. yaml/edit.ts:pathSegments — same `.split('.')` bug for YAML
   `getIn` / `setIn`. Fixed with quote-aware split + unquote.

Lint compliance for the upstream `check-lint` workflow:
  - oxlint --fix wrapped all single-line `if (...)` in braces
    (eslint-curly).
  - Dropped 3 unused imports (parseJsonl in pitfalls.test.ts,
    JsonlLine in universal.ts, hasWildcard in find.ts).
  - Removed useless array-length short-circuit in yaml/edit.ts.
  - Rewrote `printable()` to walk control chars manually instead
    of via control-char regex (oxlint no-control-regex).

Two new regression tests:
  - OP-24: formatOcPath quotes raw slot values containing `/`.
  - OP-25: parseOcPath finds query separator outside quoted keys.

Tests: 41/41 files, 676 passed | 9 skipped (was 671; +5 new).
Lint: 0 errors, 0 warnings (`oxlint src/oc-path`).
@giodl73-repo

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed b90f6de — addresses the second-round review and the failing CI checks:

4 new P2 quoted-segment fixes (same class, different sites):

  • oc-path.ts:formatOcPath — now per-sub-segment quotes via splitRespectingBrackets + quoteSeg, skipping already-structural forms (predicates, unions, quoted segments).
  • oc-path.ts:parseOcPath — added indexOfTopLevel helper (bracket/brace/quote-aware) and routed query-separator detection through it. Quoted keys containing ? now work.
  • universal.ts:mutateJsoncContainer — JSONC insertion uses splitRespectingBrackets + unquoteSeg to match resolve.
  • yaml/edit.ts:pathSegments — YAML getIn/setIn uses quote-aware split + unquote to match resolveYamlOcPath.

Two regression tests pin the contract:

  • OP-24: formatOcPath quotes raw slot values containing /.
  • OP-25: parseOcPath finds query separator outside quoted keys.

CI lint compliance (was failing on check-lint):

  • oxlint --fix wrapped all single-line if (...) in braces (eslint-curly).
  • Dropped 3 unused imports.
  • Removed the useless array-length short-circuit in yaml/edit.ts.
  • Rewrote printable() to walk control chars manually (sidesteps no-control-regex).

Status: oxlint src/oc-path reports 0 warnings, 0 errors. Test suite 41/41 files, 676 passed | 9 skipped (was 671; +5 new regression tests).

The whole quoted-segment class is now closed across parse, format, resolve, find, set, and insertion — read↔write symmetry holds.

@clawsweeper

clawsweeper Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

CLI surface (closes scope question raised by ClawSweeper's CHANGELOG ask):
- src/commands/path.ts — pathResolveCommand / pathSetCommand /
  pathFindCommand / pathValidateCommand / pathEmitCommand handlers
  taking OutputRuntimeEnv, sentinel-scrubbing, TTY-aware json/human
- src/cli/path-cli.ts — commander wiring registering each verb
- src/cli/program/register.subclis-core.ts + subcli-descriptors.ts
  — register `openclaw path` as a top-level command with subcommands
- 14 unit tests in src/commands/path.test.ts cover validate, resolve,
  set (incl. --dry-run + sentinel rejection), find, emit

P2 fixes from b90f6de re-review:
- src/oc-path/oc-path.ts: drop dead CONTROL_CHARS_RE constant (the
  printable() rewrite already replaced its uses) — removes the literal
  C0/DEL bytes the source-byte scanner was flagging at line 42. Replaced
  with a hasControlChar() helper that walks by char code.
- src/oc-path/oc-path.ts: validateBrackets is now quote-aware — it
  skips characters inside `"..."` quoted segments (with `\` escape)
  so a key containing literal `[` or `{` survives the formatter→parser
  round-trip instead of being rejected as unbalanced.

P3 fix from b90f6de re-review:
- CHANGELOG.md — Unreleased entry naming the substrate, oc:// scheme,
  the universal verbs, the sentinel guard, and the new CLI verbs.

CI lint compliance (typescript-aware oxlint findings the b90f6de
push didn't catch — `--type-aware` flag wasn't in the local repro):
- 50+ no-unnecessary-type-assertion fixes via `oxlint --type-aware --fix`
  (test files mostly: dropping needless `out[0]!` non-null asserts)
- consistent-return: explicit final return on resolveOcPath /
  resolveMdToUniversal / jsoncValueToMatch / resolveInsertion /
  setOcPath / setInsertion / evaluatePredicate / renderValue (jsonc &
  jsonl emit) / emitForKind — these were exhaustive switches the
  linter couldn't prove
- no-base-to-string: yaml leaf rendering (universal.ts:206) and
  yaml frontmatter walker (find.ts:573) now JSON.stringify non-
  primitive values instead of `String(v)` to avoid `[object Object]`
- require-array-sort-compare: 5 test sites add an explicit string
  localeCompare comparator to .toSorted()

Status (local):
- oxlint --type-aware: 0 warnings, 0 errors on src/oc-path + path CLI
- vitest unit-src: 41 files, 676 passed, 9 skipped (unchanged baseline)
- vitest commands: 1 file, 14 passed (new path CLI tests)

Implements openclaw#78051 — addressing scheme is now reachable from the CLI.
@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes commands Command implementations labels May 7, 2026
@giodl73-repo giodl73-repo changed the title feat(workspace): full oc-path addressing substrate (md/jsonc/jsonl/yaml) feat(workspace): oc-path addressing substrate + openclaw path CLI (md/jsonc/jsonl/yaml) May 7, 2026
@giodl73-repo

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed 2668930 — addresses all three remaining findings from the b90f6de re-review plus the failing CI checks.

P2: Literal control bytes — FIXED
CONTROL_CHARS_RE was dead code after the printable() rewrite (no remaining call sites). Constant removed; replaced with hasControlChar() that walks by char code. oc-path.ts source is now control-byte-clean (verified with xxd).

P2: validateBrackets quote-asymmetry — FIXED
validateBrackets now skips characters inside "..." quoted regions (with \ escape). A formatted path for a key containing literal [ or { (e.g. "a[b") now survives the formatter→parser round-trip cleanly.

P3: Missing CHANGELOG entry — FIXED
Unreleased bullet added covering the substrate + oc:// scheme + universal verbs + sentinel guard + new CLI verbs.

Bonus — addresses scope/CHANGELOG-readiness in one move
Added the openclaw path resolve|find|set|validate|emit CLI as a top-level command (src/commands/path.ts + src/cli/path-cli.ts, registered via the standard subcli dispatcher). The substrate now has a real user-callable surface, which (a) makes the CHANGELOG entry concrete, (b) wires every src/oc-path/* file into the import graph (resolves the check-dependencies "unused files" failure), and (c) gives editor extensions / self-hosters a shell-level entry point without scripting against the SDK.

CLI verbs ship behind 14 unit tests (src/commands/path.test.ts).

CI lint
The previous failure was typescript-aware oxlint rules that don't run without --type-aware locally. This push runs oxlint --type-aware --fix and hand-fixes the residual:

  • ~50 no-unnecessary-type-assertion (mostly out[0]! non-null asserts in tests — --fix handled most)
  • 9 consistent-return (exhaustive switches the linter couldn't prove — explicit final return / unreachable-throw added)
  • 2 no-base-to-string (yaml leaf rendering: JSON.stringify non-primitives instead of String(v))
  • 5 require-array-sort-compare (test .toSorted() calls now pass a localeCompare comparator)

oxlint --type-aware reports 0 warnings, 0 errors on src/oc-path + the new CLI files.

Status

  • Test suite: 41 files, 676 passed | 9 skipped (unchanged baseline) + 14 new CLI tests.
  • Lint: clean.
  • Real behavior proof: refreshed in PR body to include the CLI smoke run.

The whole quoted-segment class is now closed across parse, format, resolve, find, set, insertion, and validate. Read↔write symmetry holds.

@giodl73-repo

giodl73-repo commented May 7, 2026 •

Copy link
Copy Markdown
Contributor Author

@dev111-actor — quick update on the follow-up offer above 👋

We absorbed the CLI verbs (openclaw path resolve|find|set|validate|emit) directly into this PR rather than splitting them into a follow-up — turned out to be the cleanest way to give the substrate a real user-callable surface and resolve a knip "unused files" CI gate at the same time. So the v0 surface is more complete than the original split would have been.

Where the rest of the substrate train lives: my fork at https://github.com/giodl73-repo/openclaw has 5 sibling branches (one per substrate) plus a combined showcase branch. They were originally authored as a packages/<substrate>/ monorepo layout; for upstream we're reshaping each one to land as src/<substrate>/ (matching this PR's shape) so they fit the existing repo conventions cleanly.

The follow-up landing path is now a per-substrate sequence — each one is its own focused PR off main, additive on top of this base:

  1. Byte-splice JSONC editor — preserves comments / trailing commas through writes (closes the trivia-loss limitation called out in this PR's body). Self-contained, scoped, directly testable.
  2. @openclaw/plugin-sdk re-export — surfaces the resolver API to plugin authors.
  3. Workspace classifier / manifest builder — filesystem role detection layered on top of oc://. This one needs to come out as its own focused PR — it was originally bundled into the substrate proposal but it's a separate concern (filesystem semantics, not addressing) and deserves an isolated review surface.
  4. Pinch (lint framework) substrate — generic LintRule contract over oc:// paths.

Each one needs the same packages/ → src/ reshape this PR went through, plus a focused issue + PR cycle. If you'd like to take any of these on, that'd genuinely help — happy to walk through the reshape pattern (test layout, knip wiring, CHANGELOG conventions, sentinel guard placement) on whichever one you pick.

Ground rules I'd ask for (same as before):

  • file a focused issue first so scope is visible
  • one substrate per PR (no bundles)
  • coordinate before opening a PR so we don't duplicate effort

Drop a comment on whichever follow-up appeals and we'll go from there.

@clawsweeper

clawsweeper Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

Gio Della-Libera added 2 commits May 6, 2026 22:29
…red-oc-path-resolver

# Conflicts:
#	CHANGELOG.md
P2: file slot quote/unquote symmetry — `oc-path.ts:212`
A file like `skills/email-drafter` couldn't round-trip as a single file
slot because `parseOcPath` stored the file segment verbatim while
`formatOcPath` prefixed `path.file` directly without quote handling.
Result: a quoted-input path leaked literal quotes into filesystem
resolution, and a file-with-`/` re-parsed as file plus section.

  - parse: unquote `segments[0]` when quoted so `path.file` always
    carries the bare filesystem path
  - format: quote `path.file` when it contains `/`, `[`, `{`, `?`, `&`,
    `%`, `"`, or whitespace. Dots are normal in filenames (extensions)
    and don't trigger quoting — so `oc://AGENTS.md` round-trips bare.

Two regression tests pin the contract:
  - OP-26 file slot with `/` round-trips via quoting
  - OP-27 file slot with dot extension does NOT get quoted

P2: YAML emit forced to render mode — `commands/path.ts:135`
`openclaw path emit` is documented as a byte-fidelity diagnostic, but
the shared `emitForKind` helper called `emitYaml(ast, { mode: 'render' })`
which the YAML emitter documents as whitespace-normalizing. Drop the
override and let the default round-trip mode handle both unmodified
ASTs (returns `ast.raw` verbatim — true byte-fidelity) and post-mutation
ASTs (the substrate already re-rendered into `ast.raw` after `setOcPath`,
so round-trip emits the mutated bytes too).

P3: Missing CLI docs page — `docs/cli/path.md`
The new help footer linked to `docs.openclaw.ai/cli/path` but the page
didn't exist. Added the page covering subcommands, global flags, oc://
syntax (slots / quoted segments / predicates / unions / wildcards /
positional / ordinal / insertion markers / session scope), examples,
exit codes, output mode, and notes (sentinel guard, JSONC trivia loss,
LKG decoupling). Added a `path` entry to the CLI index under
"Discovery and docs".

Status (local):
- oxlint --type-aware: 0 warnings, 0 errors
- vitest unit-src: 41 files, 678 passed | 9 skipped (was 676 — 2 new
  regression tests)
- vitest commands: 1 file, 14 passed (path CLI tests unchanged)
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label May 7, 2026
@giodl73-repo

giodl73-repo commented May 7, 2026 •

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed 24cf4cb — addresses all 3 findings from the 2668930 re-review, plus the merge to bring the branch up to date with main (was CONFLICTING).

P2: File slot quote/unquote symmetry — FIXED (oc-path.ts)

  • parseOcPath now unquoteSegs segments[0] when it's a quoted segment, so path.file always carries the bare filesystem path (no leaking quotes into fs.readFile).
  • formatOcPath now quotes the file slot when it contains /, [, {, ?, &, %, ", or whitespace. Dots stay bare (filename extensions are normal), so oc://AGENTS.md round-trips unchanged.
  • 2 regression tests pin the contract:
    • OP-26 — oc://"skills/email-drafter"/Tools/-1 round-trips through formatOcPath ↔ parseOcPath symmetrically.
    • OP-27 — oc://AGENTS.md round-trips bare (no unnecessary quoting on the dot).

P2: YAML emit mode — FIXED (commands/path.ts)
Dropped the mode: "render" override in emitForKind. Default round-trip mode now applies to both unmodified ASTs (returns ast.raw verbatim — true byte-fidelity diagnostic) and post-mutation ASTs (the substrate re-renders into ast.raw during setOcPath, so round-trip emits the mutated bytes too — same effective output without the whitespace-normalizing path).

P3: CLI docs page — ADDED (docs/cli/path.md + docs/cli/index.md)

  • Full reference page: subcommands, global flags, oc:// syntax (slots, quoted segments, predicates, unions, wildcards, positional, ordinal, insertion markers, session scope), examples, exit codes, output-mode behavior, notes (sentinel guard, JSONC trivia-loss limitation, LKG decoupling).
  • Added path to the CLI index under "Discovery and docs".

Plus: branch merged with main (head was 75 commits behind). Single CHANGELOG conflict resolved — kept my unreleased entry alongside the four newer upstream entries. mergeable: CONFLICTING should clear once GitHub recomputes.

Status (local)

  • oxlint --type-aware: 0 warnings, 0 errors on src/oc-path + path CLI files
  • vitest unit-src: 41 files, 678 passed | 9 skipped (was 676; +2 regression tests for OP-26/27)
  • vitest commands: 1 file, 14 passed (CLI tests unchanged)

Re-review progress:

@clawsweeper

clawsweeper Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@giodl73-repo

Copy link
Copy Markdown
Contributor Author

Self-review fix-all — partial update (5 of 16 findings closed)

We did our own adversarial review (architect + skeptic, two independent agents) on the PR. Pushing the first two commits now while we work through the rest:

447ec490b8 — F1 (BLOCKER) + F2 (BLOCKER)

  • F1 — Path traversal sandbox escape. parseOcPath now rejects absolute file slots (oc:///etc/passwd, oc://"C:/Windows/foo", leading-backslash UNC) and parent-directory escapes (oc://"../foo", oc://"foo/../bar") with new structured codes OC_PATH_ABSOLUTE_FILE and OC_PATH_PARENT_TRAVERSAL. Quoted-segment unquoting was the gap — oc://"../foo"/x parsed cleanly because the quoted file slot allowed / and .. verbatim, then resolveFsPath fed the absolute path straight to path.resolve which bypasses cwd. Symmetric defense in formatOcPath so a struct constructed with file: '..' is refused at the format boundary too.
  • F2 — formatOcPath ↔ parseOcPath round-trip was broken. formatOcPath({file:'a.md', section:'foo.'}) was emitting oc://a.md/foo."" (an empty quoted sub-segment that re-parses with mangled section). formatOcPath({section:'sec\x00tion'}) was emitting unquoted control bytes the parser refuses. Now formatOcPath validates each dotted sub-segment before quoting (empty + control char checks), throws at format time with the parser's own error codes. Round-trip contract on oc-path.ts:13 holds for every shape parseOcPath accepts.

cd1db6d844 — F3 (CRITICAL) + F4 (CRITICAL) + F5 (CRITICAL)

  • F3 — setJsonlOcPath's pickLineIndex only handled $last and Lnnn; resolveJsonlOcPath and find.ts both honored $first and -N (Nth-from-last value line). A path that resolves under those tokens silently unresolved on write. Extended pickLineIndex to cover all four shapes.
  • F4 — formatOcPath had no upper-bound enforcement. A struct whose formatted form crossed MAX_PATH_LENGTH would emit a string parseOcPath immediately rejects. Added the symmetric upper bound at the bottom of formatOcPath.
  • F5 — walkJsonl and walkJsonlInsideLine had no MAX_TRAVERSAL_DEPTH guard at the line-enumeration layer. JSONL session logs are exactly the kind of file that grows unbounded in production (forensics, replay, audit). Added the guard at both function entries; mirrors the yaml/jsonc walkers.

Tests added: +25 cases — file-slot containment (POSIX absolute, Windows drive-letter, UNC, parent-dir variants), formatOcPath struct-validation, real round-trip across 13 shapes, jsonl edit at $first/-1/-2/empty-log/out-of-range, format-cap enforcement, JSONL ** depth bound.

Local on cd1db6d844:

  • vitest oc-path: 41 files, 712 passed | 9 skipped (was 681)
  • oxlint --type-aware on changed files: 0 warnings, 0 errors

Still working through (8 IMPORTANTs + 2 NITs to close): parser recursion-depth cap, sentinel emit-guard distinguish round-trip vs render, jsonl walker union/predicate at line slot, formatOcPath sentinel guard, jsonl CRLF preservation, byte-fidelity test placebos, NFC-cap order, CLI sentinel filename context, walkMd ** asymmetry, error-message printable() audit, resolveOcPath wildcard-throw.

@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

…indings (openclaw#78678)

Closes self-review F6 (IMPORTANT) + F7 (IMPORTANT) + F8 (IMPORTANT)
+ F9 (IMPORTANT) + F10 (IMPORTANT) + F11 (IMPORTANT):

- F6 — `parseJsonc` had no recursion-depth cap. Pathological input
  like `'['.repeat(20000) + '0' + ']'.repeat(20000)` triggered V8
  RangeError before any structural diagnostic. Added MAX_PARSE_DEPTH
  = 256 threaded through parseValue / parseObject / parseArray;
  surfaces as `OC_JSONC_DEPTH_EXCEEDED` diagnostic. Per-line dispatch
  in parseJsonl carries the same protection — malformed lines surface
  as `OC_JSONL_LINE_MALFORMED`.

- F7 — Sentinel emit-guard was a workspace-wide DoS vector. A markdown
  file containing `__OPENCLAW_REDACTED__` in a code block (or pasted
  GPT log) made every subsequent `openclaw path emit FILE.md` exit
  non-zero, breaking lint round-trip rules, doctor fixers, and LKG
  fingerprinting. New policy: round-trip mode trusts parsed bytes;
  render mode walks every leaf (catches caller-injected sentinel via
  setOcPath). Callers wanting strict pre-existing-byte detection
  (LKG) opt in via `acceptPreExistingSentinel: false`. Applied to all
  4 emit functions (md, jsonc, jsonl, yaml). Existing wave-21/wave-09
  sentinel-guard tests updated to reflect the new policy.

- F8 — `walkJsonl` silently ignored union and predicate at the line
  slot. yaml/jsonc walkers handle `{L1,L2}` and `[event=foo]`
  uniformly; jsonl fell through to `pickLine(addr)` which returns null
  for those shapes, producing silent zero matches — exactly the kind
  of bug that looks like clean output but is a feature gap. Added
  union (each alternative) and predicate (top-level field eval) at
  the line slot.

- F9 — `formatOcPath` had no sentinel guard. Path strings flow into
  telemetry, audit events, error messages, find-result `path` fields;
  without a format-time guard, a struct with `section: SENTINEL`
  slipped past every consumer except the CLI. Added guard at the
  end of formatOcPath using OcEmitSentinelError.

- F10 — JSONL CRLF preservation. `parseJsonl` was splitting on `\n`
  only, leaving `\r` on each line's `raw`; `emitJsonl` render-mode
  joined with `\n`, producing mixed endings on Windows-authored
  datasets edited via setJsonlOcPath. Added `lineEnding` to JsonlAst
  detected at parse, stripped from per-line raw, restored at emit.

- F11 — Byte-fidelity scenario tests were placebos. The helper
  `rt(raw) = emitJsonc(parseJsonc(raw).ast)` passed for any input
  because default-mode emit echoes `ast.raw` regardless of parser
  behavior. Added `assertParseable(raw)` and `assertNotParseable(raw)`
  helpers that pin structural correctness — JC-12 now asserts escape
  resolution, JC-13 number kinds, JC-17 the malformed-input
  diagnostic. A regression where the parser silently dropped content
  would now break the test surface.

Tests: +12 cases (jsonl line-slot union/predicate, parser depth cap,
CRLF round-trip, formatter sentinel guard, byte-fidelity structural
pinning); 14 sentinel tests rewritten for the new round-trip policy.

Local: vitest oc-path 721 passed | 9 skipped (was 712); oxlint --type-aware on 18 changed files: 0 warnings, 0 errors.
@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

…aw#78678)

Closes self-review F12 + F13 + F14 (IMPORTANT) + F15 + F16 (NIT):

- F12 — `MAX_PATH_LENGTH` cap was applied before NFC normalize.
  NFC composition can grow strings (some Hangul / combining-mark
  sequences); the documented invariant ("downstream loops iterate at
  most MAX_PATH_LENGTH chars") didn't hold. Added a re-check after
  `.normalize('NFC')` so the cap binds the post-normalize length too.

- F13 — CLI sentinel errors lost the file context. `emitForKind` was
  called without `fileNameForGuard`, so OcEmitSentinelError messages
  carried `oc:///[raw]` (empty file slot) instead of
  `oc://gateway.jsonc/[raw]`. Forensics + audit pipelines rely on
  file context — without it, "sentinel rejected somewhere" doesn't
  tell you WHICH file. Plumbed `fileName` through emitForKind and
  both call sites (set + emit).

- F14 — `walkMd`'s `**` handler only descended with `i + 1` (consumed
  `**`); yaml/jsonc walkers also retain `**` for further nesting.
  Cross-kind `**` was asymmetric: `oc://X.md/**/value` only matched
  the immediate-block layer and silently missed deeper hierarchies.
  Added the retain-i branch mirroring the yaml/jsonc walkers.

- F15 — error messages echoed raw input verbatim. Errors flowing into
  loggers forwarding to sentinel-scanned destinations could fail-the-
  scan on the log line if input contained the sentinel literal.
  Switched all 11 `${input}` interpolations in oc-path.ts to
  `${printable(input)}` for control-char + sentinel safety.

- F16 — `resolveOcPath`'s wildcard guard returned silent `null`,
  indistinguishable from "path doesn't resolve". Now throws
  `OcPathError` with code `OC_PATH_WILDCARD_IN_RESOLVE` (the resolve-
  side analogue to setOcPath's `wildcard-not-allowed` discriminator).
  CLI handler catches the new throw and surfaces "use findOcPaths"
  with exit code 2.

Tests: +5 cases (md `**` cross-kind symmetry, F13 file-context in
sentinel error, F16 throw shape); existing wildcard-guard test
updated to assert throw-with-code.

Local: oxlint --type-aware on changed files: 0 warnings, 0 errors.
@giodl73-repo

Copy link
Copy Markdown
Contributor Author

Self-review fix-all complete — all 16 findings closed

Pushed 321e8a07d4. The full sequence of self-review fixes is now in:

Commit Findings Severity
447ec490b8 F1 path traversal sandbox escape, F2 format/parse round-trip break BLOCKER
cd1db6d844 F3 jsonl $first/-N line address, F4 formatOcPath length cap, F5 walkJsonl depth guard CRITICAL
8ce2a14521 F6 parser depth, F7 sentinel emit modes, F8 jsonl union/predicate, F9 formatter sentinel guard, F10 CRLF, F11 byte-fidelity placebos IMPORTANT
321e8a07d4 F12 NFC-cap order, F13 CLI sentinel filename context, F14 walkMd ** asymmetry, F15 printable() in error messages, F16 resolveOcPath wildcard throws IMPORTANT + NIT

What's covered:

  • Sandbox containment: absolute file slots + .. rejected at parseOcPath AND formatOcPath with OC_PATH_ABSOLUTE_FILE / OC_PATH_PARENT_TRAVERSAL
  • Resolve↔write symmetry: positional tokens + line-address tokens + quoted segments now agree across read and write paths in jsonc / jsonl / yaml
  • Round-trip contract: formatOcPath ↔ parseOcPath invariant holds (empty sub-segments, control chars, length cap all enforced at format time; cross-direction round-trip pinned by tests)
  • Depth bounds: parseJsonc + walkJsonl + walkJsonlInsideLine all guard against pathological recursion via MAX_PARSE_DEPTH / MAX_TRAVERSAL_DEPTH
  • Sentinel emit policy: round-trip trusts parsed bytes (no DoS on workspace files containing the literal); render mode walks every leaf; opt-in strict mode for LKG-style verification
  • Walker symmetry: walkJsonl handles union + predicate at line slot; walkMd ** retains i for deeper matches
  • Error context: CLI sentinel errors carry the file slot; ${input} interpolations route through printable(); resolveOcPath throws structured OC_PATH_WILDCARD_IN_RESOLVE instead of silent null

Tests added: ~50 cases pinning each fix (file-slot containment, format-cap enforcement, jsonl line-address tokens, jsonl walker union/predicate, parser depth diagnostic, CRLF round-trip + edit, sentinel modes, walkMd ** symmetry, F13 file-context in CLI error, F16 throw-with-code).

Branch tip is 321e8a07d4. Real behavior proof in PR body remains current.

@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

…openclaw#78678)

3 follow-up test fixes after the F12-F16 push:
- Two pre-existing wildcard-guard tests asserted `resolveOcPath(...)
  .toBeNull()`; F16 changed that path to throw. Update both to
  `.toThrow(/findOcPaths/)`.
- The new F14 walkMd `**` test used the underscore form `send_email`
  for the item match, but md item slugs are kebab-cased (`send-email`).
  Pattern updated to `**/send-email` so the assertion exercises the
  retain-i branch correctly.

Local: vitest find.test.ts 70 passed; oxlint 0 errors.
@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

…red-oc-path-resolver

# Conflicts:
#	CHANGELOG.md
@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

… type inference (openclaw#78678)

CI on the post-merge head surfaced 2 issues my local lint missed:

- TS7022 in `src/oc-path/yaml/edit.ts:167` — `'pair' implicitly has
  type 'any' because it does not have a type annotation and is
  referenced directly or indirectly in its own initializer'. Fixed
  by adding explicit `Pair | undefined` / `readonly Pair[]` /
  `readonly string[]` type annotations on the local bindings —
  breaks the circular-inference path that the bare `Pair` cast
  triggered. Same fix at positionalForYamlNode.
- CLI-S03 in `src/commands/path.test.ts` failed asserting
  `gateway.jsonc` appeared in the sentinel error. Root cause: the
  F13 plumbing landed at emitForKind (the OUTER emit) but the
  sentinel throw originates INSIDE the per-kind setter via
  rebuildRaw → emitJsonc({mode:'render'}), which doesn't see the
  outer fileName. Threaded `path.file` through setJsoncOcPath →
  rebuildRaw → emitJsonc and through setJsonlOcPath → finalize →
  emitJsonl so internal render-mode emits also surface the file
  context (`oc://gateway.jsonc/[path]` instead of `oc:///[path]`).
  Yaml's setIn uses the yaml-lib serializer (not our emit), so no
  plumbing needed there. The jsonl finalize change also propagates
  `ast.lineEnding` through the synthetic `next` AST so CRLF
  preservation (F10) still holds after a structural edit.

Local: vitest path.test + yaml/jsonc/jsonl edit tests 70 passed;
oxlint --type-aware on changed files: 0 warnings, 0 errors.
@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@galiniliev

Copy link
Copy Markdown
Contributor

Maintainer Re-Review — Round 8 verification (9603e67)

Reviewer: @galiniliev
Prior review: Round 8 at 59c26f4 — 5 findings posted.
Recommendation: READY FOR /prepare-pr ✅


Round-8 Findings — All Verified Fixed

ID Finding Status Location
F1 formatOcPath nesting guard incomplete ✅ Fixed oc-path.ts:328-339 — guard for field-only structs
F2 isPattern not quote-aware ✅ Fixed oc-path.ts:559 — splitRespectingBrackets
F3 getPathLayout not quote-aware ✅ Fixed oc-path.ts:734-736 — all three slots
F4 locateYamlLine not quote-aware ✅ Fixed universal.ts:241-242 — quote-aware + unquote
F5 CLI find file-slot wildcards ✅ Fixed path.ts — early error OC_PATH_FILE_WILDCARD_UNSUPPORTED

No remaining unguarded .split('.') in oc-path.ts or universal.ts.

Security-Critical Fix Since Round 8

Path traversal sandbox escape (author self-review, BLOCKER) — parseOcPath and formatOcPath now both reject absolute file slots (/etc/passwd, C:\..., UNC) and parent-directory escapes (../). Quoted-segment unquoting was the gap — oc://"../foo"/x parsed cleanly. Symmetric defense at both boundaries. Verified clean.

Additional Hardening (rounds 9–15)

  • Sentinel errors now caught at CLI boundary (no commander escape)
  • path emit now respects --cwd/--file flags
  • Positional tokens ($first/$last/-N) fixed on edit paths for all kinds
  • resolveOcPath now throws structured error on wildcards (not silent null)
  • Format length cap, parser depth cap, JSONL walker depth guard
  • formatOcPath sub-segment validation (empty, control chars)
  • 16 self-review findings total, all closed with ~50 pinning tests

CI & Tests

  • CI: all checks passing, mergeable_state: clean
  • Tests: 694 substrate + 16 CLI (up from 678 + 14)

Scope Note

Still 86 files / 14,273 additions (XL). Entirely new surface — low regression risk. 15+ review rounds demonstrate convergence.

Verdict

All prior findings verified. Path-traversal security fix is solid. No new IMPORTANT findings. Ready for /prepare-pr.

@clawsweeper

clawsweeper Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@galiniliev
galiniliev merged commit bc735f4 into openclaw:main May 8, 2026
109 of 110 checks passed
@galiniliev

Copy link
Copy Markdown
Contributor

✅ Merged

Thanks @giodl73-repo for the thorough iteration across 15+ review rounds! 🦞

@giodl73-repo
giodl73-repo deleted the user/giodl/feat-shared-oc-path-resolver branch May 9, 2026 13:37
@galiniliev
galiniliev self-requested a review May 14, 2026 22:42
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…/jsonc/jsonl/yaml) (openclaw#78678)

Implements openclaw#78051 — oc:// addressing substrate for workspace files.

New src/oc-path/ substrate (parser/formatter, per-kind parse+emit for
md/jsonc/jsonl/yaml, universal resolveOcPath/setOcPath/findOcPaths verbs,
sentinel emit guard) + openclaw path resolve|find|set|validate|emit CLI +
docs/cli/path.md reference page + CHANGELOG entry.

Co-authored-by: giodl73-repo <[email protected]>
Co-authored-by: galiniliev <[email protected]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…/jsonc/jsonl/yaml) (openclaw#78678)

Implements openclaw#78051 — oc:// addressing substrate for workspace files.

New src/oc-path/ substrate (parser/formatter, per-kind parse+emit for
md/jsonc/jsonl/yaml, universal resolveOcPath/setOcPath/findOcPaths verbs,
sentinel emit guard) + openclaw path resolve|find|set|validate|emit CLI +
docs/cli/path.md reference page + CHANGELOG entry.

Co-authored-by: giodl73-repo <[email protected]>
Co-authored-by: galiniliev <[email protected]>
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
…/jsonc/jsonl/yaml) (openclaw#78678)

Implements openclaw#78051 — oc:// addressing substrate for workspace files.

New src/oc-path/ substrate (parser/formatter, per-kind parse+emit for
md/jsonc/jsonl/yaml, universal resolveOcPath/setOcPath/findOcPaths verbs,
sentinel emit guard) + openclaw path resolve|find|set|validate|emit CLI +
docs/cli/path.md reference page + CHANGELOG entry.

Co-authored-by: giodl73-repo <[email protected]>
Co-authored-by: galiniliev <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation maintainer Maintainer-authored PR proof: sufficient ClawSweeper judged the real behavior proof convincing. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants