validate

package
v0.0.55 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0, MIT Imports: 15 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

draft/validate

Enforces the house article rules before a draft is saved.

Go reference Website

Required structure, length, banned vocabulary, emoji, truncation, and faithfulness to the verified claim ledger. A violation triggers a targeted rewrite in the pipeline, not a shrug.

Contents

Install

go get github.com/sebastienrousseau/draft@latest
import "github.com/sebastienrousseau/draft/validate"

Quick start

package main

import (
	"fmt"

	"github.com/sebastienrousseau/draft/claims"
	"github.com/sebastienrousseau/draft/validate"
)

func main() {
	draft := "# Too Short\n\nA draft that breaks most of the rules."

	// Errors returns the hard violations that must block a save.
	// An empty slice means the draft is clean.
	for _, e := range validate.Errors(draft) {
		fmt.Println("✗", e)
	}

	// Faithfulness is separate: it cross-checks the draft against the ledger
	// that grounded it. Hard errors come first, warnings are advisory.
	ledger := []claims.Record{{
		Claim:       "Router-S used 5x fewer FLOPs",
		SourceQuote: "used 5x fewer FLOPs than the dense baseline",
		Type:        "result",
		Strength:    "demonstrated",
	}}
	errs, warnings := validate.Faithfulness("Router-S used 9x fewer FLOPs.", ledger)
	fmt.Println("errors:", errs)
	fmt.Println("warnings:", warnings)
	// Output: warnings: [numbers not found in any claim: 9]

	// The building blocks are exported too.
	fmt.Println(validate.WordCount(draft))            // alphanumeric tokens
	fmt.Println(validate.ContainsEmoji("clean ✅"))    // true
	fmt.Println(validate.EndsSentence("mid-thought")) // false — looks truncated
	fmt.Println(validate.LooksLikeArticle(draft))
}

API

Symbol Signature Purpose
Errors func(md string) []string Hard rule violations that must block a save; empty means clean
Faithfulness func(article string, records []claims.Record) (errs, warnings []string) Cross-check a draft against the verified ledger
LimitationRetention func(article string, given []claims.Record) (errs, warnings []string) Fails a draft carrying none of the limitations it was given
Baselines func(article string, records []claims.Record) []string Comparisons missing their baseline; points written as %
SeparatePopulations func(article string, records []claims.Record) []string Warns where one sentence joins two studies' numbers
WordCount func(s string) int Alphanumeric word tokens
ContainsEmoji func(s string) bool Pictographic or symbol emoji
EndsSentence func(tail string) bool Whether trailing text closes on sentence-ending punctuation
LooksLikeArticle func(s string) bool Whether a string resembles a Markdown article body
UnsafeMarkup func(md string) []string HTML and URLs that would run script on a rendered site

Errors versus warnings

The two functions split along a clean line: Errors judges the draft against itself, Faithfulness judges it against its sources. Neither calls the other — the pipeline runs both.

