Skip to content

refactor: one owner for report front matter, sections and escapeRegExp - #1788

Merged
obviyus merged 3 commits into
mainfrom
refactor/front-matter-owner
Oct 9, 2026
Merged

obviyus merged 3 commits into
mainfrom
refactor/front-matter-owner

Conversation

@obviyus

@obviyus obviyus commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What

There is now one owner for each part of report front-matter and section parsing:

  • src/report-front-matter.ts owns frontMatterField, frontMatterValue, frontMatterStringArray (plus parseFrontMatterStringArray for value-level reads), frontMatterJsonArray, frontMatterBoolean, replaceFrontMatterValue, sectionValue, replaceSectionValue and appendSectionValue.
  • src/clawsweeper-markdown.ts owns escapeRegExp. The repair router now uses markdownTopLevelSection, so its extractMarkdownSection copy is gone.
  • Deleted copies:
    • clawsweeper-record-metadata.ts: the factory methods.
    • decision-packets.ts: replaceFrontMatterValue.
    • repair/workflow-utils.ts: frontMatterField, frontMatterValue, jsonArrayFrontMatter and sectionValue.
    • repair/create-job.ts: frontMatterValue, frontMatterArray and sectionValue.
    • repair/target-fanout.ts: its regex-only frontMatterField.
    • repair/issue-implementation-intake.ts: frontMatterStringArray.
    • repair/comment-router-core.ts: extractMarkdownSection and its private fence helpers.
    • escapeRegExp in clawsweeper-text.ts and repair/text-utils.ts, plus four inline escape regexes.
  • These pure helpers were also injected through the dependency interfaces. Following the "pure functions are imported, never injected" rule, they are now imported. I removed:
    • all 63 dependency-interface members;
    • the ...recordMetadata wiring for these names in clawsweeper-runtime.ts;
    • the function parameters that passed them along (withRunnerPreflightProvenance, localExactBootstrapReviewCommentBody, the live-proof/attach.ts identity helpers and createApplyChangedSinceReviewMarker);
    • the test stubs.
  • Tests that faked front matter through stubs now put the values in real markdown front matter. test/clawsweeper-record-metadata.test.ts is renamed to test/report-front-matter.test.ts because it now tests only the owner.

Why

These audits found the duplicates:

  • SlopHelpers finding 2: front matter and sections are parsed 4–6 times, with a live $ substitution bug.
  • SlopDataModel finding 3: there are four parsers for one document format.
  • SlopRepair finding 1: extractMarkdownSection and escapeRegExp are copied between the repair and top-level code.

The copies already disagreed on fences, quotes and $ replacement patterns.

Behavior changes (every caller whose behavior changes)

When copies differed, the shared reader's semantics won, with one stricter choice (item 7).

  1. decision-packets.ts syncDecisionPacketRecord. It used markdown.replace(pattern, line), so $&, $` and $' in a packet path were expanded. They are now written literally (replacer function). New test: decision packet sync writes packet pointers literally and keeps CRLF headers. It fails on main (actual: false).

  2. replaceSectionValue / appendSectionValue. The record-metadata copy used `$1${value}` as the replacement string, so model text with $1/$& (shell snippets, for example) corrupted the section. Callers: promotion-facts, coverage-proof, apply-close-execution, failed-review-retry, live-proof/attach. The text is now written literally. The section heading is now regex-escaped; no shipped heading contains a metacharacter other than .. New test: section writes keep replacement patterns in model text literal. On main this returns "Run \echo"`.

  3. repair/target-fanout.ts summarizeFleetReviewCoverage. The old regex read review_status: / reviewed_at: from anywhere in the file, including fenced samples, and stripped single quotes. It now uses the fence- and ambiguity-aware reader. New test (added first): target fanout coverage ignores review metadata inside a fenced report sample. It fails on main with 1 !== 0.

  4. repair/workflow-utils.ts and repair/create-job.ts. Quote stripping changed from removing a leading and a trailing " separately to removing one matched pair. Absent values still read as "" at each call site (?? ""). Callers: apply-candidate selection, close-promotion signals, stale comment-sync selection, applyCheckedAtForItem, and create-job parseClawSweeperReport. A named variant was not needed, because no writer emits unpaired quotes.

  5. repair/create-job.ts list fields (work_cluster_refs, work_validation, work_likely_files). A valid JSON non-array (for example 42) now reads as ["42"] instead of [], which matches the shared frontMatterStringArray.

  6. repair/comment-router(-core).ts: reviewSummaryFromCommentBody, reviewFollowupFromCommentBody, beforeMergeReason/decisionNeededReason/trustedHumanReviewReason and the router's markdownSection now use markdownTopLevelSection. These forms are no longer read:

    • Heading: colon-style headings;
    • indented headings;
    • bare Label: lines as section boundaries.

    Null results are kept with || null. The test that pinned the colon form now asserts null.

  7. Quoted-empty values (key: "") are now ambiguous (fail closed) in the shared reader. Before, record-metadata read them as an empty value and the repair copy read them as ambiguous. The repair promotion test (workflow empty and quoted-empty ratings remain ambiguous) pins the fail-closed behavior. In the main lane, an empty value was already invalid for every enum reader, so it still fails closed.

  8. CRLF packet insertion. The shared writer inserts a new key after ---\r?\n and uses the same line ending, so CRLF reports keep their packet pointers (Codex P2).

