Repository navigation
feat: deterministic AI report rendering with validated judgment - #314
Conversation
172e162 to
be3638c
Compare
jflowers
left a comment
There was a problem hiding this comment.
Verdict: APPROVE WITH ADVISORIES — all 7 reviewer runs completed; 19 findings (5 MEDIUM, 14 LOW, 0 HIGH, 0 CRITICAL).
CI and pre-flight
All six checks pass: Gaze AI Report, MegaLinter, Unit + Integration Tests (Go 1.24 / Go 1.25), E2E Tests (Go 1.24 / Go 1.25). Pre-flight ran in ci-aware mode and skipped go build, go test, and golangci-lint locally because each maps to a passing CI check; the local checkout is also not the PR head, so a local run would test a different tree.
What the change does
gaze report stops publishing whatever the model streams and instead renders every section, table, grade, and deterministic recommendation itself from the analysis payload; the model supplies only a validated summary + recommendations payload. A malformed or non-English answer fails the run while the deterministic report and a rejection callout still publish. Spec 040's 40 functional requirements trace cleanly to implementation: the three mirror pairs (.opencode/ ↔ internal/scaffold/assets/) are byte-identical by git blob hash, the FR-032 prompt reduction (528 → 138 lines) checks out from hunk headers, and the File Sync Invariants row removed by FR-024 is a spec-authorized change recorded in the AGENTS.md change log with the remaining gates left byte-identical.
MEDIUM findings
-
GFM autolinking bypasses the header/prose escapers —
internal/aireport/render_markdown.go:77.headerEscaperandproseEscaperescape brackets, angle brackets, pipes, and backticks, but GFM extended autolinking still turns a barewww.domain or email address into a clickable link when preceded by a space — whichProject: <value>andBranch: <value>always supply.Branchcomes fromGITHUB_HEAD_REF/GITHUB_REF_NAME, andwww.evil.exampleis a legal git ref, so a PR author can plant a clickable attacker-chosen link in the GitHub Step Summary. The AI-answer channel'sruleMarkupalready banswww.and://; that class is blocked in one channel and open in the others writing into the same artifact. No test pins the escaper's stated invariant. -
Both sanitizers ship with most of their contract untested —
internal/aireport/render_markdown.go:77and:187.TestRenderMarkdown_MetadataEscapedasserts only the[,],<,>pairs; 8 ofheaderEscaper's 12 replacement pairs and all three newline-flattening entries have no assertion.TestRenderMarkdown_HostileDataEscapedinjects multi-line input but asserts only[ ] <, never the flattening that prevents block-structure injection. Replacer order (\r\nbefore\r/\n) is also uncaught. A regression dropping the line-break flattening would allow heading or block injection into the report and the Step Summary with no failing test. -
-mwiring is asserted only by value presence —internal/aireport/adapter_opencode_test.go.TestOpenCodeAdapter_ModelFlagPassedasserts the model string appears somewhere in captured argv but never that-mprecedes it. BecauseopenCodeArgsappends-mand the model as separate entries, a regression dropping-mleaves every test green — whileTestOpenCodeAdapter_NoModelFlag_Succeedsdoes check the flag's absence, confirming the intent is wiring. -
FR-014's deny-all invariant has no regression protection —
internal/aireport/adapter_opencode_test.go.TestOpenCodeAdapter_AgentFileIsToolFreeasserts four substrings (description,mode: primary,"*": deny, system prompt) but never that no allow rule exists. Appendingbash: allowafter"*": denypasses both this test andfake_opencode's substring check, while the agent can run tools. FR-014 makes this a MUST. The Go test is additionallytesting.Short()-guarded, so the short suite relies only on the fake binary. -
Package cohesion drifts at the advisory band —
internal/aireport. vibe-check between basee7f23b5cand head172e1628measures LCOM4 6→7 (Δ+1), Ce 32→34 (Δ+2), exported types 15→25. Six new type-disjoint clusters (answer.go, assess.go, grade.go, sections.go, opencode_events.go, render_markdown.go — roughly 2,400 lines) register as an additional disconnected component; the ΔCe decomposes tounicode,unicode/utf8,strconvadded andsyncremoved. Every REQUEST CHANGES gate stays uncrossed (ΔLCOM 1 < 2, instability +0.0017 < 0.15, distance improved, no new cycles) — worth discussing, not blocking.
LOW findings
- Silent stream degradation —
internal/aireport/opencode_events.go:95.parseEventsdiscards non-JSON lines without surfacing a skip count, so a mostly-corrupt stream that still yields one answer produces no diagnostic signal. - Inconsistent failure semantics on the external-analyzer path —
cmd/gaze/main.go:2600.runExternalReporthard-errors whenapplyExternalReportCRAPfails, aborting before any report is written, while native CRAP and the external quality/classification/docscan steps record a step error and render a warning callout. FR-004 asks for the callout behavior; this path is the sole remaining hard-fail. - Unwired
gazeVersionseam —cmd/gaze/main.go:2165/:2166. No production path or test assignsreportParams.gazeVersion;reportMetadataalways passes the zero value andbuildReportMetadatafalls back to theversionconstant. The widermetadata *ReportMetadataoverride subsumes it. Remove it or wire a test (CS-002 zero-waste). codeSpanpadding branch untested —internal/aireport/assess.go:507. No fixture has a value that begins or ends with a backtick, so the CommonMark space-padding path is unreachable from the suite.- Zero-tally recommendation branch untested —
internal/aireport/assess.go:482. Thetotal == 0guard has no regression protection. - Mixed-stream
parseEventsresilience unverified —internal/aireport/opencode_events.go:111.not_json.txtcovers only the all-junk fail-closed path; nothing mixes valid events with junk lines, andcontracts/opencode-adapter.mdsays skipped lines are counted but no count is produced. - Test-quality gaps in the new suites —
render_markdown_test.go(metadata escaping pins only[ ] < >;CellEscapingbuilds its expectation with the production helper, making the truncation assertion vacuous),assess_test.go(fixStrategyTextdefault branch),cmd/gaze/external_analyzer_test.go(all-zeroClassificationCountstreated as a real result, but the only success assertion requires sum > 0),cmd/gaze/main_test.go(five-plusgo buildcalls in the short suite — TC-011).
Convention references: TC-009 (assert specific values), TC-011 (testing.Short() for subprocess tests), CS-002 (zero-waste), FR-004/FR-014 (spec MUSTs).
Notes
The five MEDIUM items are advisories, not merge blockers. The dogfood gaze-ai-report job installs a pinned released gaze version, so CI does not exercise this code path until a release ships it and the gaze-version input is bumped (issue #313) — closing findings 2, 3, and 4 before that bump is worthwhile.
This review was generated by /uf.review-pr (AI-assisted).
Escaping markup alone does not stop GFM extended autolinking: cmark-gfm resolves backslash escapes before its autolink postprocessor, so a bare "www." domain, "scheme://" URL, or dotted email in a crafted branch name or analysis-derived value stays clickable in a Step Summary. All three sanitizers now defang the full trigger class before escaping by inserting brackets ("www[.]", "[:]//", "x[@]y"), which breaks the autolink grammar at both the source and rendered level; code-span table names stay verbatim because GFM never autolinks span content. Negative tests assert on the emitted bytes, and a table-driven test now pins all twelve headerEscaper pairs exactly, including the CR-LF-before-CR/LF replacer ordering that the new-line clause of the escaper invariant previously relied on untested. Addresses PR unbound-force#314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
The opencode adapter contract says lines that fail to unmarshal are "skipped and counted", but parseEvents discarded them silently, so a mostly-corrupt stream yielding one decodable answer succeeded with no signal that parsing degraded. parseEvents now counts unmarshal failures and threads the count through extractFinalText: the zero-events error and the errNoFinalText sentinel (still matched with errors.Is) carry the count, and the success path logs a warning. A mixed-junk regression test pins the tolerance half of the contract too: junk, wrong-shape JSON, and CRLF-framed noise skip without discarding their neighboring events. Addresses PR unbound-force#314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
codeSpan's CommonMark space-padding branch for backtick-terminated names was unreachable from the suite, and longestBacktickRun had no direct tests; exact-literal tables now cover every backtick-position class. The boundary arms of ambiguousClassificationRecommendation (zero tallies with classification present, a nonzero ambiguous minority, and an exact tie) now have dedicated no-recommendation cases, so a less-or-equal-to less-than regression can no longer emit a spurious "50.0%" recommendation unchallenged. Addresses PR unbound-force#314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
Spec, plan, research, data model, contracts, quickstart and tasks for Go-rendered gaze report markdown with a validated AI judgment-slot contract (fixes CI Step Summary containing only agent narration). Includes spec-review council lesson learnings.
… 040)
Gaze now renders every report section, table, grade, and deterministic
recommendation itself. The AI adapter supplies only a plain-prose summary
and prioritized recommendations as one strict JSON object, validated by a
single shared validator before rendering.
- new internal/aireport/{sections,grade,assess,render_markdown,answer,opencode_events}.go
- gaze report --format=markdown (no AI provider) and --sections
- rubric v1 grades in JSON assessment and the Overall Health section
- tool-free gaze-headless opencode agent, --format json final-text extraction
- /gaze rewritten as a thin consumer (528 -> 138 lines, -73.3% tokens)
- agents/gaze-reporter.md is now tool-owned; local copy ignored by gaze report
- external analyzers build the quality/classification sections via test_mapping
Code review iteration 1 fixes: independent external step gating, LCOM
cohesion (6->7), prose escaping, GoDoc, metadata tests, caller context,
deduplicated markdown path.
Protects dogfood gates 38/6/8 (CRAPload 23, GazeCRAPload 6, avgCC 4.93).
…ation, external classify, codeSpan)
- Check off T081 (review council reached APPROVE WITH ADVISORIES after three iterations) and T082 (PR description prepared) in spec 040 tasks.md Assisted-by: DeepSeek-V4.1-Flash-1017 Generated with AI assistance (DeepSeek-V4.1-Flash-1017)
Escaping markup alone does not stop GFM extended autolinking: cmark-gfm resolves backslash escapes before its autolink postprocessor, so a bare "www." domain, "scheme://" URL, or dotted email in a crafted branch name or analysis-derived value stays clickable in a Step Summary. All three sanitizers now defang the full trigger class before escaping by inserting brackets ("www[.]", "[:]//", "x[@]y"), which breaks the autolink grammar at both the source and rendered level; code-span table names stay verbatim because GFM never autolinks span content. Negative tests assert on the emitted bytes, and a table-driven test now pins all twelve headerEscaper pairs exactly, including the CR-LF-before-CR/LF replacer ordering that the new-line clause of the escaper invariant previously relied on untested. Addresses PR unbound-force#314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
The opencode adapter contract says lines that fail to unmarshal are "skipped and counted", but parseEvents discarded them silently, so a mostly-corrupt stream yielding one decodable answer succeeded with no signal that parsing degraded. parseEvents now counts unmarshal failures and threads the count through extractFinalText: the zero-events error and the errNoFinalText sentinel (still matched with errors.Is) carry the count, and the success path logs a warning. A mixed-junk regression test pins the tolerance half of the contract too: junk, wrong-shape JSON, and CRLF-framed noise skip without discarding their neighboring events. Addresses PR unbound-force#314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
codeSpan's CommonMark space-padding branch for backtick-terminated names was unreachable from the suite, and longestBacktickRun had no direct tests; exact-literal tables now cover every backtick-position class. The boundary arms of ambiguousClassificationRecommendation (zero tallies with classification present, a nonzero ambiguous minority, and an exact tie) now have dedicated no-recommendation cases, so a less-or-equal-to less-than regression can no longer emit a spurious "50.0%" recommendation unchallenged. Addresses PR unbound-force#314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
e1c72e7 to
2e4e1d1
Compare
Escaping markup alone does not stop GFM extended autolinking: cmark-gfm resolves backslash escapes before its autolink postprocessor, so a bare "www." domain, "scheme://" URL, or dotted email in a crafted branch name or analysis-derived value stays clickable in a Step Summary. All three sanitizers now defang the full trigger class before escaping by inserting brackets ("www[.]", "[:]//", "x[@]y"), which breaks the autolink grammar at both the source and rendered level; code-span table names stay verbatim because GFM never autolinks span content. Negative tests assert on the emitted bytes, and a table-driven test now pins all twelve headerEscaper pairs exactly, including the CR-LF-before-CR/LF replacer ordering that the new-line clause of the escaper invariant previously relied on untested. Addresses PR #314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
The opencode adapter contract says lines that fail to unmarshal are "skipped and counted", but parseEvents discarded them silently, so a mostly-corrupt stream yielding one decodable answer succeeded with no signal that parsing degraded. parseEvents now counts unmarshal failures and threads the count through extractFinalText: the zero-events error and the errNoFinalText sentinel (still matched with errors.Is) carry the count, and the success path logs a warning. A mixed-junk regression test pins the tolerance half of the contract too: junk, wrong-shape JSON, and CRLF-framed noise skip without discarding their neighboring events. Addresses PR #314 review feedback from @jflowers. Signed-off-by: Jay Flowers <[email protected]> Assisted-by: glm-5
Summary
Fixes a governance failure where
gaze reportcould publish whatever the AI model streamed as the quality report. In CI run41309423609 the Gaze AI Report Step Summary contained only model narration — English, then Chinese code-switching — and no report at all, while the job exited green.
Gaze now renders every section, table, grade, and deterministic recommendation itself, and the AI supplies only a validated judgment payload. A malformed or non-English answer fails the run, while the deterministic report and a rejection callout are still published. This lands as spec 040 (
specs/040-deterministic-ai-report-rendering/, 82 tasks, 8 phases, 5 user stories).internal/aireport/render_markdown.go,grade.go(rubric v1),assess.go(five fixed scorecard rows, ≤8 recommendations),sections.go(SectionSet). Identical data produces byte-identical output outside the AI slots.gaze report --format=markdownneeds no adapter or API key. JSON gainsmetadataandassessment, so the markdown grades and the machine-readable contract are the same data (SC-005).assets/report-mode-prompt.mdreplaces the per-project prompt; oneParseAIAnswervalidator (14 normative rules: 1,200-char summary, 1–5 recommendations ≤400 chars, 5% non-Latin) gates every adapter. The OpenCode adapter runs a tool-freegaze-headlessagent with--format jsonand extracts only the final assistant text, failing closed on a completed tool, an error event, or no events./gazebecomes a thin consumer — the agent runsgaze report --format=markdown, shows it verbatim, and adds one## Assessment. DE-004: 528 lines / 2,965 words / ≈5,118 tokens → 138 lines / 774 words / ≈1,364 tokens (−73.9% lines, −73.3% tokens).test_mapping, the report builds the quality section,Summary.AvgContractCoverage, and classification counts from the same data; each section is gated independently, and a degradation renders> ⚠️ Quality analysis unavailable:instead of a header-only report.Release notes / behavior changes
gaze reportnow ignores.opencode/agents/gaze-reporter.mdand prints a one-line notice when it exists; it always uses the built-in report-mode prompt.gaze initnow treats.opencode/agents/gaze-reporter.mdas tool-owned: it is overwritten when it differs and reported asupdated. Local customizations to that agent will be lost — keep project-specific instructions in your own agent files.commands/gaze.mdremains user-owned.How to Test
How to Demo
gaze report --format=markdown ./...in a terminal or the GitHub Step Summary — show that every table, grade, and recommendation comes from Gaze, with no AI slots.diff— identical bytes.go test -race -count=1 -run TestIncident ./internal/aireport/) and show the non-zero exit, the> ⚠️ AI narrative rejected:callout, and the fully published deterministic report./gaze,/gaze crap ./internal/crap,/gaze quality ./internal/quality— verbatim rendered report, then a short## Assessment.Key Files Changed
internal/aireport/render_markdown.go,grade.go,assess.go,sections.go— deterministic renderer, rubric v1, assessment, section selection.internal/aireport/answer.go,opencode_events.go,assets/report-mode-prompt.md— one AI answer validator, OpenCode event extraction, embedded tool-free prompt.internal/aireport/runner.go,payload.go,compact.go,prompt.go— always-publish text path,errors.Join,metadata/assessment, embedded prompt accessor, legacy prompt removal.cmd/gaze/main.go—--format=markdown,--sections, metadata, ignore notice, external-analyzer quality parity.internal/scaffold/scaffold.go+.opencode/agents/gaze-reporter.md(+ byte-identical scaffold mirror),.opencode/references/example-report.md,.opencode/commands/gaze.md.docs/reference/cli/report.md(format matrix, validation errors, AI answer contract, ignore notice, JSON additions, grading rubric),docs/guides/ci-integration.md,docs/guides/ai-reports.md,docs/guides/opencode-integration.md,docs/reference/cli/init.md,README.md,AGENTS.md.internal/aireport/testdata/golden/(8 files),internal/aireport/testdata/opencode_streams/(9 fixtures),internal/aireport/golden_helpers_test.go,incident_test.go, renderer/validator/adapter replay tests,cmd/gazegolden + round-trip tests,baseline.md.Known Issues
parseEventsskip-count is not surfaced;codeSpanspace-padding/multi-run andheaderEscapernewline/backslash/asterisk/underscore/pipe branches are untested; the zero-tally classification success path lacks a regression test;reportParams.gazeVersionis an unused seam.gaze-ai-reportjob installs a pinned releasedgazeversion, so it will not exercise this code until a release ships it and the caller/gaze-versioninput is bumped — tracked in ci: bump reusable_gaze_ai_report gaze-version to the first release with deterministic report rendering (spec 040 SC-008) #313.Follow-ups
gaze-versionafter release (SC-008).This PR was generated by /uf.finale (AI-assisted).