diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6d1600b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,248 @@ +# John Slop contributor guide + +## Mission and product boundaries + +John Slop is a transparent, local-first heuristic linter for low-effort or +insufficiently reviewed text and source code. It reports concrete signals that +are often associated with careless AI-assisted work. It must not claim to prove +that a person used AI, identify a model, or infer authorship from writing style. + +Treat a score as **confidence that configured signals are present**, not as the +probability that content is AI-generated. User-facing language must say +"suspicious", "low-care signal", or "needs review" rather than making an +accusation. A result must always be explainable from the findings that produced +it. + +The initial formatter and LSP scope is deliberately narrow: detect configured +Unicode characters that have safe ASCII replacements, expose those replacements +as edits, and reuse the same library implementation in every binary. Do not add +prose rewriting, generative inference, or destructive archive editing without a +separate design decision. + +## Required architecture + +Keep domain logic in a library and binaries as thin adapters. The intended +layout is: + +```text +src/ + lib.rs public library facade + config.rs typed loading, validation, and provenance + diagnostic.rs miette conversion and presentation-neutral spans + input/ files, directories, archives, and ignore policy + detection/ engine, score aggregation, and rule implementations + replacement.rs pure replacement/edit generation + bin/ + john-slop.rs command-line detector + john-slop-fmt.rs replacement formatter + john-slop-lsp.rs stdio language server +assets/ + config.toml embedded replacement defaults + heuristics.toml embedded detection rules +tests/ + fixtures/ small, reviewed input/output fixtures +``` + +Names can evolve when Rust conventions demand it, but preserve these boundaries: + +- `input` acquires text and never scores or changes it. +- `detection` is pure over text plus validated rules. +- `replacement` returns non-overlapping edits and does no I/O. +- `diagnostic` renders findings but does not discover them. +- the CLI, formatter, and LSP call the same config, detector, and replacement APIs. +- filesystem writes are confined to explicit adapter methods. + +Do not retain the current all-files-in-memory iterator design as the core API. +Prefer a streaming iterator of per-file results so one unreadable or binary file +does not erase findings from unrelated files. Preserve the outer archive path and +inner member name as separate fields. Reject unsafe archive paths and apply size, +entry-count, and nesting limits before extraction or decompression. + +## Core data contracts + +Use typed, presentation-neutral domain values. The exact names may change, but +the model must express at least: + +```rust +struct Finding { + rule_id: RuleId, + category: Category, + message: String, + help: Option, + byte_span: Range, + matched_text: String, + weight: f64, + fix: Option, +} + +struct Analysis { + findings: Vec, + confidence: Confidence, +} + +struct TextEdit { + byte_span: Range, + replacement: String, +} +``` + +All internal spans are zero-based UTF-8 byte ranges into the exact source +snapshot that was analyzed. Validate boundaries before slicing. Convert spans at +the edge: `miette::SourceSpan` for terminal output and UTF-16 line/column ranges +for LSP. Keep an indexed line map per document so LSP conversions are tested and +not repeatedly O(n). + +Rule IDs are stable, unique, lowercase kebab-case identifiers. Findings are +sorted by source identity, span start, then rule ID so output is deterministic. +Never use a hash-map iteration order as output order. + +## Heuristics and confidence + +Store data-driven heuristic definitions in `assets/heuristics.toml`, separately +from replacement configuration. Compile and validate rules once at startup. +Invalid regular expressions, duplicate IDs, negative/non-finite weights, invalid +thresholds, and unsafe empty matches are configuration errors—not ignored rules. + +Each rule needs an ID, category, rationale/message, help text, matcher type, +weight, and optional applicability filters such as prose/source-code extensions. +Start with high-precision, independently testable signals: + +- copied assistant disclaimers or knowledge-cutoff phrases; +- prompt/response scaffolding accidentally left in a document; +- templated filler and repeated conclusion/transition phrases; +- suspicious Unicode/confusable punctuation when the configured corpus expects + ASCII; +- source-code placeholders, tutorial residue, fabricated references, or comments + that merely narrate obvious code, using conservative language-specific rules. + +Avoid weak demographic, dialect, spelling, grammar, vocabulary, or +English-fluency proxies. Repetition alone must not trigger a high-confidence +verdict. Give users a per-rule disable/weight override and path/language scopes. + +Scoring must be documented and deterministic. Use bounded weighted evidence, +apply a per-rule occurrence cap, and damp correlated findings from the same rule +or family. Map the aggregate onto `0..=100` and named bands such as `low`, +`medium`, and `high`; keep thresholds configurable. Tests must pin the formula, +caps, threshold edges, and empty-input result. Never label the numeric result an +accuracy or probability unless it has been independently calibrated against a +published, representative corpus. + +Every terminal finding must become a `miette::Diagnostic` with named source, +precise label, stable diagnostic code (the rule ID), severity, message, and help. +A summary score supplements findings; it never replaces their evidence. Machine +output must offer a versioned JSON schema and must not include ANSI escapes. + +## Configuration contract + +Use `figment` with its TOML support and Serde for typed layered configuration. +Its providers allow embedded serialized defaults and later TOML providers to +override individual values while retaining source metadata for useful errors. +Use `directories` (or an equivalent platform-aware crate) to resolve the user +configuration directory; do not hand-build it from `HOME`. + +The precedence from lowest to highest is: + +1. embedded `assets/config.toml` and `assets/heuristics.toml`; +2. user base config at `$XDG_CONFIG_HOME/john_slop/config.toml`, conventionally + `~/.config/john_slop/config.toml` on Linux; +3. named user config at `$XDG_CONFIG_HOME/john_slop/.toml` when a + validated config name is selected; +4. an explicit `--config ` file; +5. explicit CLI flags for the current invocation. + +Missing optional files are allowed; malformed files are fatal and identify their +origin. A config name accepts only ASCII letters, digits, `_`, and `-`; it cannot +contain separators, `.` segments, or an extension. Decide array behavior per +field: replacement/rule tables merge by stable ID, while ignore globs and file +extensions replace as complete arrays unless the schema explicitly says +otherwise. Do not rely on a library's default array-merge semantics implicitly. + +`assets/config.toml` is the canonical, documented replacement catalog. Each +entry has an ID, Unicode source string/code point, ASCII replacement, rationale, +and enabled flag. Reject duplicate sources, empty sources, non-ASCII targets, +and conflicting edits. Longer sources win matching precedence. Provide a command +that prints the resolved configuration with secrets/redacted fields if secrets +are ever introduced. + +Configuration schema changes require a `schema_version`, migration notes, and +tests for precedence. Embed assets with `include_str!` so installed binaries do +not depend on the source tree or current working directory. + +## CLI, formatter, and LSP behavior + +Use explicit Cargo binaries named `john-slop`, `john-slop-fmt`, and +`john-slop-lsp`. + +- The detector reads files/directories/stdin, reports findings, and exits `0` + below the selected threshold, `1` when findings cross it, and `2` for usage or + operational/configuration errors. +- The formatter supports stdin/stdout, `--check`, and an explicit `--write`. + Default behavior must not rewrite a file. Writes must be atomic where the + platform permits, preserve original bytes when no edit applies, preserve line + endings, and be idempotent. +- The LSP communicates only over stdin/stdout; logs go to stderr. Initially it + publishes replacement diagnostics and exposes quick-fix/code-action edits for + open documents. It must honor document versions, clear diagnostics on close, + handle invalid URIs without panicking, and never write editor-owned files. + +Replacement edits are generated from the original snapshot, sorted, checked for +overlap, then applied from the end of the buffer toward the beginning. The +formatter and LSP must produce byte-for-byte equivalent results for the same +source and resolved config. + +## Errors, safety, and observability + +- Libraries return typed errors with `thiserror`; application boundaries attach + path/rule context and render with `miette`. +- Do not use `unwrap`, `expect`, `panic!`, `todo!`, or `unreachable!` on + user-controlled input. An `expect` is acceptable only for an invariant proved + during construction and explained in a comment. +- Treat invalid UTF-8 and binary content as explicit skipped-input diagnostics + according to policy; do not silently truncate or lossily rewrite it. +- Do not follow symlinks by default. Respect ignore configuration and establish + file-size, archive-size, archive-entry, and recursion limits. +- Do not make network calls during analysis. Results should be reproducible and + private by default. +- Structured logs go to stderr and are disabled or quiet by default. Never mix + logs with JSON, formatter stdout, or the LSP protocol stream. + +## Testing and quality gates + +Each behavior change requires tests at the lowest useful layer plus an +integration test when it crosses a binary boundary. Include positive, +near-miss/negative, Unicode, empty, large-input, malformed-config, and ordering +cases. Regression fixtures must state why they should or should not match. + +Before considering a task complete, run: + +```text +cargo fmt --all -- --check +cargo clippy --all-targets --all-features -- -D warnings +cargo test --all-targets --all-features +cargo doc --no-deps +``` + +Also run focused CLI golden tests and LSP protocol tests once those binaries +exist. Favor property tests for replacement idempotence/non-overlap and fuzz +targets for config parsing, span conversion, archives, and replacement planning. +Benchmarks should cover a representative large document and directory; optimize +only from measured results. + +## Change discipline + +Keep commits and patches small enough to review. Do not combine a structural +move with new detection behavior unless the new behavior requires it. Preserve +public behavior during refactors or document the deliberate break. Update sample +configuration, schema/version notes, CLI help, and tests together. + +When implementing `tasks.md`, work in dependency order, mark only verified items +complete, and add newly discovered work under the relevant milestone. Record a +short decision note in the task file when changing configuration precedence, +the score formula, a public data contract, or safety limits. + +After completing and verifying each individual task, create a dedicated commit +before starting the next task. Stage only the files that belong to that task; +never include unrelated or pre-existing user changes. Use a concise conventional +commit message that describes the completed behavior. If a task cannot be +verified or committed, leave it unchecked and report the blocker instead of +combining it with later work. diff --git a/tasks.md b/tasks.md new file mode 100644 index 0000000..08d3186 --- /dev/null +++ b/tasks.md @@ -0,0 +1,232 @@ +# John Slop implementation plan + +This backlog turns the current proof of concept into a reusable detector library +with three thin binaries. Check an item only after its acceptance criteria and +quality gates pass. Preserve unrelated user changes while refactoring. + +## Definition of done + +A task is done when its public behavior is documented, errors carry actionable +context, automated tests cover success and failure paths, and the following pass: + +```text +cargo fmt --all -- --check +cargo clippy --all-targets --all-features -- -D warnings +cargo test --all-targets --all-features +cargo doc --no-deps +``` + +For user-visible output, add deterministic snapshots/golden assertions without +terminal color. For new dependencies, disable unnecessary default features, +explain their role in the commit/PR, and run the available dependency/security +audit in CI. + +## Milestone 0 — Baseline and decisions + +- [ ] Capture current behavior with tests before moving code: plain file, + recursive directory, ZIP member, invalid UTF-8, missing path, and basic Unicode + matching. +- [ ] Fix the misleading Unicode tests/comments (UTF-8 byte lengths and grapheme + terminology) so test names reflect what is actually asserted. +- [ ] Record initial decisions in `docs/decisions/`: evidence confidence is not + authorship probability; UTF-8 byte spans are canonical; formatter writes are + opt-in; no archive mutation in the first formatter release. +- [ ] Define supported inputs and limits: extensions/MIME policy, maximum file + bytes, archive bytes, expanded bytes, entry count, nesting, hidden files, + symlinks, and ignore rules. +- [ ] Establish an MSRV in `Cargo.toml` and CI, add license/repository metadata, + and document supported platforms. +- [ ] Move `tempfile` and other test-only crates to `[dev-dependencies]`; remove + `rayon`, `once_cell`, or `unicode-segmentation` if the final design does not + justify them. + +Acceptance: the existing behavior is characterized, ambiguous product choices +are written down, and a clean baseline passes all quality gates. + +## Milestone 1 — Library-first restructure + +- [ ] Add `src/lib.rs` and expose a small facade for loading config, analyzing a + source, planning replacements, and reading inputs. +- [ ] Replace demo functions and ad hoc errors in `main.rs` with typed domain + values (`SourceId`, `Finding`, `Analysis`, `Confidence`, `TextEdit`). +- [ ] Split `reader.rs` into `input/file.rs`, `input/walk.rs`, and + `input/archive.rs`; yield one `Result` at a time rather + than loading a directory into a `Vec`. +- [ ] Preserve outer and inner archive identities. Prevent path traversal and + decompression bombs using the limits from Milestone 0. +- [ ] Centralize error enums with `thiserror`; add `miette` context only at + presentation boundaries. Remove placeholder `try_report` and sample reports. +- [ ] Add explicit `[[bin]]` targets for `john-slop`, `john-slop-fmt`, and + `john-slop-lsp`; the latter two may initially call stub adapters but all three + must compile. +- [ ] Keep binary parsing/orchestration out of the library. Add `clap` with derive + for stable help, validation, and exit-code handling. + +Acceptance: integration tests can call the library without spawning a process; +all binaries build; no production module is a demo; failures in one directory +entry do not discard successful documents. + +## Milestone 2 — Typed layered configuration + +- [ ] Add Serde, `figment` with TOML support, and a platform-aware configuration + directory crate such as `directories`. +- [ ] Create `assets/config.toml` as the embedded replacement catalog with + `schema_version` and documented examples. +- [ ] Create `assets/heuristics.toml` as a separate embedded rule catalog with + stable IDs, categories, matcher types, weights, messages, help, occurrence caps, + and applicability scopes. +- [ ] Implement exact precedence: embedded defaults < user `config.toml` < named + user `.toml` < explicit `--config` < explicit CLI flags. +- [ ] Validate config names and refuse traversal, extensions, empty names, and + non-ASCII characters. Resolve the user path with platform APIs. +- [ ] Implement merge-by-ID for rule/replacement tables rather than allowing + positional array replacement to produce surprising partial configuration. +- [ ] Validate the fully resolved model: schema version, unique IDs/sources, + ASCII-only replacement targets, regex compilation, finite non-negative weights, + ordered thresholds, safe matchers, and edit conflicts. +- [ ] Preserve enough provider metadata to identify the offending file and key in + a `miette` configuration diagnostic. +- [ ] Add `john-slop config show` and `john-slop config paths` so precedence is + inspectable; output deterministic TOML or JSON. +- [ ] Test every layer alone and in combination, including missing optional files, + malformed TOML, unknown fields, named configs, array semantics, and CLI wins. + +Acceptance: installed binaries work without source-tree assets, the resolved +configuration is explainable, and all precedence/validation tests pass. + +## Milestone 3 — Heuristic detection engine + +- [ ] Define a `Rule`/`Detector` interface and a registry built entirely from the + validated heuristic config. Compile reusable matchers once. +- [ ] Implement exact phrase and regex rules with precise byte spans, match text, + category, weight, message, help, and stable rule ID. +- [ ] Add conservative first-party rules for copied assistant disclaimers, + knowledge-cutoff language, prompt/response leakage, templated filler, repetitive + transitions/conclusions, suspicious Unicode, and code-specific placeholder or + tutorial residue. +- [ ] Add applicability filters for prose versus source code, extension/language, + include/exclude globs, and generated/vendor/minified paths. +- [ ] Design the confidence formula: bounded weighted evidence, per-rule caps, + correlated-family damping, normalization to `0..=100`, and configurable + low/medium/high thresholds. +- [ ] Return zero confidence and no verdict for empty/no-evidence input. Keep + unsupported/binary input distinct from a clean analysis. +- [ ] Sort findings deterministically and deduplicate identical rule/span pairs. +- [ ] Add table-driven unit tests for every shipped rule with positive examples + and realistic near misses. Add tests for disabled rules, overrides, scope, + caps, damping, threshold boundaries, and multilingual text. +- [ ] Build a reviewed evaluation corpus that is legally distributable and labels + observable low-care signals, not presumed author identity. Report per-rule + precision/recall and aggregate false-positive rates before tuning defaults. +- [ ] Document limitations, adversarial evasion, domain shift, and why the score + is not an AI-authorship probability. + +Acceptance: every score decomposes into visible findings; no high-confidence +result can arise solely from a single weak repeated signal; the shipped rules and +formula are pinned by tests. + +## Milestone 4 — Diagnostics and detector CLI + +- [ ] Convert each `Finding` into a typed `miette::Diagnostic` with named source, + exact `SourceSpan`, severity, rule ID as diagnostic code, message, and help. +- [ ] Add a summary that reports confidence band/score and counts by severity, + while retaining every contributing diagnostic. +- [ ] Build detector CLI inputs for file, directory, and stdin (`--stdin-filename` + for language/path scoping); add ignore and maximum-size controls. +- [ ] Add human, concise, and versioned JSON output modes. Ensure JSON and stdout + diagnostics never contain logs or ANSI escapes. +- [ ] Implement documented exit codes: `0` below fail threshold, `1` at/above it, + `2` for usage/configuration/I/O failure. Add `--fail-level`. +- [ ] Report per-document input errors without hiding findings from other + documents; define whether partial failure returns `2` and test it. +- [ ] Add CLI integration tests for spans containing multibyte UTF-8, multiple + files, stdin, missing paths, malformed configs, stable ordering, JSON schema, + and exit codes. + +Acceptance: a user can trace the aggregate score to highlighted source ranges +and remediation help; CI can consume stable machine output and exit statuses. + +## Milestone 5 — Shared ASCII replacement engine and formatter + +- [ ] Parse replacement definitions into a trie or deterministic longest-match + planner and emit validated, non-overlapping `TextEdit`s against the original + source. +- [ ] Apply edits from highest to lowest byte offset. Preserve line endings and + return the original buffer unchanged when there are no edits. +- [ ] Reject non-character-boundary and overlapping edits as typed invariant + errors. Define deterministic behavior when sources share prefixes. +- [ ] Implement `john-slop-fmt` stdin/stdout mode, `--check`, `--diff`, and + explicit `--write`. Require an explicit policy for recursive directory writes. +- [ ] Make writes atomic with a same-directory temporary file plus rename when + supported; retain permissions and never rewrite on analysis/config failure. +- [ ] Do not rewrite ZIP/DOCX/XLSX/PPTX members in this milestone; emit a clear + unsupported-operation diagnostic. +- [ ] Add unit/property tests for idempotence, Unicode boundaries, longest match, + non-overlap, stable output, line endings, empty input, and no-op byte identity. +- [ ] Add integration tests proving `--check` exit status, stdout purity, atomic + failure behavior, config overrides, and formatter/detector agreement. + +Acceptance: formatting twice equals formatting once; default invocation does not +modify files; every replacement comes from the resolved typed config. + +## Milestone 6 — LSP binary + +- [ ] Select an actively maintained LSP framework after a short dependency/API + review (evaluate `tower-lsp-server`); pin the decision and protocol assumptions + in a decision record. +- [ ] Implement stdio initialization/shutdown and incremental or full document + synchronization with URI, version, language ID, and current text tracked per + open document. +- [ ] Build and thoroughly test byte-offset to LSP UTF-16 line/character mapping, + including CRLF, emoji, combining marks, astral characters, and EOF positions. +- [ ] Publish diagnostics only for configured ASCII-replacement findings in the + initial release. Include stable codes and source `john-slop`. +- [ ] Expose quick fixes/code actions using the exact edits from the shared + replacement engine; reject stale-version requests. +- [ ] Recompute after open/change/configuration updates, clear on close, and avoid + publishing obsolete results when analysis overlaps newer edits. +- [ ] Keep all protocol bytes on stdout and diagnostics/logging on stderr. Add + opt-in structured logging without document contents. +- [ ] Add in-process protocol tests for lifecycle, versions, Unicode positions, + config reload, close cleanup, invalid URI, malformed messages, concurrent + documents, and formatter/LSP output equivalence. + +Acceptance: a standards-compliant client can see replacement diagnostics and +apply a quick fix; the resulting text exactly matches `john-slop-fmt` under the +same config. + +## Milestone 7 — Hardening, documentation, and release + +- [ ] Replace the placeholder README with installation, threat model, examples, + configuration precedence/schema, rule authoring, confidence interpretation, + CLI/formatter/LSP setup, exit codes, privacy, and limitations. +- [ ] Publish commented sample base and named configs. Document how to disable a + rule/replacement and how merge-by-ID works. +- [ ] Add CI on the supported OS/MSRV matrix for formatting, Clippy, tests, docs, + audit/deny checks, and fixture/golden consistency. +- [ ] Add fuzz targets for TOML/config merging, regex/rule loading, UTF-8 span + mapping, replacement planning, and malicious ZIP metadata. Seed them with + regression fixtures. +- [ ] Benchmark large files, many small files, rule scaling, and archive limits. + Add parallelism only if measurement shows a benefit and output remains ordered. +- [ ] Review dependency features, licenses, advisories, unsafe code, and release + binary size. Generate an SBOM/checksums if releases distribute binaries. +- [ ] Add changelog, contribution guide, code of conduct, security reporting + instructions, release profile, and reproducible release procedure. +- [ ] Run a false-positive review against the evaluation corpus and require an + explicit sign-off before changing default rule weights or thresholds. + +Acceptance: a new user can install and operate all three binaries from the README; +CI enforces the documented contracts; release artifacts are reproducible and the +detector's limitations are prominent. + +## Deferred by design + +- Statistical or model-based authorship classification. +- Automatic prose or source-code rewriting beyond configured ASCII replacements. +- In-place modification of archive members or office documents. +- Network-backed analysis or telemetry. +- Editor-specific extensions; the LSP is the integration boundary. + +These are not implied follow-ups. Each requires a separate privacy, safety, +performance, and product-design review before entering the active milestones.