Skip to content

feat: deterministic AI report rendering with validated judgment - #314

Merged
jflowers merged 8 commits into
unbound-force:mainfrom
jflowers:040-deterministic-ai-report-rendering
Nov 3, 2026
Merged

jflowers merged 8 commits into
unbound-force:mainfrom
jflowers:040-deterministic-ai-report-rendering

Conversation

@jflowers

@jflowers jflowers commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes a governance failure where gaze report could publish whatever the AI model streamed as the quality report. In CI run
41309423609 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).

  • Deterministic rendering — new 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.
  • No-AI report — gaze report --format=markdown needs no adapter or API key. JSON gains metadata and assessment, so the markdown grades and the machine-readable contract are the same data (SC-005).
  • Validated AI judgment — an embedded, tool-free assets/report-mode-prompt.md replaces the per-project prompt; one ParseAIAnswer validator (14 normative rules: 1,200-char summary, 1–5 recommendations ≤400 chars, 5% non-Latin) gates every adapter. The OpenCode adapter runs a tool-free gaze-headless agent with --format json and extracts only the final assistant text, failing closed on a completed tool, an error event, or no events.
  • /gaze becomes a thin consumer — the agent runs gaze 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).
  • External-analyzer parity — when an analyzer advertises 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 report now ignores .opencode/agents/gaze-reporter.md and prints a one-line notice when it exists; it always uses the built-in report-mode prompt.
  • gaze init now treats .opencode/agents/gaze-reporter.md as tool-owned: it is overwritten when it differs and reported as updated. Local customizations to that agent will be lost — keep project-specific instructions in your own agent files. commands/gaze.md remains user-owned.

How to Test

go build -o "${TMPDIR:-/tmp}/gaze" ./cmd/gaze

# 1. Deterministic full report, no AI provider or key
"${TMPDIR:-/tmp}/gaze" report --format=markdown ./...

# 2. Same data twice → byte-identical (SC-002/SC-009)
"${TMPDIR:-/tmp}/gaze" report --format=markdown ./internal/crap > /tmp/r1.md
"${TMPDIR:-/tmp}/gaze" report --format=markdown ./internal/crap > /tmp/r2.md
diff /tmp/r1.md /tmp/r2.md && echo IDENTICAL

# 3. Grades are in the machine-readable contract too (SC-005)
"${TMPDIR:-/tmp}/gaze" report --format=json ./... | jq .assessment

# 4. Section selection + pre-analysis validation
"${TMPDIR:-/tmp}/gaze" report --format=markdown --sections=crap ./internal/crap
"${TMPDIR:-/tmp}/gaze" report --format=markdown --sections=bogus ./...   # rejects before analysis

# 5. Threshold failure still publishes the report, then exits non-zero
"${TMPDIR:-/tmp}/gaze" report --format=markdown --max-crapload=0 ./internal/crap; echo "exit=$?"

# 6. Incident regression (narration/CJK replay exits non-zero with a rejection callout)
go test -race -count=1 -run 'TestIncident|TestRunReport_IncidentReplay' ./internal/aireport/ ./cmd/gaze/

# 7. Scaffold propagation (the /gaze agent is now tool-owned)
d=$(mktemp -d); (cd "$d" && go mod init example.com/x >/dev/null && gaze init && \
  echo "# custom" >> .opencode/agents/gaze-reporter.md && gaze init | grep 'updated: .opencode/agents/gaze-reporter.md')