Errors checks the structural markers from rules (a # title first, ## sections, the post-lead aside, the executive summary), unfilled skeleton placeholders, both word-count bounds, emoji, unsafe markup, and banned words and phrases in every inflection.

Unsafe markup is what a Jekyll or kramdown site would run: script, iframe, object, embed, style, base, meta, link and form elements, event handler attributes in HTML or a kramdown attribute list, and javascript:, vbscript: or data: URLs in links, images, reference definitions, autolinks and URL attributes, entity-encoded or not. A quote is verbatim, so a source can supply any of these; the draft goes back to the writer rather than having the quote rewritten.

Both bounds matter: the writing prompt asks for MinWords–MaxWords and rules declares that band for a finished draft, so checking only the floor told the writer one thing and held it to another. The pipeline's --review path applies this check differently — it fails only on violations an edit introduced, so an article that was already over length stays reviewable.

Faithfulness returns two slices, and the distinction is deliberate:

  • Errors block a save — a metric term the article names that no verified claim supports (a possible silent unit conversion), an ending that does not close on sentence punctuation (truncation), and near-duplicate paragraphs.
  • Warnings are advisory — a number in the article that appears in no claim, a hedged claim restated assertively, or one sentence stating numbers from two claims whose quotes sit in different sections and count different groups (SeparatePopulations: banks in one, corporates in the other, likely two surveys) — and are surfaced without failing the run.
  • Strict-numbers findings are warnings by default and errors under --strict-numbers: a number in no claim, a comparison stated without the baseline its claim names, and a difference of two percentages written as a percent rather than in points (Baselines).

Both read their vocabulary from rules, so what the writer was asked for and what the validator enforces cannot drift apart.

Errors is benchmarked (validate/bench_test.go); a full house-rule pass over a finished draft runs in well under a millisecond, so validation is never the reason a run is slow.

License

Licensed under either of Apache License 2.0 or MIT License, at your option. © Sebastien Rousseau.

Back to top ↑

Documentation

Overview

Package validate enforces the house article rules before a draft is saved: required structure, length, banned vocabulary, emoji, truncation, and faithfulness to the verified claim ledger.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Baselines added in v0.0.53

func Baselines(article string, records []claims.Record) []string

Baselines checks that a comparison in the article is stated against what the source compared it with, and in the source's units.

  • A sentence that makes a comparison and states a number from a comparative claim must name that claim's baseline: the phrase after "than", "over", "versus", "relative to", "compared with" or "against" in the claim. One shared word is enough, so "the baseline" for "the dense baseline" passes; "GPT-4" for it does not.
  • A difference of two percentages is in points. The article writing "3.7%" where the source has 45.2% against 41.5%, or says "3.7 points", turns an absolute gain into a relative one. A percentage any claim states as a percentage is left alone.

The 2026-12-07 article did both. Findings are warnings, and errors under Options.StrictNumbers, since both are a number stated wrongly.

func ContainsEmoji

func ContainsEmoji(s string) bool

ContainsEmoji reports whether s contains a pictographic or symbol emoji.

func DuplicateParagraphIndexes

func DuplicateParagraphIndexes(article string) []int

DuplicateParagraphIndexes returns the indexes, within Paragraphs(article), of paragraphs that nearly duplicate an earlier one. Headings and short paragraphs are never reported: a repeated heading is structure, and short runs of shared words are not evidence of duplication.

func EndsSentence

func EndsSentence(tail string) bool

EndsSentence reports whether the trailing text closes on sentence-ending punctuation. It decodes the final rune (not the final byte) so multibyte closers — smart quotes, apostrophe, ellipsis — are recognised rather than mistaken for a truncated fragment.

func Errors

func Errors(md string) []string

Errors reports the house-rule violations in a finished body under the default house style. See ErrorsWithStyle for the per-style variant.

Example
package main

import (
	"fmt"

	"github.com/sebastienrousseau/draft/validate"
)

func main() {
	fmt.Println(validate.Errors("not a valid article")[0])
}
Output:
body-only mode must start with a Markdown H1

func ErrorsWithStyle

func ErrorsWithStyle(md string, style rules.Style) []string

ErrorsWithStyle checks a body against a specific editorial style: the word band and banned vocabulary come from the style, the structural rules do not, because an H1, a lead aside, an executive summary and section headings are the shape of a grounded article rather than a matter of taste.

The default style takes the fast path — a package-level regex compiled once — so the common case pays nothing for the configurability. A custom style compiles its banned-word matcher on demand.

func Faithfulness

func Faithfulness(article string, records []claims.Record) (errs, warnings []string)

Faithfulness cross-checks a draft against the verified claim ledger with the default policy. Hard errors (returned first) block a save; warnings are advisory.

func FaithfulnessWithOptions

func FaithfulnessWithOptions(article string, records []claims.Record, opts Options) (errs, warnings []string)

FaithfulnessWithOptions is Faithfulness with an explicit policy.

func LimitationCounts added in v0.0.52

func LimitationCounts(article string, given []claims.Record) (total, kept int)

LimitationCounts is how many limitations the writer was given and how many the draft carries, for the provenance record.

func LimitationRetention added in v0.0.52

func LimitationRetention(article string, given []claims.Record) (errs, warnings []string)

LimitationRetention checks that the draft carries the limitations its writer was given: given is the ledger the writing prompt held (see claims.SelectForPrompt), not the whole extraction. A draft that keeps none of them is an error; each one dropped is a warning.

"Carries" means what --verify reports: an article sentence attributed to the claim by provenance.Attribute. The floor is one, not all, because the measured rate is far below all: thirteen published articles carried 103 of the 310 limitations their ledgers held, and a writer given a long ledger cannot fit every caveat into one article. A draft with none, though, is presenting a source's results without the limits the source states.

func LooksLikeArticle

func LooksLikeArticle(s string) bool

LooksLikeArticle reports whether s resembles a Markdown article body, used to decide whether a failed draft is still worth saving for manual review.

func Paragraphs

func Paragraphs(article string) []string

Paragraphs splits an article on blank lines, the unit the duplicate check works in. Exported so a repair pass can address the same paragraphs the check complains about, rather than re-deriving the split and drifting.

func SeparatePopulations added in v0.0.53

func SeparatePopulations(article string, records []claims.Record) []string

SeparatePopulations warns about a sentence that states numbers from two claims which look like two studies: their quotes verified in different sections and count different groups (banks in one, corporates in the other, as rules.PopulationNouns lists them). Put side by side, such numbers read as one comparison the source never made: the 2026-11-30 article set 60% of banks against 32% of corporates from two separate surveys.

It is a warning, never an error. Sections are where the reader split the source, not where its studies begin, so one section can hold two surveys and one survey can span two sections; the check is a prompt to look.

func UnsafeMarkup added in v0.0.49

func UnsafeMarkup(md string) []string

UnsafeMarkup lists the constructs in md that would run script or load foreign content once a Markdown site renders it: dangerous elements, event handler attributes (in HTML or a kramdown attribute list), and javascript:, vbscript: or data: URLs in a link, image, reference definition, autolink or URL attribute. Each kind is listed once, in the order first found, so a caller can compare two drafts. An empty result means none was found.

Code spans and fences are not exempt. A renderer escapes them, but the article's text also feeds frontmatter and excerpts that strip the backticks, and an article that needs a live payload in code is not one draft writes.

func WordCount

func WordCount(s string) int

WordCount counts the words of prose a reader sees: whitespace-separated tokens that contain a letter or a digit, after HTML comments, tags and link targets are removed. "3,000", "FCA's" and "AI-driven" are one word each, and a lone "##" or dash is none. Splitting at every non-letter instead counted numbers, contractions, hyphenations and the lead aside's attributes as extra words, and put real drafts up to 171 words over their prose length.

Types

type Options

type Options struct {
	// StrictNumbers makes a number that appears in the article and in no
	// claim block the save instead of merely warning.
	//
	// A fabricated number is the clearest possible sign of invention, and for
	// a tool whose promise is that every sentence is grounded, letting one
	// reach disk with a line on stderr is hard to defend. It is opt-in for
	// one release because the naive check is noisy — see ungroundedNumbers —
	// so the real false-positive rate can be measured on a corpus before it
	// becomes the default.
	StrictNumbers bool

	// StrictQuotes makes a quotation that no verified source quote contains
	// block the save instead of merely warning. See unsourcedQuotations.
	StrictQuotes bool
}

Options tunes the checks whose strictness is a policy choice rather than a correctness one.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL