Vibecode Grammarly
track this build5 phases, 17 steps, beginner friendly0%You can build grammar checks and rewrites, but Grammarly's moat is cross-app extensions, inline UX, enterprise controls, writing telemetry, and long-running language quality.
You are building a lean indie version of Grammarly. Create the following project files first, then implement the application by following them. Keep the files updated as decisions change. Do not collapse this into a single README or prompt. ===== README.md ===== # Grammarly · indie build Build a local writing checker with rule suggestions and optional accepted rewrites. Estimated effort: **multi-day**. Work `BUILD_PLAN.md` top to bottom · every phase ends in a check that has to pass before the next one starts. ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Generation | Ollama local HTTP API | A backend-only adapter with a configurable installed local model and visible failure states. | | Grammar | LanguageTool Java HTTP server | Reuse existing local language rules rather than writing a grammar engine. | ## Before you start Have every one of these ready. The plan assumes them from step one. - [ ] **Python 3.12 or newer and a terminal** · Python is free; this local prototype requires no hosting subscription. - Why: The local backend, tests and storage use Python. - Get it: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. - Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. - [ ] **A current desktop browser and text editor** · No paid service required for this local step. - Why: You need to view the local interface and edit generated project files. - Get it: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. - Verify: You can create a text file in the project folder and open browser developer tools. - [ ] **Grammarly acceptance sample** · No paid service required for this local step. - Why: This fixture makes the first end-to-end check reproducible. - Get it: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. - Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. - [ ] **Confirm the bounded replacement** · No paid service required for this local step. - Why: The full commercial product is larger than this guide. - Get it: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. - Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. - [ ] **Ollama with an explicitly local model** (optional) · No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - Why: Generation requires a running model; ordinary editing remains usable while it is unavailable. - Get it: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. - Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. - [ ] **LanguageTool Java HTTP server** · Local basic engine; premium cloud-only rules are outside this build. - Why: The app reuses the existing grammar engine. - Get it: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. - Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. ## Quick start ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` Then copy `.env.example` to `.env` and fill in the values it documents. ## Honest limits This build deliberately does not replace: - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling If one of those is essential to you, that is the reason to keep paying for Grammarly, and the README should say so rather than pretend. ===== BRIEF.md ===== # Build brief · Grammarly The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a local writing checker with rule suggestions and optional accepted rewrites as a bounded replacement for Grammarly. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Generation: Ollama local HTTP API. A backend-only adapter with a configurable installed local model and visible failure states. - Grammar: LanguageTool Java HTTP server. Reuse existing local language rules rather than writing a grammar engine. ### Data model (create this before Phase 1) - documents(id,title,text,revision) - issues(id,document_id,revision,offset,length,rule_id,message,replacements_json) - dictionary(word) - rewrites(id,document_id,revision,mode,proposal,state) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: A short paragraph with a misspelling, an emoji before it and a protected proper name. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - Grammarly acceptance sample: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - Ollama with an explicitly local model: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. Cost: No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - LanguageTool Java HTTP server: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. Cost: Local basic engine; premium cloud-only rules are outside this build. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, OLLAMA_URL, LOCAL_MODEL, LANGUAGETOOL_URL. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Commands, after creating the named files: `python scripts/model_probe.py`. - In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Commands, after creating the named files: `java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start local grammar service until these checks pass. ### Phase 2 · Local grammar service Build: Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The local server supplies basic rules; cloud-only AI checks are not included. Done when: A check returns a visible issue on the deliberate misspelling. Disconnecting the service shows retry guidance without deleting the draft. Do not build yet: Do not start safe inline replacement until these checks pass. ### Phase 3 · Safe inline replacement Build: Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. Done when: Accepting the correction changes only the intended word after the emoji. Editing the draft during a check invalidates stale suggestions. Do not build yet: Do not start optional rewrite and cli until these checks pass. ### Phase 4 · Optional rewrite and CLI Build: Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. Done when: Rejecting a rewrite preserves the original document exactly. The CLI returns a failure status for the misspelling fixture and success after correction. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the Grammarly replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere: retain the paid product if this capability is essential; it is outside this bounded build. - document/email integrations: retain the paid product if this capability is essential; it is outside this bounded build. - tone/brand controls: retain the paid product if this capability is essential; it is outside this bounded build. - enterprise admin: retain the paid product if this capability is essential; it is outside this bounded build. - polished false-positive handling: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.ollama.com/api/chat ; https://docs.ollama.com/cloud ; https://dev.languagetool.org/http-server. Recheck before upgrading; freeze the versions actually tested. ===== AGENTS.md ===== # Agent instructions · Grammarly indie build - Read `README.md` and `BUILD_PLAN.md` before writing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, Ollama local HTTP API, LanguageTool Java HTTP server. Do not substitute. - Work one phase at a time, in order. Do not start a phase until every "Done when" item of the previous one passes. - Prefer the fewest moving parts that satisfy the step. No frameworks, services or dependencies the plan does not name. - Secrets live in `.env`, never in source or logs. Keep `.env.example` current when a variable is introduced. - Do not invent cryptography, security guarantees, APIs or compliance claims. - Add a focused test for every destructive, security-sensitive or data-loss path the plan names. - Run the project checks before declaring a phase complete, and record any deliberate shortcut in the README under "Tradeoffs". ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The local server supplies basic rules; cloud-only AI checks are not included. - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - Export without an import or restore rehearsal is not verified portability. ===== BUILD_PLAN.md ===== # Build plan · Grammarly Build a local writing checker with rule suggestions and optional accepted rewrites. Phases are in dependency order. Each ends in a "Done when" list; treat an unticked item as a blocker, not a note. ## Phase 1 · Local foundation and data contract Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Verify the selected local model Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Files: `providers/local_model.py`, `scripts/model_probe.py` ```sh python scripts/model_probe.py ``` 5. Start the grammar service In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Files: `providers/grammar.py` ```sh java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081 ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## Phase 2 · Local grammar service Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. ### Steps 1. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Files: `features/local_grammar_service.py`, `templates/local_grammar_service.html` 2. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Files: `features/local_grammar_service.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_local_grammar_service.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Disconnecting the service shows retry guidance without deleting the draft. ### Watch out - The local server supplies basic rules; cloud-only AI checks are not included. ## Phase 3 · Safe inline replacement Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. ### Steps 1. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Files: `features/safe_inline_replacement.py`, `templates/safe_inline_replacement.html` 2. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Files: `features/safe_inline_replacement.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_safe_inline_replacement.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Editing the draft during a check invalidates stale suggestions. ### Watch out - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. ## Phase 4 · Optional rewrite and CLI Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. ### Steps 1. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Files: `features/optional_rewrite_and_cli.py`, `templates/optional_rewrite_and_cli.html` 2. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Files: `features/optional_rewrite_and_cli.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_optional_rewrite_and_cli.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] The CLI returns a failure status for the misspelling fixture and success after correction. ### Watch out - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. ## Phase 5 · Portable delivery and clean-start proof Finish the Grammarly replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## Not in this build - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling ## After v1, if you want it - Extend optional rewrite and cli only after the fixture and recovery checks pass. - Before adding another integration, document its credentials, limits, cost and failure behavior with primary-source links. ===== .env.example ===== # Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/grammarly # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Keep the inference service bound to loopback; the backend calls it, never the public browser. OLLAMA_URL=http://127.0.0.1:11434 # Optional. Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. LOCAL_MODEL=replace-with-installed-local-model # Required. The loopback Java server started from the official distribution; Python proxies checks to it. LANGUAGETOOL_URL=http://127.0.0.1:8081
You are building a lean indie version of Grammarly. Create the following project files first, then implement the application by following them. Keep the files updated as decisions change. Do not collapse this into a single README or prompt. ===== README.md ===== # Grammarly · indie build Build a local writing checker with rule suggestions and optional accepted rewrites. Estimated effort: **multi-day**. Work `BUILD_PLAN.md` top to bottom · every phase ends in a check that has to pass before the next one starts. ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Generation | Ollama local HTTP API | A backend-only adapter with a configurable installed local model and visible failure states. | | Grammar | LanguageTool Java HTTP server | Reuse existing local language rules rather than writing a grammar engine. | ## Before you start Have every one of these ready. The plan assumes them from step one. - [ ] **Python 3.12 or newer and a terminal** · Python is free; this local prototype requires no hosting subscription. - Why: The local backend, tests and storage use Python. - Get it: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. - Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. - [ ] **A current desktop browser and text editor** · No paid service required for this local step. - Why: You need to view the local interface and edit generated project files. - Get it: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. - Verify: You can create a text file in the project folder and open browser developer tools. - [ ] **Grammarly acceptance sample** · No paid service required for this local step. - Why: This fixture makes the first end-to-end check reproducible. - Get it: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. - Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. - [ ] **Confirm the bounded replacement** · No paid service required for this local step. - Why: The full commercial product is larger than this guide. - Get it: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. - Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. - [ ] **Ollama with an explicitly local model** (optional) · No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - Why: Generation requires a running model; ordinary editing remains usable while it is unavailable. - Get it: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. - Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. - [ ] **LanguageTool Java HTTP server** · Local basic engine; premium cloud-only rules are outside this build. - Why: The app reuses the existing grammar engine. - Get it: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. - Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. ## Quick start ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` Then copy `.env.example` to `.env` and fill in the values it documents. ## Honest limits This build deliberately does not replace: - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling If one of those is essential to you, that is the reason to keep paying for Grammarly, and the README should say so rather than pretend. ===== BRIEF.md ===== # Build brief · Grammarly The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a local writing checker with rule suggestions and optional accepted rewrites as a bounded replacement for Grammarly. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Generation: Ollama local HTTP API. A backend-only adapter with a configurable installed local model and visible failure states. - Grammar: LanguageTool Java HTTP server. Reuse existing local language rules rather than writing a grammar engine. ### Data model (create this before Phase 1) - documents(id,title,text,revision) - issues(id,document_id,revision,offset,length,rule_id,message,replacements_json) - dictionary(word) - rewrites(id,document_id,revision,mode,proposal,state) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: A short paragraph with a misspelling, an emoji before it and a protected proper name. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - Grammarly acceptance sample: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - Ollama with an explicitly local model: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. Cost: No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - LanguageTool Java HTTP server: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. Cost: Local basic engine; premium cloud-only rules are outside this build. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, OLLAMA_URL, LOCAL_MODEL, LANGUAGETOOL_URL. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Commands, after creating the named files: `python scripts/model_probe.py`. - In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Commands, after creating the named files: `java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start local grammar service until these checks pass. ### Phase 2 · Local grammar service Build: Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The local server supplies basic rules; cloud-only AI checks are not included. Done when: A check returns a visible issue on the deliberate misspelling. Disconnecting the service shows retry guidance without deleting the draft. Do not build yet: Do not start safe inline replacement until these checks pass. ### Phase 3 · Safe inline replacement Build: Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. Done when: Accepting the correction changes only the intended word after the emoji. Editing the draft during a check invalidates stale suggestions. Do not build yet: Do not start optional rewrite and cli until these checks pass. ### Phase 4 · Optional rewrite and CLI Build: Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. Done when: Rejecting a rewrite preserves the original document exactly. The CLI returns a failure status for the misspelling fixture and success after correction. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the Grammarly replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere: retain the paid product if this capability is essential; it is outside this bounded build. - document/email integrations: retain the paid product if this capability is essential; it is outside this bounded build. - tone/brand controls: retain the paid product if this capability is essential; it is outside this bounded build. - enterprise admin: retain the paid product if this capability is essential; it is outside this bounded build. - polished false-positive handling: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.ollama.com/api/chat ; https://docs.ollama.com/cloud ; https://dev.languagetool.org/http-server. Recheck before upgrading; freeze the versions actually tested. ===== AGENTS.md ===== # Agent instructions · Grammarly indie build - Read `README.md` and `BUILD_PLAN.md` before writing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, Ollama local HTTP API, LanguageTool Java HTTP server. Do not substitute. - Work one phase at a time, in order. Do not start a phase until every "Done when" item of the previous one passes. - Prefer the fewest moving parts that satisfy the step. No frameworks, services or dependencies the plan does not name. - Secrets live in `.env`, never in source or logs. Keep `.env.example` current when a variable is introduced. - Do not invent cryptography, security guarantees, APIs or compliance claims. - Add a focused test for every destructive, security-sensitive or data-loss path the plan names. - Run the project checks before declaring a phase complete, and record any deliberate shortcut in the README under "Tradeoffs". ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The local server supplies basic rules; cloud-only AI checks are not included. - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - Export without an import or restore rehearsal is not verified portability. ===== BUILD_PLAN.md ===== # Build plan · Grammarly Build a local writing checker with rule suggestions and optional accepted rewrites. Phases are in dependency order. Each ends in a "Done when" list; treat an unticked item as a blocker, not a note. ## Phase 1 · Local foundation and data contract Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Verify the selected local model Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Files: `providers/local_model.py`, `scripts/model_probe.py` ```sh python scripts/model_probe.py ``` 5. Start the grammar service In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Files: `providers/grammar.py` ```sh java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081 ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## Phase 2 · Local grammar service Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. ### Steps 1. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Files: `features/local_grammar_service.py`, `templates/local_grammar_service.html` 2. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Files: `features/local_grammar_service.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_local_grammar_service.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Disconnecting the service shows retry guidance without deleting the draft. ### Watch out - The local server supplies basic rules; cloud-only AI checks are not included. ## Phase 3 · Safe inline replacement Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. ### Steps 1. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Files: `features/safe_inline_replacement.py`, `templates/safe_inline_replacement.html` 2. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Files: `features/safe_inline_replacement.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_safe_inline_replacement.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Editing the draft during a check invalidates stale suggestions. ### Watch out - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. ## Phase 4 · Optional rewrite and CLI Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. ### Steps 1. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Files: `features/optional_rewrite_and_cli.py`, `templates/optional_rewrite_and_cli.html` 2. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Files: `features/optional_rewrite_and_cli.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_optional_rewrite_and_cli.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] The CLI returns a failure status for the misspelling fixture and success after correction. ### Watch out - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. ## Phase 5 · Portable delivery and clean-start proof Finish the Grammarly replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## Not in this build - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling ## After v1, if you want it - Extend optional rewrite and cli only after the fixture and recovery checks pass. - Before adding another integration, document its credentials, limits, cost and failure behavior with primary-source links. ===== .env.example ===== # Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/grammarly # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Keep the inference service bound to loopback; the backend calls it, never the public browser. OLLAMA_URL=http://127.0.0.1:11434 # Optional. Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. LOCAL_MODEL=replace-with-installed-local-model # Required. The loopback Java server started from the official distribution; Python proxies checks to it. LANGUAGETOOL_URL=http://127.0.0.1:8081
You are building a production product version of Grammarly. Create the following project files first, then implement the application by following them. Keep the files updated as decisions change. Do not collapse this into a single README or prompt. ===== PRODUCT.md ===== # Grammarly · product brief ## Problem You can build grammar checks and rewrites, but Grammarly's moat is cross-app extensions, inline UX, enterprise controls, writing telemetry, and long-running language quality. ## Product outcome An operated version of a local writing checker with rule suggestions and optional accepted rewrites, with authorized access, restore evidence and honest scope limits. ## Target user A builder who needs a maintainable product foundation, not a one-off demo. ## Required capabilities - grammar engine/API - LLM API - browser extension - optional desktop accessibility layer - user dictionary ## Explicit non-goals for v1 - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling ## Success criteria - A check returns a visible issue on the deliberate misspelling. - Accepting the correction changes only the intended word after the emoji. - Rejecting a rewrite preserves the original document exactly. - A private-data authorization check passes using a second identity. - An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - README names the excluded vendor capabilities and actual provider/hosting costs. ===== BRIEF.md ===== # Build brief · Grammarly The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a local writing checker with rule suggestions and optional accepted rewrites as a bounded replacement for Grammarly. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Generation: Ollama local HTTP API. A backend-only adapter with a configurable installed local model and visible failure states. - Grammar: LanguageTool Java HTTP server. Reuse existing local language rules rather than writing a grammar engine. ### Data model (create this before Phase 1) - documents(id,title,text,revision) - issues(id,document_id,revision,offset,length,rule_id,message,replacements_json) - dictionary(word) - rewrites(id,document_id,revision,mode,proposal,state) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: A short paragraph with a misspelling, an emoji before it and a protected proper name. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - Grammarly acceptance sample: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - Ollama with an explicitly local model: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. Cost: No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - LanguageTool Java HTTP server: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. Cost: Local basic engine; premium cloud-only rules are outside this build. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, OLLAMA_URL, LOCAL_MODEL, LANGUAGETOOL_URL. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Commands, after creating the named files: `python scripts/model_probe.py`. - In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Commands, after creating the named files: `java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start local grammar service until these checks pass. ### Phase 2 · Local grammar service Build: Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The local server supplies basic rules; cloud-only AI checks are not included. Done when: A check returns a visible issue on the deliberate misspelling. Disconnecting the service shows retry guidance without deleting the draft. Do not build yet: Do not start safe inline replacement until these checks pass. ### Phase 3 · Safe inline replacement Build: Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. Done when: Accepting the correction changes only the intended word after the emoji. Editing the draft during a check invalidates stale suggestions. Do not build yet: Do not start optional rewrite and cli until these checks pass. ### Phase 4 · Optional rewrite and CLI Build: Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. Done when: Rejecting a rewrite preserves the original document exactly. The CLI returns a failure status for the misspelling fixture and success after correction. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the Grammarly replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere: retain the paid product if this capability is essential; it is outside this bounded build. - document/email integrations: retain the paid product if this capability is essential; it is outside this bounded build. - tone/brand controls: retain the paid product if this capability is essential; it is outside this bounded build. - enterprise admin: retain the paid product if this capability is essential; it is outside this bounded build. - polished false-positive handling: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.ollama.com/api/chat ; https://docs.ollama.com/cloud ; https://dev.languagetool.org/http-server. Recheck before upgrading; freeze the versions actually tested. ===== ARCHITECTURE.md ===== # Architecture · Grammarly ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Generation | Ollama local HTTP API | A backend-only adapter with a configurable installed local model and visible failure states. | | Grammar | LanguageTool Java HTTP server | Reuse existing local language rules rather than writing a grammar engine. | ## Modules Each module has one owner concern and a documented way to replace it. | Module | Owns | How to replace it | | --- | --- | --- | | Data and identity | documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state) | Keep stable ids and a versioned repository interface; migrate storage behind it with a fixture round-trip. | | Local grammar service | Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. | Keep the acceptance contract: A check returns a visible issue on the deliberate misspelling. Replace only this module after replaying its fixture; preserve ids and existing records. | | Safe inline replacement | Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. | Keep the acceptance contract: Accepting the correction changes only the intended word after the emoji. Replace only this module after replaying its fixture; preserve ids and existing records. | | Optional rewrite and CLI | Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. | Keep the acceptance contract: Rejecting a rewrite preserves the original document exactly. Replace only this module after replaying its fixture; preserve ids and existing records. | | Operations | Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. | Change host or backup destination only after an isolated restore and authorization check. | ## Configuration Every runtime setting is an environment variable documented in `.env.example`, validated at startup, with a safe local default wherever one exists. - `DATA_DIR` · required · A new private folder this application creates on first run; never serve it as static files. - `SECRET_KEY` · required, secret · Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. - `APP_MODE` · required · Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. - `SITE_URL` · required · The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. - `OLLAMA_URL` · required · Keep the inference service bound to loopback; the backend calls it, never the public browser. - `LOCAL_MODEL` · optional · Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. - `LANGUAGETOOL_URL` · required · The loopback Java server started from the official distribution; Python proxies checks to it. ## Production baseline - Security: least privilege, input validation at every boundary, secret redaction in logs, rate limits on abuse-prone paths, no invented security primitives. - Data: explicit schema and migrations, transactional writes where integrity matters, backup and restore procedures that have been exercised. - Integrations: adapters around third-party providers, idempotent webhook or job processing, bounded retries, timeouts. - Observability: structured logs with request or operation ids, an error-tracking hook, and health and readiness checks where a server exists. - Quality: unit tests for domain rules, integration tests at module boundaries, one end-to-end test of the critical path. ## Decision records For each dependency in the stack table, keep a short note: why it was chosen, its failure mode, and how it is replaced. Do not add infrastructure until a requirement in `PRODUCT.md` justifies it. ===== AGENTS.md ===== # Agent instructions · Grammarly product build - Read `PRODUCT.md` and `ARCHITECTURE.md` before changing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, Ollama local HTTP API, LanguageTool Java HTTP server. - Implement milestone by milestone from `MILESTONES.md`; keep each change reviewable and leave the application runnable at every commit. - Treat authentication, payments, encryption, imports, webhooks and destructive actions as high-risk boundaries when present. - Never invent cryptography or silently weaken a requirement to make a check pass. - Put every external service behind an interface with a deterministic fake for tests. - Add migrations and rollback or recovery notes for every persistent data change. - Log useful operational context without credentials, tokens, passwords or personal data. - Update documentation and run every check before completing a milestone. ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The local server supplies basic rules; cloud-only AI checks are not included. - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - Export without an import or restore rehearsal is not verified portability. - Product mode is additional engineering, not a switch that makes a local prototype production-ready. ===== MILESTONES.md ===== # Delivery milestones · Grammarly Estimated effort: **multi-day** for the indie phases; the production-only milestones add the trust and operability layer. ## M1 · Local foundation and data contract Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Verify the selected local model Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Files: `providers/local_model.py`, `scripts/model_probe.py` ```sh python scripts/model_probe.py ``` 5. Start the grammar service In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Files: `providers/grammar.py` ```sh java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081 ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## M2 · Local grammar service Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. ### Steps 1. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Files: `features/local_grammar_service.py`, `templates/local_grammar_service.html` 2. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Files: `features/local_grammar_service.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_local_grammar_service.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Disconnecting the service shows retry guidance without deleting the draft. ### Watch out - The local server supplies basic rules; cloud-only AI checks are not included. ## M3 · Safe inline replacement Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. ### Steps 1. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Files: `features/safe_inline_replacement.py`, `templates/safe_inline_replacement.html` 2. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Files: `features/safe_inline_replacement.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_safe_inline_replacement.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Editing the draft during a check invalidates stale suggestions. ### Watch out - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. ## M4 · Optional rewrite and CLI Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. ### Steps 1. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Files: `features/optional_rewrite_and_cli.py`, `templates/optional_rewrite_and_cli.html` 2. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Files: `features/optional_rewrite_and_cli.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_optional_rewrite_and_cli.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] The CLI returns a failure status for the misspelling fixture and success after correction. ### Watch out - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. ## M5 · Portable delivery and clean-start proof Finish the Grammarly replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## M6 · Operate and share with access controls (production only) Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. ### Steps 1. Establish owner access before exposure Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. Files: `ARCHITECTURE.md`, `OPERATIONS.md` 2. Deploy a monitored service Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Files: `Caddyfile`, `OPERATIONS.md` ```sh waitress-serve --listen=127.0.0.1:5000 app:app ``` 3. Rehearse loss and recovery Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. Files: `OPERATIONS.md`, `release-checklist.md` ### Done when - [ ] An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. - [ ] A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. - [ ] Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. ### Watch out - Product mode is additional engineering, not a switch that makes a local prototype production-ready. ===== OPERATIONS.md ===== # Operations · Grammarly ## Backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. ## Restore Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Do a restore drill before the first real user, and write the date here when it passes. ## Monitoring Check HTTP availability, free disk, backup age and domain failures for Local grammar service, Safe inline replacement, Optional rewrite and CLI. Alert without logging private payloads. ## Incident checklist Pause outbound jobs and public intake as appropriate, preserve redacted diagnostics, restore an isolated verified backup, rotate affected credentials and reconcile uncertain effects before reopening. 1. Contain the issue without destroying evidence or user data. 2. Record the timeline and affected scope. 3. Rotate exposed secrets and revoke compromised sessions or credentials. 4. Restore from a verified backup when needed. 5. Document the root cause, the remediation and the regression test. ## Release gate - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] A private-data authorization check passes using a second identity. - [ ] An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - [ ] README names the excluded vendor capabilities and actual provider/hosting costs. ## Launch constraint Do not market omitted Grammarly capabilities as implemented. The non-goals in `PRODUCT.md` remain user-visible limitations until they are deliberately delivered. ===== .env.example ===== # Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/grammarly # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Keep the inference service bound to loopback; the backend calls it, never the public browser. OLLAMA_URL=http://127.0.0.1:11434 # Optional. Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. LOCAL_MODEL=replace-with-installed-local-model # Required. The loopback Java server started from the official distribution; Python proxies checks to it. LANGUAGETOOL_URL=http://127.0.0.1:8081
# Grammarly · indie build Build a local writing checker with rule suggestions and optional accepted rewrites. Estimated effort: **multi-day**. Work `BUILD_PLAN.md` top to bottom · every phase ends in a check that has to pass before the next one starts. ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Generation | Ollama local HTTP API | A backend-only adapter with a configurable installed local model and visible failure states. | | Grammar | LanguageTool Java HTTP server | Reuse existing local language rules rather than writing a grammar engine. | ## Before you start Have every one of these ready. The plan assumes them from step one. - [ ] **Python 3.12 or newer and a terminal** · Python is free; this local prototype requires no hosting subscription. - Why: The local backend, tests and storage use Python. - Get it: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. - Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. - [ ] **A current desktop browser and text editor** · No paid service required for this local step. - Why: You need to view the local interface and edit generated project files. - Get it: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. - Verify: You can create a text file in the project folder and open browser developer tools. - [ ] **Grammarly acceptance sample** · No paid service required for this local step. - Why: This fixture makes the first end-to-end check reproducible. - Get it: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. - Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. - [ ] **Confirm the bounded replacement** · No paid service required for this local step. - Why: The full commercial product is larger than this guide. - Get it: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. - Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. - [ ] **Ollama with an explicitly local model** (optional) · No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - Why: Generation requires a running model; ordinary editing remains usable while it is unavailable. - Get it: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. - Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. - [ ] **LanguageTool Java HTTP server** · Local basic engine; premium cloud-only rules are outside this build. - Why: The app reuses the existing grammar engine. - Get it: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. - Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. ## Quick start ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` Then copy `.env.example` to `.env` and fill in the values it documents. ## Honest limits This build deliberately does not replace: - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling If one of those is essential to you, that is the reason to keep paying for Grammarly, and the README should say so rather than pretend.
# Build brief · Grammarly The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a local writing checker with rule suggestions and optional accepted rewrites as a bounded replacement for Grammarly. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Generation: Ollama local HTTP API. A backend-only adapter with a configurable installed local model and visible failure states. - Grammar: LanguageTool Java HTTP server. Reuse existing local language rules rather than writing a grammar engine. ### Data model (create this before Phase 1) - documents(id,title,text,revision) - issues(id,document_id,revision,offset,length,rule_id,message,replacements_json) - dictionary(word) - rewrites(id,document_id,revision,mode,proposal,state) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: A short paragraph with a misspelling, an emoji before it and a protected proper name. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - Grammarly acceptance sample: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - Ollama with an explicitly local model: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. Cost: No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - LanguageTool Java HTTP server: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. Cost: Local basic engine; premium cloud-only rules are outside this build. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, OLLAMA_URL, LOCAL_MODEL, LANGUAGETOOL_URL. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Commands, after creating the named files: `python scripts/model_probe.py`. - In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Commands, after creating the named files: `java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start local grammar service until these checks pass. ### Phase 2 · Local grammar service Build: Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The local server supplies basic rules; cloud-only AI checks are not included. Done when: A check returns a visible issue on the deliberate misspelling. Disconnecting the service shows retry guidance without deleting the draft. Do not build yet: Do not start safe inline replacement until these checks pass. ### Phase 3 · Safe inline replacement Build: Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. Done when: Accepting the correction changes only the intended word after the emoji. Editing the draft during a check invalidates stale suggestions. Do not build yet: Do not start optional rewrite and cli until these checks pass. ### Phase 4 · Optional rewrite and CLI Build: Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. Done when: Rejecting a rewrite preserves the original document exactly. The CLI returns a failure status for the misspelling fixture and success after correction. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the Grammarly replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere: retain the paid product if this capability is essential; it is outside this bounded build. - document/email integrations: retain the paid product if this capability is essential; it is outside this bounded build. - tone/brand controls: retain the paid product if this capability is essential; it is outside this bounded build. - enterprise admin: retain the paid product if this capability is essential; it is outside this bounded build. - polished false-positive handling: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.ollama.com/api/chat ; https://docs.ollama.com/cloud ; https://dev.languagetool.org/http-server. Recheck before upgrading; freeze the versions actually tested.
# Agent instructions · Grammarly indie build - Read `README.md` and `BUILD_PLAN.md` before writing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, Ollama local HTTP API, LanguageTool Java HTTP server. Do not substitute. - Work one phase at a time, in order. Do not start a phase until every "Done when" item of the previous one passes. - Prefer the fewest moving parts that satisfy the step. No frameworks, services or dependencies the plan does not name. - Secrets live in `.env`, never in source or logs. Keep `.env.example` current when a variable is introduced. - Do not invent cryptography, security guarantees, APIs or compliance claims. - Add a focused test for every destructive, security-sensitive or data-loss path the plan names. - Run the project checks before declaring a phase complete, and record any deliberate shortcut in the README under "Tradeoffs". ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The local server supplies basic rules; cloud-only AI checks are not included. - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - Export without an import or restore rehearsal is not verified portability.
# Build plan · Grammarly Build a local writing checker with rule suggestions and optional accepted rewrites. Phases are in dependency order. Each ends in a "Done when" list; treat an unticked item as a blocker, not a note. ## Phase 1 · Local foundation and data contract Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Verify the selected local model Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Files: `providers/local_model.py`, `scripts/model_probe.py` ```sh python scripts/model_probe.py ``` 5. Start the grammar service In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Files: `providers/grammar.py` ```sh java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081 ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## Phase 2 · Local grammar service Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. ### Steps 1. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Files: `features/local_grammar_service.py`, `templates/local_grammar_service.html` 2. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Files: `features/local_grammar_service.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_local_grammar_service.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Disconnecting the service shows retry guidance without deleting the draft. ### Watch out - The local server supplies basic rules; cloud-only AI checks are not included. ## Phase 3 · Safe inline replacement Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. ### Steps 1. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Files: `features/safe_inline_replacement.py`, `templates/safe_inline_replacement.html` 2. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Files: `features/safe_inline_replacement.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_safe_inline_replacement.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Editing the draft during a check invalidates stale suggestions. ### Watch out - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. ## Phase 4 · Optional rewrite and CLI Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. ### Steps 1. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Files: `features/optional_rewrite_and_cli.py`, `templates/optional_rewrite_and_cli.html` 2. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Files: `features/optional_rewrite_and_cli.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_optional_rewrite_and_cli.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] The CLI returns a failure status for the misspelling fixture and success after correction. ### Watch out - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. ## Phase 5 · Portable delivery and clean-start proof Finish the Grammarly replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## Not in this build - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling ## After v1, if you want it - Extend optional rewrite and cli only after the fixture and recovery checks pass. - Before adding another integration, document its credentials, limits, cost and failure behavior with primary-source links.
# Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/grammarly # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Keep the inference service bound to loopback; the backend calls it, never the public browser. OLLAMA_URL=http://127.0.0.1:11434 # Optional. Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. LOCAL_MODEL=replace-with-installed-local-model # Required. The loopback Java server started from the official distribution; Python proxies checks to it. LANGUAGETOOL_URL=http://127.0.0.1:8081
# Grammarly · product brief ## Problem You can build grammar checks and rewrites, but Grammarly's moat is cross-app extensions, inline UX, enterprise controls, writing telemetry, and long-running language quality. ## Product outcome An operated version of a local writing checker with rule suggestions and optional accepted rewrites, with authorized access, restore evidence and honest scope limits. ## Target user A builder who needs a maintainable product foundation, not a one-off demo. ## Required capabilities - grammar engine/API - LLM API - browser extension - optional desktop accessibility layer - user dictionary ## Explicit non-goals for v1 - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere - document/email integrations - tone/brand controls - enterprise admin - polished false-positive handling ## Success criteria - A check returns a visible issue on the deliberate misspelling. - Accepting the correction changes only the intended word after the emoji. - Rejecting a rewrite preserves the original document exactly. - A private-data authorization check passes using a second identity. - An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - README names the excluded vendor capabilities and actual provider/hosting costs.
# Build brief · Grammarly The one-shot brief this plan expands. `BUILD_PLAN.md` (or `MILESTONES.md`) is the same sequence broken into steps and checks; where the two disagree, the plan wins. Build me a local writing checker with rule suggestions and optional accepted rewrites as a bounded replacement for Grammarly. Build it in phases in the order below. Do not write the whole product in one pass. Finish the current phase, run its Done when checks, fix failures, then continue. Indie mode completes Phases 1-5. Phase 6 is required before shared or public deployment. ### Stack (fixed, do not substitute) - Runtime: Python 3.12+ and Flask. A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. - Storage: SQLite through Python sqlite3. Local ownership with explicit transactions and a portable backup path. - Interface: Jinja HTML templates, CSS and vanilla JavaScript. Implement the specified screens directly with labelled controls and progressive enhancement. - Verification: Python unittest and browser acceptance fixtures. Check invariants and the actual user workflow before the next phase. - Generation: Ollama local HTTP API. A backend-only adapter with a configurable installed local model and visible failure states. - Grammar: LanguageTool Java HTTP server. Reuse existing local language rules rather than writing a grammar engine. ### Data model (create this before Phase 1) - documents(id,title,text,revision) - issues(id,document_id,revision,offset,length,rule_id,message,replacements_json) - dictionary(word) - rewrites(id,document_id,revision,mode,proposal,state) - Use stable ids and explicit relationships; add auxiliary tables named by the phases before those phases use them. - Acceptance fixture: A short paragraph with a misspelling, an emoji before it and a protected proper name. ### Prerequisites and configuration - Python 3.12 or newer and a terminal: Install Python from python.org. Open a terminal in a new empty project folder. On Windows, use py -3 where this guide says python if python is not on PATH; on macOS/Linux use python3 if needed. Create .venv and activate it before installing packages. Verify: python --version reports 3.12+ and python -c "import sqlite3" succeeds. Cost: Python is free; this local prototype requires no hosting subscription. - A current desktop browser and text editor: Use an installed Chrome, Firefox or Edge browser. Open the empty project folder in your editor; open the terminal there, not in this catalog repository. Verify: You can create a text file in the project folder and open browser developer tools. Cost: No paid service required for this local step. - Grammarly acceptance sample: Create synthetic sample data before implementation: A short paragraph with a misspelling, an emoji before it and a protected proper name. Save it under fixtures/ with the expected results in fixtures/README.md; use no real credentials or customer records. Verify: The fixture files and expected outcomes exist and can be inspected without a vendor account. Cost: No paid service required for this local step. - Confirm the bounded replacement: The deliverable is a local writing checker with rule suggestions and optional accepted rewrites. Read every exclusion below. Indie mode runs locally; any public or shared use requires the product access and deployment gates first. Verify: You can name the primary workflow and the vendor features this version deliberately leaves out. Cost: No paid service required for this local step. - Ollama with an explicitly local model: Install Ollama from the official site, choose a locally runnable model from its library that fits available RAM, download it, and copy its exact installed name into LOCAL_MODEL. Use the documented local-only configuration, exclude cloud model names, and record model license, download size and tested memory use. Verify: ollama list shows the chosen model; a short local prompt succeeds with network access disabled after download. Cost: No cloud inference fee for this local configuration; you supply disk space, compute and electricity. - LanguageTool Java HTTP server: Follow the official server page: install a compatible Java runtime, download and unzip the LanguageTool server distribution, create server.properties, then start the server using the command in the first phase. Do not install an assumed official Docker image. Verify: java -version succeeds and http://localhost:8081/v2/check?language=en-US&text=my+text returns JSON. Cost: Local basic engine; premium cloud-only rules are outside this build. - Configuration: DATA_DIR, SECRET_KEY, APP_MODE, SITE_URL, OLLAMA_URL, LOCAL_MODEL, LANGUAGETOOL_URL. Ship .env.example, replace placeholders and exclude secrets from git. ### Phase 1 · Local foundation and data contract Build: Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. - Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Commands, after creating the named files: `python -m venv .venv`; `python -m pip install Flask Flask-WTF python-dotenv waitress tzdata`; `python -m pip freeze > requirements.txt`; `python -m flask --app app run --host 127.0.0.1`. - For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Commands, after creating the named files: `python manage.py init`; `python manage.py seed`. - Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. - Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Commands, after creating the named files: `python scripts/model_probe.py`. - In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Commands, after creating the named files: `java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081`. - Trap: The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. Done when: The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. Restarting preserves the seeded records or canonical files; running init again deletes nothing. A cross-origin state-changing request to an admin route is refused. Do not build yet: Do not start local grammar service until these checks pass. ### Phase 2 · Local grammar service Build: Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. - Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: The local server supplies basic rules; cloud-only AI checks are not included. Done when: A check returns a visible issue on the deliberate misspelling. Disconnecting the service shows retry guidance without deleting the draft. Do not build yet: Do not start safe inline replacement until these checks pass. ### Phase 3 · Safe inline replacement Build: Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. - Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. Done when: Accepting the correction changes only the intended word after the emoji. Editing the draft during a check invalidates stale suggestions. Do not build yet: Do not start optional rewrite and cli until these checks pass. ### Phase 4 · Optional rewrite and CLI Build: Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. - Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. - Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Commands, after creating the named files: `python -m unittest discover -s test`. - Trap: This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. Done when: Rejecting a rewrite preserves the original document exactly. The CLI returns a failure status for the misspelling fixture and success after correction. Do not build yet: Do not start portable delivery and clean-start proof until these checks pass. ### Phase 5 · Portable delivery and clean-start proof Build: Finish the Grammarly replacement with a documented first-run path and a recoverable export. - Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. - Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. - Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Commands, after creating the named files: `python -m pip install -r requirements.txt`; `python -m unittest discover -s test`. - Trap: Export without an import or restore rehearsal is not verified portability. Done when: A new folder reaches the documented fixture outcome using only README instructions. A backup restored in isolation preserves the proof data and can be opened. Do not build yet: Do not start operate and share with access controls until these checks pass. ### Phase 6 · Operate and share with access controls (product-builder only) Build: Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. - Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. - Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Commands, after creating the named files: `waitress-serve --listen=127.0.0.1:5000 app:app`. - Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. - Trap: Product mode is additional engineering, not a switch that makes a local prototype production-ready. Done when: An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. Do not build yet: Do not add new providers or vendor-scale features until the release gates are recorded. ### Out of scope (and why) - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - This is a local writing checker with rule suggestions and optional accepted rewrites; full Grammarly feature parity, vendor hosting and support are not included. - inline suggestions everywhere: retain the paid product if this capability is essential; it is outside this bounded build. - document/email integrations: retain the paid product if this capability is essential; it is outside this bounded build. - tone/brand controls: retain the paid product if this capability is essential; it is outside this bounded build. - enterprise admin: retain the paid product if this capability is essential; it is outside this bounded build. - polished false-positive handling: retain the paid product if this capability is essential; it is outside this bounded build. ### README must contain - Exact install, configure, initialize, start, test and recovery commands for a clean folder. - The schema, fixture, acceptance results, private data locations and export format. - Every prerequisite and secret source, actual running costs and deliberately excluded capabilities. - An honest distinction between tests actually run and checks still awaiting real credentials or deployment. - Dependency documentation reviewed 2026-09-05: https://flask.palletsprojects.com/en/stable/installation/ ; https://docs.python.org/3/library/sqlite3.html ; https://flask-wtf.readthedocs.io/en/1.2.x/csrf/ ; https://docs.pylonsproject.org/projects/waitress/en/stable/usage.html ; https://docs.ollama.com/api/chat ; https://docs.ollama.com/cloud ; https://dev.languagetool.org/http-server. Recheck before upgrading; freeze the versions actually tested.
# Architecture · Grammarly ## Stack | Part | Choice | Why | | --- | --- | --- | | Runtime | Python 3.12+ and Flask | A small local HTTP application with readable server-side handlers and no JavaScript build pipeline. | | Storage | SQLite through Python sqlite3 | Local ownership with explicit transactions and a portable backup path. | | Interface | Jinja HTML templates, CSS and vanilla JavaScript | Implement the specified screens directly with labelled controls and progressive enhancement. | | Verification | Python unittest and browser acceptance fixtures | Check invariants and the actual user workflow before the next phase. | | Generation | Ollama local HTTP API | A backend-only adapter with a configurable installed local model and visible failure states. | | Grammar | LanguageTool Java HTTP server | Reuse existing local language rules rather than writing a grammar engine. | ## Modules Each module has one owner concern and a documented way to replace it. | Module | Owns | How to replace it | | --- | --- | --- | | Data and identity | documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state) | Keep stable ids and a versioned repository interface; migrate storage behind it with a fixture round-trip. | | Local grammar service | Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. | Keep the acceptance contract: A check returns a visible issue on the deliberate misspelling. Replace only this module after replaying its fixture; preserve ids and existing records. | | Safe inline replacement | Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. | Keep the acceptance contract: Accepting the correction changes only the intended word after the emoji. Replace only this module after replaying its fixture; preserve ids and existing records. | | Optional rewrite and CLI | Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. | Keep the acceptance contract: Rejecting a rewrite preserves the original document exactly. Replace only this module after replaying its fixture; preserve ids and existing records. | | Operations | Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. | Change host or backup destination only after an isolated restore and authorization check. | ## Configuration Every runtime setting is an environment variable documented in `.env.example`, validated at startup, with a safe local default wherever one exists. - `DATA_DIR` · required · A new private folder this application creates on first run; never serve it as static files. - `SECRET_KEY` · required, secret · Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. - `APP_MODE` · required · Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. - `SITE_URL` · required · The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. - `OLLAMA_URL` · required · Keep the inference service bound to loopback; the backend calls it, never the public browser. - `LOCAL_MODEL` · optional · Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. - `LANGUAGETOOL_URL` · required · The loopback Java server started from the official distribution; Python proxies checks to it. ## Production baseline - Security: least privilege, input validation at every boundary, secret redaction in logs, rate limits on abuse-prone paths, no invented security primitives. - Data: explicit schema and migrations, transactional writes where integrity matters, backup and restore procedures that have been exercised. - Integrations: adapters around third-party providers, idempotent webhook or job processing, bounded retries, timeouts. - Observability: structured logs with request or operation ids, an error-tracking hook, and health and readiness checks where a server exists. - Quality: unit tests for domain rules, integration tests at module boundaries, one end-to-end test of the critical path. ## Decision records For each dependency in the stack table, keep a short note: why it was chosen, its failure mode, and how it is replaced. Do not add infrastructure until a requirement in `PRODUCT.md` justifies it.
# Agent instructions · Grammarly product build - Read `PRODUCT.md` and `ARCHITECTURE.md` before changing code. The stack is fixed: Python 3.12+ and Flask, SQLite through Python sqlite3, Jinja HTML templates, CSS and vanilla JavaScript, Python unittest and browser acceptance fixtures, Ollama local HTTP API, LanguageTool Java HTTP server. - Implement milestone by milestone from `MILESTONES.md`; keep each change reviewable and leave the application runnable at every commit. - Treat authentication, payments, encryption, imports, webhooks and destructive actions as high-risk boundaries when present. - Never invent cryptography or silently weaken a requirement to make a check pass. - Put every external service behind an interface with a deterministic fake for tests. - Add migrations and rollback or recovery notes for every persistent data change. - Log useful operational context without credentials, tokens, passwords or personal data. - Update documentation and run every check before completing a milestone. ## Known traps - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. - The local server supplies basic rules; cloud-only AI checks are not included. - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. - Export without an import or restore rehearsal is not verified portability. - Product mode is additional engineering, not a switch that makes a local prototype production-ready.
# Delivery milestones · Grammarly Estimated effort: **multi-day** for the indie phases; the production-only milestones add the trust and operability layer. ## M1 · Local foundation and data contract Create the runnable local foundation for a local writing checker with rule suggestions and optional accepted rewrites, including the real schema and acceptance fixture. ### Steps 1. Create and start the local application Run the venv command first, then stop and activate it before running the remaining commands. Use your OS instructions: Windows .venv\Scripts\activate.bat in cmd, or .venv\Scripts\Activate.ps1 in PowerShell; macOS/Linux source .venv/bin/activate. Then install the listed packages. Create app.py exposing app, load .env with python-dotenv, and add a /healthz route. Freeze tested dependency versions to requirements.txt. Create .env manually from .env.example; replace SECRET_KEY before launch. Files: `app.py`, `requirements.txt`, `.env.example`, `.gitignore` ```sh python -m venv .venv python -m pip install Flask Flask-WTF python-dotenv waitress tzdata python -m pip freeze > requirements.txt python -m flask --app app run --host 127.0.0.1 ``` 2. Implement storage and seed the named fixture For database-backed state create schema.sql and db.py using this model: documents(id,title,text,revision); issues(id,document_id,revision,offset,length,rule_id,message,replacements_json); dictionary(word); rewrites(id,document_id,revision,mode,proposal,state). Add the auxiliary relationships explicitly used in later phases; use stable ids, foreign keys, parameterized values and transactions. For canonical files use atomic replacement and hashes instead. Implement python manage.py init and python manage.py seed to create only synthetic data: A short paragraph with a misspelling, an emoji before it and a protected proper name. Re-running init must not erase data. Files: `schema.sql`, `db.py`, `manage.py`, `fixtures/README.md` ```sh python manage.py init python manage.py seed ``` 3. Protect the local request boundary Install Flask-WTF CSRF protection for forms and same-origin fetches, validate Host and Origin against SITE_URL, bound inputs and escape output. Deliberately public intake endpoints get bounded validation and rate limits; signed provider webhooks use signature checks instead of browser CSRF tokens. All other admin routes stay local until product authentication exists. When a later phase tests viewer/member permissions, implement the users, hashed passwords, expiring server sessions and role checks in this foundation first; product mode must never use a fabricated identity from request input. Add error, empty, keyboard-focus and retry states now. Files: `app.py`, `templates/base.html`, `test/test_foundation.py` 4. Verify the selected local model Create providers/local_model.py with a POST /api/chat adapter using the configured local model and stream:false. Validate structured output, bound input/output, set a timeout and reject cloud models or non-loopback inference URLs. Add a probe that sends one harmless prompt and a test double for deterministic tests. Missing model setup must disable generation with a specific error while leaving editing usable. Files: `providers/local_model.py`, `scripts/model_probe.py` ```sh python scripts/model_probe.py ``` 5. Start the grammar service In the unzipped LanguageTool distribution create an empty server.properties and run the command below in a separate terminal. Keep the default local-only binding and proxy requests through Python; no browser-wide CORS permission is needed. Files: `providers/grammar.py` ```sh java -cp languagetool-server.jar org.languagetool.server.HTTPServer --config server.properties --port 8081 ``` ### Done when - [ ] The documented start command serves /healthz and the initial screen at http://127.0.0.1:5000. - [ ] Restarting preserves the seeded records or canonical files; running init again deletes nothing. - [ ] A cross-origin state-changing request to an admin route is refused. ### Watch out - The Flask development server is for local development only. Loopback binding alone does not replace CSRF and origin validation. ## M2 · Local grammar service Local grammar service for Grammarly: Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. ### Steps 1. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Start the LanguageTool Java HTTP server locally from the official distribution and connect through the Python backend using POST /v2/check. Files: `features/local_grammar_service.py`, `templates/local_grammar_service.html` 2. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Record the input revision with returned offsets; show explicit language selection and ignore configured dictionary words. Files: `features/local_grammar_service.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: A check returns a visible issue on the deliberate misspelling. Then check: Disconnecting the service shows retry guidance without deleting the draft. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_local_grammar_service.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Disconnecting the service shows retry guidance without deleting the draft. ### Watch out - The local server supplies basic rules; cloud-only AI checks are not included. ## M3 · Safe inline replacement Safe inline replacement for Grammarly: Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. ### Steps 1. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Map LanguageTool offsets to browser string positions carefully and highlight the fixture error after an emoji. Files: `features/safe_inline_replacement.py`, `templates/safe_inline_replacement.html` 2. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Apply one suggestion only if the document revision still matches, then rerun checking rather than shifting all saved offsets. Files: `features/safe_inline_replacement.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Accepting the correction changes only the intended word after the emoji. Then check: Editing the draft during a check invalidates stale suggestions. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_safe_inline_replacement.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Editing the draft during a check invalidates stale suggestions. ### Watch out - Offset conventions across Java, Python and JavaScript can differ around non-BMP characters. ## M4 · Optional rewrite and CLI Optional rewrite and CLI for Grammarly: Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. ### Steps 1. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Add optional local-model tighten/friendlier/formal modes with side-by-side diff and explicit acceptance. Files: `features/optional_rewrite_and_cli.py`, `templates/optional_rewrite_and_cli.html` 2. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Expose a check-file CLI using the same service and dictionary, with nonzero exit when issues remain. Files: `features/optional_rewrite_and_cli.py` 3. Exercise the acceptance fixture Use A short paragraph with a misspelling, an emoji before it and a protected proper name. Check: Rejecting a rewrite preserves the original document exactly. Then check: The CLI returns a failure status for the misspelling fixture and success after correction. Add a focused regression for the failure case under test/ using a temporary database or folder and fake external services; also perform the visible workflow in a browser. Files: `test/test_optional_rewrite_and_cli.py` ```sh python -m unittest discover -s test ``` ### Done when - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] The CLI returns a failure status for the misspelling fixture and success after correction. ### Watch out - This is a destination editor; system-wide inline checking and proprietary tone models are not reproduced. ## M5 · Portable delivery and clean-start proof Finish the Grammarly replacement with a documented first-run path and a recoverable export. ### Steps 1. Write the user-facing runbook Document prerequisites, every configuration variable, data locations and the three domain workflows: Local grammar service; Safe inline replacement; Optional rewrite and CLI. Include the exclusions, actual costs and source check date 2026-09-05. Commands shown earlier that reference project files are files the builder must implement before running them. Files: `README.md`, `.env.example` 2. Create and rehearse a recoverable backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Files: `OPERATIONS.md`, `scripts/backup.py` 3. Reproduce the first-run experience Use a new folder and only README instructions to reach the fixture outcome. Install from requirements.txt, initialize storage, run the tests and exercise the UI at 375px and 1280px; use keyboard-only controls and inspect browser errors. Record exactly what passed; do not mark unrun checks complete. Files: `README.md`, `verification.md` ```sh python -m pip install -r requirements.txt python -m unittest discover -s test ``` ### Done when - [ ] A new folder reaches the documented fixture outcome using only README instructions. - [ ] A backup restored in isolation preserves the proof data and can be opened. ### Watch out - Export without an import or restore rehearsal is not verified portability. ## M6 · Operate and share with access controls (production only) Product-builder only: make a local writing checker with rule suggestions and optional accepted rewrites operable for its stated audience before allowing remote access. ### Steps 1. Establish owner access before exposure Add owner/member/viewer authorization as appropriate, password hashes through Werkzeug, expiring server-side sessions, CSRF and login rate limits. Add users, sessions and audit schema migrations plus an owner-init command prompting securely for its password. Enforce ownership on every private read/write/download and fail closed when product setup is incomplete. Existing learner or admin identities must use this same boundary. Files: `ARCHITECTURE.md`, `OPERATIONS.md` 2. Deploy a monitored service Serve app:app with Waitress on loopback behind Caddy HTTPS. Configure trusted proxy headers narrowly, Secure/HttpOnly/SameSite cookies, upload limits, request ids and structured logs without private content. Run background jobs as a separate supervised process when the domain workflow requires them. Files: `Caddyfile`, `OPERATIONS.md` ```sh waitress-serve --listen=127.0.0.1:5000 app:app ``` 3. Rehearse loss and recovery Add a scheduled encrypted off-host backup using this procedure: Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. Monitor health, disk space, failed jobs and backup age. Stop the service to test an alert; rehearse recovery with outbound effects disabled and record recovery time. Rotate any exposed credentials and require reconciliation before resuming queues. Files: `OPERATIONS.md`, `release-checklist.md` ### Done when - [ ] An unauthenticated visitor cannot read private records, download private files or mutate the admin surface. - [ ] A viewer cannot mutate data by making a direct request, and guessed ids cannot cross ownership boundaries. - [ ] Stopping the service triggers the configured alert and the latest off-host backup restores the fixture in isolation. ### Watch out - Product mode is additional engineering, not a switch that makes a local prototype production-ready.
# Operations · Grammarly ## Backup Use sqlite3.Connection.backup for the database in DATA_DIR and pause writers while taking the matching attachment snapshot. Keep schema version, hashes and a manifest for grammarly. ## Restore Restore into a separate empty directory or isolated deployment, with all outbound actions and schedules disabled. Recreate this proof: A short paragraph with a misspelling, an emoji before it and a protected proper name. Compare ids/counts and open the result before recording the restore date. Never test a restore over the only live copy. Do a restore drill before the first real user, and write the date here when it passes. ## Monitoring Check HTTP availability, free disk, backup age and domain failures for Local grammar service, Safe inline replacement, Optional rewrite and CLI. Alert without logging private payloads. ## Incident checklist Pause outbound jobs and public intake as appropriate, preserve redacted diagnostics, restore an isolated verified backup, rotate affected credentials and reconcile uncertain effects before reopening. 1. Contain the issue without destroying evidence or user data. 2. Record the timeline and affected scope. 3. Rotate exposed secrets and revoke compromised sessions or credentials. 4. Restore from a verified backup when needed. 5. Document the root cause, the remediation and the regression test. ## Release gate - [ ] A check returns a visible issue on the deliberate misspelling. - [ ] Accepting the correction changes only the intended word after the emoji. - [ ] Rejecting a rewrite preserves the original document exactly. - [ ] A private-data authorization check passes using a second identity. - [ ] An off-host restore drill has a date, observed result and recovery time in OPERATIONS.md. - [ ] README names the excluded vendor capabilities and actual provider/hosting costs. ## Launch constraint Do not market omitted Grammarly capabilities as implemented. The non-goals in `PRODUCT.md` remain user-visible limitations until they are deliberately delivered.
# Copy to .env and fill in. Never commit .env; this file documents it. # Required. A new private folder this application creates on first run; never serve it as static files. DATA_DIR=./data/grammarly # Required · secret. Generate with python -c "import secrets; print(secrets.token_hex(32))" and save only in .env. SECRET_KEY=replace-with-a-random-secret # Required. Use indie for loopback-only personal work. Product mode must refuse to start until owner login and the deployment gates are configured. APP_MODE=indie # Required. The origin used for local forms and links; replace with the chosen HTTPS origin in product mode. SITE_URL=http://127.0.0.1:5000 # Required. Keep the inference service bound to loopback; the backend calls it, never the public browser. OLLAMA_URL=http://127.0.0.1:11434 # Optional. Copy the exact non-cloud name from ollama list; preflight must reject this placeholder. LOCAL_MODEL=replace-with-installed-local-model # Required. The loopback Java server started from the official distribution; Python proxies checks to it. LANGUAGETOOL_URL=http://127.0.0.1:8081
$ choose a build depth, inspect the files, then open the complete pack in your agent
They pay because suggestions appear inside the apps where writing actually happens.
xinline suggestions everywhere
xdocument/email integrations
xtone/brand controls
xenterprise admin
xpolished false-positive handling
Don't feel like building it? These folks already made it free.
all 4 free alternatives to Grammarly →· no votes, no pay-to-list · just what's real
Grammarly pricing
| plan | monthly | annual (per mo) | what you get |
|---|---|---|---|
| free | $0/user | $0/user | 100 generative-AI prompts/month. |
| pro | $30/user | $12/user | 2,000 AI prompts/member/month; up to 149 seats; 1 style guide; 1 brand tone; 2 groups. |
| enterprise | custom | — | Unlimited prompts, members, style guides, brand tones, and groups. |
free tier100 generative-AI prompts/month
billingmonthly + quarterly + annual for Pro; Enterprise is custom
hidden costsAdditional Pro seats are prorated. A 7-day trial is available only for eligible accounts.
verified 2026-08-12 · source ↗
Vibecode Grammarly
Kinda. The core of Grammarly is buildable in a weekend with the prompt on this page, but there are real gaps: inline suggestions everywhere, document/email integrations. Read the honest list above before committing.
How much does Grammarly cost?
Grammarly costs about $30/month (Pro, checked 2026-07-30), which is $360 per year.
What do I lose by replacing Grammarly?
Honestly: inline suggestions everywhere; document/email integrations; tone/brand controls; enterprise admin; polished false-positive handling. If any of those are load-bearing for you, keep paying.
Is there an open-source alternative to Grammarly?
Yes: Harper (A fast English grammar checker that stays on your device and mostly keeps its opinions to itself.) Writing Tools (Select text anywhere, hit a hotkey, and fix, rewrite, summarize, or obey a custom instruction without opening another tab.) WritingTool (A LibreOffice extension with long-document checks, style statistics, profiles, and local AI; installing Java is the cover charge.) All 4 curated free alternatives are at vibecodeit.com/grammarly/alternatives. The prompt is for when you want it exactly your way.