How to Demo

  1. 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.
  2. Run it twice and diff — identical bytes.
  3. Replay the incident stream (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.
  4. In OpenCode, /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.
  • Tests/fixtures: 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/gaze golden + round-trip tests, baseline.md.

Known Issues

  • Eight LOW advisories from the final council pass are recorded and intentionally deferred: parseEvents skip-count is not surfaced; codeSpan space-padding/multi-run and headerEscaper newline/backslash/asterisk/underscore/pipe branches are untested; the zero-tally classification success path lacks a regression test; reportParams.gazeVersion is an unused seam.
  • The dogfood gaze-ai-report job installs a pinned released gaze version, so it will not exercise this code until a release ships it and the caller/gaze-version input 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.
  • Entropy metrics moved slightly and stay well inside gates (internal/aireport LCOM 6→7 vs Δ≥2 gate; Ce 32→34; instability +0.0017; distance 0.1030→0.0514).

Follow-ups


This PR was generated by /uf.finale (AI-assisted).

@jflowers jflowers self-assigned this Nov 2, 2026
@jflowers
jflowers force-pushed the 040-deterministic-ai-report-rendering branch from 172e162 to be3638c Compare November 2, 2026 19:33

@jflowers jflowers left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. GFM autolinking bypasses the header/prose escapers — internal/aireport/render_markdown.go:77. headerEscaper and proseEscaper escape brackets, angle brackets, pipes, and backticks, but GFM extended autolinking still turns a bare www. domain or email address into a clickable link when preceded by a space — which Project: <value> and Branch: <value> always supply. Branch comes from GITHUB_HEAD_REF/GITHUB_REF_NAME, and www.evil.example is a legal git ref, so a PR author can plant a clickable attacker-chosen link in the GitHub Step Summary. The AI-answer channel's ruleMarkup already bans www. 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.

  2. Both sanitizers ship with most of their contract untested — internal/aireport/render_markdown.go:77 and :187. TestRenderMarkdown_MetadataEscaped asserts only the [, ], <, > pairs; 8 of headerEscaper's 12 replacement pairs and all three newline-flattening entries have no assertion. TestRenderMarkdown_HostileDataEscaped injects multi-line input but asserts only [ ] <, never the flattening that prevents block-structure injection. Replacer order (\r\n before \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.

  3. -m wiring is asserted only by value presence — internal/aireport/adapter_opencode_test.go. TestOpenCodeAdapter_ModelFlagPassed asserts the model string appears somewhere in captured argv but never that -m precedes it. Because openCodeArgs appends -m and the model as separate entries, a regression dropping -m leaves every test green — while TestOpenCodeAdapter_NoModelFlag_Succeeds does check the flag's absence, confirming the intent is wiring.

  4. FR-014's deny-all invariant has no regression protection — internal/aireport/adapter_opencode_test.go. TestOpenCodeAdapter_AgentFileIsToolFree asserts four substrings (description, mode: primary, "*": deny, system prompt) but never that no allow rule exists. Appending bash: allow after "*": deny passes both this test and fake_opencode's substring check, while the agent can run tools. FR-014 makes this a MUST. The Go test is additionally testing.Short()-guarded, so the short suite relies only on the fake binary.

  5. Package cohesion drifts at the advisory band — internal/aireport. vibe-check between base e7f23b5c and head 172e1628 measures 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 to unicode, unicode/utf8, strconv added and sync removed. 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. parseEvents discards 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. runExternalReport hard-errors when applyExternalReportCRAP fails, 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 gazeVersion seam — cmd/gaze/main.go:2165/:2166. No production path or test assigns reportParams.gazeVersion; reportMetadata always passes the zero value and buildReportMetadata falls back to the version constant. The wider metadata *ReportMetadata override subsumes it. Remove it or wire a test (CS-002 zero-waste).
  • codeSpan padding 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. The total == 0 guard has no regression protection.
  • Mixed-stream parseEvents resilience unverified — internal/aireport/opencode_events.go:111. not_json.txt covers only the all-junk fail-closed path; nothing mixes valid events with junk lines, and contracts/opencode-adapter.md says skipped lines are counted but no count is produced.
  • Test-quality gaps in the new suites — render_markdown_test.go (metadata escaping pins only [ ] < >; CellEscaping builds its expectation with the production helper, making the truncation assertion vacuous), assess_test.go (fixStrategyText default branch), cmd/gaze/external_analyzer_test.go (all-zero ClassificationCounts treated as a real result, but the only success assertion requires sum > 0), cmd/gaze/main_test.go (five-plus go build calls 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).

Comment thread internal/aireport/render_markdown.go Resolved
Comment thread internal/aireport/render_markdown.go Resolved
Comment thread internal/aireport/opencode_events.go Resolved
Comment thread internal/aireport/opencode_events.go Resolved
Comment thread internal/aireport/assess.go Resolved
Comment thread internal/aireport/assess.go Resolved
jflowers added a commit to jflowers/gaze that referenced this pull request Nov 2, 2026
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
jflowers added a commit to jflowers/gaze that referenced this pull request Nov 2, 2026
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
jflowers added a commit to jflowers/gaze that referenced this pull request Nov 2, 2026
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).
- 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
@jflowers
jflowers force-pushed the 040-deterministic-ai-report-rendering branch from e1c72e7 to 2e4e1d1 Compare November 3, 2026 18:17
@jflowers
jflowers merged commit fe28ce6 into unbound-force:main Nov 3, 2026
6 checks passed
jflowers added a commit that referenced this pull request Nov 3, 2026
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
jflowers added a commit that referenced this pull request Nov 3, 2026
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
@jflowers
jflowers deleted the 040-deterministic-ai-report-rendering branch November 15, 2026 20:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant