console: refuse unclosed and unbalanced legal fragments
An input ending inside a tag was silently dropped by the tokenizer and accepted. Count raw token bytes and refuse a shortfall, refuse unbalanced or unclosed elements, and mask Unicode format characters in error names.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
internal/console/legalfetch.go+27 −3internal/console/legalfetch_test.go+13 −0
Intent
<task-notification> <task-id>a1fffac0df555cda2</task-id> <tool-use-id>toolu_013V5HGBmWbT7yEzeicCmPCB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a1fffac0df555cda2.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: dpaInForce" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE Commit: 420ec0f8 "console: dpaInForce decides each account's DPA version" (the packed-refs.lock message appeared, but `git log -1` shows the commit) Tests: `TestDPAInForce` has 16 subtests and all pass. It failed to build before the implementation (RED), and the same command passes after (GREEN). `go build ./...`, `go vet ./internal/console/` and `gofmt -l` are clean. Subtests: the brief's 8 cases plus these 8: - Delivered exactly 30 days ago. - A nil lookup. - Out-of-order input. - Earlier documents ignored. - A nil `EffectiveAt`. - Other kinds ignored. - Accepted document missing: three cases. Concerns: none. Go commands needed the sandbox disabled because of the read-only go-build cache, and the first test run took over 120 seconds to compile. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/dpa-and-retention/.superpowers/sdd/2026-11-25-dpa-acceptance/task-4-report.md</result> <usage><subagent_tokens>47502</subagent_tokens><tool_uses>9</tool_uses><duration_ms>539394</duration_ms></usage> </task-notification>
<task-notification> <task-id>a1b06d3af00299e8a</task-id> <tool-use-id>toolu_01Wzp7GTfaGDBUmMr8sReUxC</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/260ddc60-0dfc-4cf8-8857-7688d6275097/tasks/a1b06d3af00299e8a.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ `dpaInForce` follows §3.5 and the controller rulings (`internal/console/dpainforce.go:35-52`). - It considers only kind "dpa" with ID >= the accepted ID (:38). - The accepted document is always eligible, and a later one needs `dpaQualifies` (:41-48). - It keeps the newest, and `best` only rises, so input order doesn't matter. - The missing-accepted fallback is a zero document carrying the accepted ID (:36). - ✅ `dpaQualifies` (:16-28): - A nil `EffectiveAt` never qualifies (:17). - An `EffectiveAt` after now doesn't qualify. - Without `NeedsNotice` the document qualifies. - With `NeedsNotice`, a nil lookup or no delivery leaves it pending for good. That is intended. - Delivery must satisfy `!deliveredAt.After(now-30d)` (:27), so exactly 30 days counts. - ✅ When an older version qualifies and a newer one doesn't, the older is in force and the newer is pending. The "three versions" cases cover this (`dpainforce_test.go`, in both slice orders). - ❌ `dpaPending` (:56-71) can return a version older than the one in force. Example: accepted 1, v2 needs notice with none delivered, v3 qualifies. In force is 3, and pending is 2. The pane would then say "Version 2 applies from…" while 3 is already in force. The spec says "a newer version is pending", and "nil when nothing newer is pending" is the stated check. I did not run this case. It follows from the code, and no test covers it. - The ruling's literal wording, "newest later document that does not qualify", does allow this. The ruling and the spec disagree here. - ⚠️ Cannot verify from diff: `LegalDocument`, `DPAAcceptance` and `NeedsNotice` field names and types (from tasks 1-3). The caller-side wiring of the notice lookup is not in this diff. ### Strengths - The qualification rule lives in one helper, `dpaQualifies`, shared by both functions, so they can't disagree about whether a given document qualifies. - `d := docs[i]` is declared inside the loop, so `&d` (:67) is a per-iteration copy and safe. - The table test is broad. It covers the 29-day, exactly-30-day and future-effective cases, a nil lookup, a nil `EffectiveAt`, other kinds, out-of-order input, and a missing accepted document. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) - `dpainforce.go:60-61` should also skip documents with `d.ID <= inForce.ID`, where `inForce = dpaInForce(...)`. Equivalently, track the in-force ID first. That way pending is always strictly newer than what is in force, and is nil when everything newer already applies. Add a test: accepted 1, v2 needs notice with none delivered, v3 qualifies, expecting in force 3 and pending nil. The current table never exercises a pending version older than the in-force one. The controller should confirm this reading, since it differs from the literal ruling. #### Minor (Nice to Have) - The `dpaInForce` loop (:41-46) handles the accepted document with a nested `best.ID == accepted.DocumentID` check. That works, but it reads awkwardly. A separate `found` variable would be clearer. ### Assessment **Task quality:** Needs fixes **Reasoning:** `dpaInForce` is correct and well tested. `dpaPending` can return a version older than the one in force when an intermediate version is stuck pending and a later one qualifies, which breaks the "newer version pending" rule.</result> <usage><subagent_tokens>44266</subagent_tokens><tool_uses>1</tool_uses><duration_ms>23861</duration_ms></usage> </task-notification>
Attributed to this commit: 9.70 g CO₂e (1,214,089 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on dpa-and-retention, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/legalfetch.go b/internal/console/legalfetch.go| index 6842763d7..781758807 100644 |
| --- a/internal/console/legalfetch.go |
| +++ b/internal/console/legalfetch.go |
| @@ -20,6 +20,7 @@ import ( |
| "net/url" |
| "strings" |
| "time" |
| + "unicode" |
| "unicode/utf8" |
| "golang.org/x/net/html" |
| @@ -98,13 +99,26 @@ var agreementElements = map[string]bool{ |
| // the stored bytes are the fetched bytes. |
| func canonicalAgreement(b []byte) error { |
| z := html.NewTokenizer(bytes.NewReader(b)) |
| + var open []string |
| + seen := 0 |
| for { |
| - switch z.Next() { |
| - case html.ErrorToken: |
| + tt := z.Next() |
| + if tt == html.ErrorToken { |
| if err := z.Err(); err != io.EOF { |
| return errors.New("unreadable html") |
| } |
| + // The tokenizer discards a tag the input ends inside; a browser |
| + // would complete it, so what rendered would not be what was checked. |
| + if seen < len(b) { |
| + return errors.New("unclosed tag") |
| + } |
| + if len(open) > 0 { |
| + return fmt.Errorf("unclosed <%s>", open[len(open)-1]) |
| + } |
| return nil |
| + } |
| + seen += len(z.Raw()) |
| + switch tt { |
| case html.TextToken: |
| case html.CommentToken: |
| return errors.New("comment") |
| @@ -126,6 +140,16 @@ func canonicalAgreement(b []byte) error { |
| return fmt.Errorf("link %s", shortToken(a.Val)) |
| } |
| } |
| + switch { |
| + case tok.Type == html.EndTagToken: |
| + // br is void: "</br>" is read as "<br>", so it is never balanced. |
| + if len(open) == 0 || open[len(open)-1] != tok.Data { |
| + return fmt.Errorf("unbalanced </%s>", tok.Data) |
| + } |
| + open = open[:len(open)-1] |
| + case tok.Type == html.StartTagToken && tok.Data != "br": |
| + open = append(open, tok.Data) |
| + } |
| } |
| } |
| } |
| @@ -153,7 +177,7 @@ func shortToken(s string) string { |
| sb.WriteString("…") |
| break |
| } |
| - if r < ' ' || r == 0x7f || r == utf8.RuneError { |
| + if r < ' ' || r == 0x7f || r == utf8.RuneError || unicode.Is(unicode.Cf, r) { |
| r = '?' |
| } |
| sb.WriteRune(r) |
diff --git a/internal/console/legalfetch_test.go b/internal/console/legalfetch_test.go| index 78d9b17dd..77e8852f8 100644 |
| --- a/internal/console/legalfetch_test.go |
| +++ b/internal/console/legalfetch_test.go |
| @@ -109,6 +109,8 @@ func TestCanonicalAgreementAccepts(t *testing.T) { |
| `<section><h2>Terms & scope</h2><p>Read the <a href="/terms/">terms</a> and <a href="https://example.com/x">more</a>, <strong>now</strong> <em>ok</em>.<br>line<br/>two</p>` + "\n" + |
| `<ul><li>one</li></ul><ol><li><a>bare</a></li></ol><h3>Sub</h3></section>`, |
| "", |
| + `<p>a<br>b</p><p>a<br/>b</p>`, |
| + `<section><h2><em>a</em></h2><ul><li><a href="/x"><strong>b</strong></a></li></ul></section>`, |
| } |
| for _, s := range ok { |
| if err := canonicalAgreement([]byte(s)); err != nil { |
| @@ -131,6 +133,17 @@ func TestCanonicalAgreementRefuses(t *testing.T) { |
| {`<p class="x">t</p>`, "attribute class on <p>"}, |
| {`<a href="mailto:x@y">t</a>`, "link mailto:"}, |
| {`<p>a</p><style>p{}</style>`, "element <style>"}, |
| + {`<p>x</p><img src=x onerror=y`, "unclosed tag"}, |
| + {`<p>x</p><a href="/x" onclick=`, "unclosed tag"}, |
| + {`<p>x</p><a href="/x`, "unclosed tag"}, |
| + {`<p>x</p><scr`, "unclosed tag"}, |
| + {`<p>Terms</p><script `, "unclosed tag"}, |
| + {`<a href="https://x">open`, "unclosed <a>"}, |
| + {`<p>x</p></section>`, "unbalanced </section>"}, |
| + {`<p><em>x</p></em>`, "unbalanced </p>"}, |
| + {`<p>a</br>b</p>`, "unbalanced </br>"}, |
| + {"<p>x</p><a href=\"/\u202e\u202ex\">t</a", "unclosed tag"}, |
| + {"<p a\u202eb=\"x\">t</p>", "attribute a?b on <p>"}, |
| } { |
| err := canonicalAgreement([]byte(c.in)) |
| if err == nil { |