Proof

  • pnpm run check exits 0 on this head after rebasing onto main 3ef195d (refactor: own stringOrUndefined helpers in value-coerce #1782, refactor: own ISO timestamp helpers in iso-time #1786 and refactor: route sha256 hex digests through content-hash #1790). Both coverage runs report ℹ fail 0. When I resolved the conflicts, I dropped every dependency-interface and destructure line that either side deleted.
  • Definition counts on main → branch:
    • frontMatterField 3 → 1, frontMatterValue 3 → 1, frontMatterStringArray 2 → 1;
    • replaceFrontMatterValue 2 → 1, sectionValue 3 → 1;
    • extractMarkdownSection 1 → 0 (it uses the existing markdownTopLevelSection), escapeRegExp 2 → 1;
    • inline escape regexes 7 → 1;
    • front-matter/section DI interface members 63 → 0.
    • Diff vs main: 100 files changed, 463 insertions(+), 752 deletions(-).
  • Shipped-consumer regressions, base vs head. /tmp/h2-consumer-proof.mjs (fixture script, not committed) runs the real consumers from each dist:
    • Apply record writer. createApplyRecordOperations(...).writeReportMarkdown is the apply path that persists a report and syncs its decision packet. The fixture uses a record root named team$&-$'-$`.
      • Base (main before this PR): writes decision_packet_path: team--- → FAIL.
      • Head: writes decision_packet_path: team$&-$'-$`/openclaw-openclaw/decision-packets/321.json → PASS.
    • Fleet coverage. summarizeFleetReviewCoverage is the function that target-fanout coverage calls. The fixture report has review_status: complete / reviewed_at only inside a fenced YAML sample.
      • Base: scanned=1 percent=100 → FAIL.
      • Head: scanned=0 percent=0 → PASS.
    • I did not run the target-fanout coverage CLI itself. Before it calls this function, it loads eligible repositories and live open counts from GitHub.
  • Render identity. Every saved real report was re-rendered with main dist and branch dist through render-comments.mjs: prompt-rest, prompt-lean, prompt-dump, async-proof/{base,branch}, retire-proof/166090, /tmp/rules-slice/{reports,reports-leased,run-144991,run-167362}. That is 15 reports in 10 directories. All 10 outputs are byte-identical.
  • Router section equivalence. I compared main's extractMarkdownSection with the branch's markdownTopLevelSection(...) || null for the 10 router headings. The bodies were 618 real ClawSweeper comments from openclaw/openclaw (issues/comments, newest 1000) and the 15 rendered comments. Result: 6330 lookups, 1008 sections found, 0 differences.
  • Front-matter reader equivalence. On the 15 saved reports, I compared the old workflow-utils, create-job and target-fanout readers, the unescaped record-metadata sectionValue and the escaped repair sectionValue against the owner, for every key and ## heading. Result: 5150 reads, 0 differences.

Codex review dispositions

  • [P2] Keep CRLF support when inserting packet metadata: fixed. The writer keeps the delimiter's line ending, and the packet test covers a CRLF report.
  • [P3] Migrate docs/proof/record-front-matter-literal-write to the shared exports: declined. That directory is a frozen proof for an already merged PR. Its before/after harness compiles the module at that PR's merge base, so it cannot be re-run on current main with or without this change.

Not in this PR

  • repair/issue-implementation-intake.ts still parses its own Record<string,string> front matter and has a case-insensitive section() helper. Only its string-list decoder moved to the owner.
  • commit-sweeper.ts and comment-router-core.ts job-file writers edit a different document type (commit records and repair jobs), so they are not changed.

Merge Danger

  • Door: two-way. This is a pure refactor plus the fixes listed above. Revert is clean.

  • Blast radius:

    • Report front-matter reads and writes in the apply, review, label, dashboard and live-proof lanes.
    • Repair router section parsing.
    • Fleet coverage counts.

    Shared-file hunks in clawsweeper-runtime.ts and the *-dependencies.ts files only remove members, so they may conflict on nearby lines with the parallel asRecord/stringOrUndefined slice.

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The branch centralizes Markdown report headers and sections, preserves dollar characters in stored text, and excludes fenced examples from review coverage counts.

Example: An operator checks coverage for one report containing completion metadata only in a fenced example.

  • Before: Coverage reports scanned=1 and percent=100.
  • After: Coverage reports scanned=0 and percent=0.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful consolidation with no identified defect, supported by consumer observations whose execution remains in-process.
Proof confidence 🦐 gold shrimp (3/6) Verified repository maintain access exempts this PR from the external-contributor gate. The body demonstrates corrected compiled record-writer and coverage-consumer outputs through in-process fixtures, with saved-report compatibility comparisons; shipped CLI execution is not demonstrated. The stored format is unchanged and no migration is required.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes
User problem: Stored review instructions and decision-packet paths can be corrupted by dollar patterns, and fenced examples can inflate review coverage.
Reason: The consolidation repairs demonstrated data-handling errors and removes duplicate owners with a net reduction in production code. The body explains the limited decoding changes and supplies compatibility comparisons.

Merge readiness

✅ Ready for maintainer review

This PR contributes useful work still absent from current main. Inspection found no actionable introduced defect, and the earlier CRLF concern is addressed.

Priority: P2
Reviewed head: 0b9a2e98e1c7fff747d1d33e5d58e4037694e566

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied observations run compiled consumers directly rather than the shipped apply and target-fanout CLI entry points; reported base/head results were not independently rerun.
Agent review details

How this fits together

ClawSweeper stores review decisions in Markdown reports with a leading metadata header. Review, repair, apply, and dashboard consumers read these reports to display results and select permitted work.

flowchart TD
  A[Review decisions and text] --> B[Stored Markdown reports]
  B --> C[Shared header and section helpers]
  C --> D[Metadata ambiguity checks]
  D --> E[Review and repair consumers]
  D --> F[Apply safety checks]
  C --> G[Coverage summaries and comments]
Loading

Technical review

Best possible solution:

Keep one shared report owner that preserves structural ambiguity checks and writes stored text literally.

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

Yes: current main's replacement-string writers establish the dollar-expansion failure, and its unrestricted coverage regex accepts fenced metadata. The PR supplies failing-base and passing-head consumer observations; this review did not execute a reproduction.

Is this the best way to solve the issue?

Yes: routing callers through the existing structural owner removes competing implementations and repairs literal writes without introducing another parsing layer or stored format.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7b0c589b7335.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Applicable repository policy: Read the full root AGENTS.md; no nested policies or matching maintainer-notes directory were found. Applied report ownership, changelog, read-only review, and proof guidance. (AGENTS.md:1, 0b9a2e98e1c7)
  • Literal writes and conservative decoding: The shared writer uses replacement functions, insertion preserves the opening delimiter's line ending, and quoted-empty fields remain ambiguous. Existing duplicate-key, competing-record, and fenced-example structural checks are retained. (src/report-front-matter.ts:90, 0b9a2e98e1c7)
  • Work remains necessary on current main: Pinned main still writes decision-packet paths as replacement strings, writes section content with replacement-string interpolation, and scans fleet metadata with an unrestricted regex. The related merged helper refactors do not repair these paths. (src/decision-packets.ts:414, 7b0c589b7335)
  • Observed consumer results: The fully inspected PR body reports compiled production-consumer observations: packet paths preserve dollar patterns, and fenced-only completion metadata changes coverage from scanned=1/percent=100 to scanned=0/percent=0. It explicitly says the coverage CLI was not run. Captured body source identity: 6dd3401fa266f82db424f657526ad3a84b23f47c4a1af550977d47c44ff8939d. (0b9a2e98e1c7)
  • Existing-record compatibility: The persisted report shape and keys are unchanged. The body reports byte-identical rendering of saved reports, zero differences across 6,330 router section lookups, and zero differences across 5,150 report reads; its enumerated decoding changes concern malformed or unsupported forms. No Bay schema or navigation change is introduced. (src/report-front-matter.ts:23, 0b9a2e98e1c7)
  • Author proof-policy classification verified: Although REST reports CONTRIBUTOR association, the repository permission endpoint confirms obviyus has the maintain role and write permission, supporting the supplied trusted-author classification.

Likely related people:

  • Dwin Gharibi: Raw commit ced376c adds src/report-front-matter.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ced376c34353; files: src/report-front-matter.ts)
  • Peter Steinberger: Raw commit 05c662b adds src/clawsweeper-markdown.ts:37 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 05c662bd74e1; files: src/clawsweeper-markdown.ts)

Review metrics

Metric Value Why it matters
Production and test size production +292/-561; tests +168/-184 Consolidation removes 269 production lines while retaining focused corruption and coverage regressions.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Stored-text corruption and incorrect fleet coverage are bounded correctness problems without evidence of an urgent outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-09T06:06:23.141Z sha e8b9033 :: needs changes before merge. :: none
  • reviewed 2026-10-09T06:26:19.366Z sha 56dd14a :: needs maintainer review before merge. :: none

Reviewed October 9, 2026, 3:12 AM ET / 07:12 UTC (Revision 3).

@obviyus
obviyus force-pushed the refactor/front-matter-owner branch from e8b9033 to 56dd14a Compare October 9, 2026 06:22
@obviyus

obviyus commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 9, 2026
@obviyus
obviyus force-pushed the refactor/front-matter-owner branch from 56dd14a to 0b9a2e9 Compare October 9, 2026 07:08
@obviyus

obviyus commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant