prosefix 0.3.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {prosefix-0.3.0 → prosefix-0.3.1}/PKG-INFO +13 -10
  2. {prosefix-0.3.0 → prosefix-0.3.1}/README.md +10 -7
  3. {prosefix-0.3.0 → prosefix-0.3.1}/man/prosefix.1 +63 -24
  4. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/__init__.py +1 -1
  5. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/cli.py +11 -4
  6. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/config.py +15 -8
  7. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/engine.py +63 -8
  8. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/jsonout.py +38 -8
  9. {prosefix-0.3.0 → prosefix-0.3.1}/pyproject.toml +2 -2
  10. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_cli.py +48 -9
  11. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_config.py +26 -0
  12. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_decide.py +97 -2
  13. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_engine.py +22 -0
  14. {prosefix-0.3.0 → prosefix-0.3.1}/.gitignore +0 -0
  15. {prosefix-0.3.0 → prosefix-0.3.1}/LICENSE +0 -0
  16. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/settings.py +0 -0
  17. {prosefix-0.3.0 → prosefix-0.3.1}/prosefix/tools.py +0 -0
  18. {prosefix-0.3.0 → prosefix-0.3.1}/tests/conftest.py +0 -0
  19. {prosefix-0.3.0 → prosefix-0.3.1}/tests/data/walkthrough.md +0 -0
  20. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_docs.py +0 -0
  21. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_settings.py +0 -0
  22. {prosefix-0.3.0 → prosefix-0.3.1}/tests/test_walkthrough.py +0 -0
  23. {prosefix-0.3.0 → prosefix-0.3.1}/tests/vault/obsidian.md +0 -0
  24. {prosefix-0.3.0 → prosefix-0.3.1}/tests/vault/off.md +0 -0
  25. {prosefix-0.3.0 → prosefix-0.3.1}/tests/vault/plain.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: prosefix
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Fix spelling, style, typos and punctuation in Markdown files, in place.
5
5
  Project-URL: Homepage, https://github.com/AndrewBroz/prosefix
6
6
  Project-URL: Issues, https://github.com/AndrewBroz/prosefix/issues
@@ -14,10 +14,10 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Topic :: Text Processing :: Markup :: Markdown
16
16
  Requires-Python: >=3.11
17
- Requires-Dist: adjudicate<0.4,>=0.3.6
17
+ Requires-Dist: adjudicate<0.4,>=0.3.7
18
18
  Requires-Dist: proofix<0.9,>=0.8.2
19
19
  Requires-Dist: pyyaml>=6
20
- Requires-Dist: stylefix<0.11,>=0.10.1
20
+ Requires-Dist: stylefix<0.11,>=0.10.2
21
21
  Description-Content-Type: text/markdown
22
22
 
23
23
  # prosefix
@@ -81,11 +81,13 @@ prosefix --doctor # tools found or missing, the endpoint, the settings file
81
81
 
82
82
  The endpoint comes from flags, `PROSEFIX_LLM_*` / `ADJUDICATE_LLM_*` environment variables, `~/.config/prosefix/config.toml` and `~/.config/adjudicate/config.toml`, never from a project file. Without a model, all rule-based tiers still run.
83
83
 
84
- **Questions without a model.** Some items need judgement but have a likely answer: a capitalised swap (`Color` to `Colour`), a serial comma, a number the guide may spell out, an abbreviation that may end a sentence, and a comma or full stop at a closing quote. Without a model, prosefix asks about each one whenever it can store your answer, that is, whenever it uses a decision cache. The question is listed for review, and the text is left as written. `--llm none` and `--no-cache` store nothing, so they do not ask: they apply the capitalised swap and list the others as plain review items. Before 0.3.0, only `--llm cached` asked.
84
+ **Questions without a model.** Some items need judgement but have a likely answer: a capitalised swap (`Color` to `Colour`), a serial comma, a number the guide may spell out, an abbreviation that may end a sentence, and a comma or full stop at a closing quote. Without a model, prosefix asks about each one whenever it can store your answer, that is, whenever it uses a decision cache. The question is listed for review, and the text is left as written. `--no-cache` reads and stores nothing, so it does not ask: it applies the capitalised swap and lists the others as plain review items. Before 0.3.0, only `--llm cached` asked.
85
+
86
+ **`--llm none`** contacts no model and reads only your own answers from the cache, never the model's. It applies them and asks the same questions as `--llm cached`, so the two write the same text when the cache holds only your answers. Before 0.3.1 it read no cache at all.
85
87
 
86
88
  ### Which English
87
89
 
88
- When nothing sets the variety (no `--target`, no project `target`, no front matter `prosefix: {target: …}` or `lang:`), prosefix reads the note and keeps the variety it is already written in. It counts the distinct words that only one variety spells that way (`colour`, `programme`, `finalise` against `color`, `program`, `finalize`), outside code and quotations; names, words in your accept lists and words both varieties accept do not count. Two or more British words, and at least twice as many as American ones, mean UK; the same the other way means US. A note with words of both varieties but no clear majority keeps its spellings as written (no variety conversion; everything else follows the US default), and a note with no such words at all uses US. The per-file line says which:
90
+ When nothing sets the variety (no `--target`, no project `target`, no front matter `prosefix: {target: …}` or `lang:`), prosefix reads the note and keeps the variety it is already written in. It counts the distinct words that only one variety spells that way (`colour`, `programme`, `finalise` against `color`, `program`, `finalize`), outside code and quotations; names, words in your accept lists and words both varieties accept do not count. Two or more British words, and at least twice as many as American ones, mean UK; the same the other way means US. A note with such words but no clear majority keeps its spellings, its outer quote marks and the order of its dates as written (no variety conversion; everything else follows the US default), and a note with no such words at all uses US. The per-file line says which:
89
91
 
90
92
  ```text
91
93
  prosefix: draft.md: en-GB (detected) · 6 change(s), 4 for review
@@ -184,25 +186,26 @@ The tiers are `variety`, `guide`, `ambiguous`, `numbers`, `serial-comma`, `abbre
184
186
  - `start` and `end`: UTF-16 offsets into `output`, not into the input, left out when they cannot be placed there;
185
187
  - `options`: the replacements on offer (keeping the text as written is always possible, and never listed);
186
188
  - `suggestion`: the model's pick even when it was too unsure to apply it, or null;
187
- - `confidence` and `reason`;
189
+ - `message`: the question in plain words, such as `Keep 'monday', or change it to 'Monday' or 'today'?`;
190
+ - `confidence` and `reason`: the model's reason, or why no model answered (`no model configured` or `model error`);
188
191
  - `explain`: a sentence or two on the rule, for the person answering, when the question has one;
189
192
  - `key`: what `--decide` takes.
190
193
 
191
- **One line per file.** `prosefix --json-lines` writes nothing to the notes either. It prints one line per file, `"type": "file"` followed by the file's entry, as each file finishes, in any order. Then it prints one `"type": "summary"` line with `schema`, `prosefix`, `endpoint` and `skipped`. Each line is compact JSON in ASCII. A file that fails, including a path that does not exist, gets a line with `"status": "error"`, and the exit status stays 0. A `--report` file that cannot be written makes it 2.
194
+ **One line per file.** `prosefix --json-lines` writes nothing to the notes either. It prints one line per file, `"type": "file"` followed by the file's entry, as each file finishes, in any order. Then it prints one `"type": "summary"` line with `schema`, `prosefix`, `endpoint` and `skipped`. `endpoint` is null when no model is used. Otherwise it has `url`, `model`, `source` and `error`: null, or the run's first model failure, given once rather than in every question. Each line is compact JSON in ASCII. A file that fails, including a path that does not exist, gets a line with `"status": "error"`, and the exit status stays 0. A `--report` file that cannot be written makes it 2.
192
195
 
193
196
  **Answers.** `prosefix --decide` reads answers as JSON on stdin and stores each in the cache that its note's path uses:
194
197
 
195
198
  ```json
196
199
  {"decisions":[
197
200
  {"path":"/v/essay.md","key":"3b9e0c1d2a4f5e6a7b8c9d0e","choice":"licence",
198
- "word":"license","options":["licence","license"]},
201
+ "word":"license","options":["licence","license"],"start":118,"end":125},
199
202
  {"path":"/v/essay.md","key":"…","choice":"KEEP"},
200
203
  {"path":"/v/notes.md","key":"…","choice":{"text":"licensed"}}]}
201
204
  ```
202
205
 
203
206
  `choice` is one of the options, `"KEEP"` to keep the text as written, or `{"text": …}` for your own words. It prints `{"written": 3, "caches": [...]}`. Malformed input prints `{"error": "…"}`, stores nothing and exits 2. The next run with the cache applies the answers, for example `prosefix --json-lines --llm cached /v/essay.md`.
204
207
 
205
- One answer can change the sentence of another question in the same note, and so that question's key. `word` is the text at the question's `start`:`end` in `output`. With `word` and `options`, prosefix carries such an answer over: an answer the run did not use moves to the one open question in the same note with the same word and options, and the note runs again, up to three times. An answer gets one chance to move: the next run of its note, normally the cached run right after `--decide`. An answer can also raise a question about the word it put in (`licence`, once chosen over `license`); prosefix answers that question `KEEP`.
208
+ One answer can change the sentence of another question in the same note, and so that question's key. `word` is the text at the question's `start`:`end` in `output`. With `word` and `options`, prosefix carries such an answer over: an answer the run did not use moves to the one open question in the same note with the same word and options, and the note runs again, up to three times. An answer gets one chance to move: the next run of its note, normally the cached run right after `--decide`. An answer also settles any other question on the same place, from either pass: once you choose `licence` over `license`, or keep `license`, prosefix doesn't ask whether that word should be the other one. It answers such a question `KEEP`. `start` and `end`, the question's UTF-16 offsets in `output`, give the place. Without them, only a question on the word an answer put in, with the same options, is settled.
206
209
 
207
210
  Known limits: an answer to a proofix compound question applies to every occurrence of that form. An answer whose edit overlaps a stylefix edit loses to it and is dropped without notice. An answer without `word` and `options` is not carried over.
208
211
 
@@ -212,7 +215,7 @@ Known limits: an answer to a proofix compound question applies to every occurren
212
215
  - `prosefix --check-endpoint --json [--url URL] [--model NAME]`: tests the endpoint and gives `ok`, `url`, `model`, `models`, `model_info`, `latency_ms` and `error`. `model_info` lists each model's `id` and `created` (Unix seconds, or null) in the server's order. It exits 1 when the test fails.
213
216
  - `prosefix --setup --url URL [--model NAME] [--thinking-switch] --json`: tests the endpoint and, only if the test passes, writes `~/.config/prosefix/config.toml` with mode 0600. It gives `ok`, `written`, `url`, `model` and `error`, and exits 1 when nothing was written.
214
217
 
215
- `--key-stdin` reads the API key from the first line of stdin; prosefix never prints it. It works only with `--check-endpoint --json` and `--setup --url … --json`, and `--thinking-switch` only with `--setup --url`; prosefix refuses them elsewhere, with exit status 2. Without `--key-stdin`, a `--url` equal to the one saved in prosefix's config file uses the saved key (`api_key`, or `api_key_env` by name), timeout and thinking switch, so a change of model keeps them. Another URL gets no key. The details are in the man page (`man prosefix`, or `man/prosefix.1` in the source).
218
+ `--key-stdin` reads the API key from the first line of stdin; prosefix never prints it. It works only with `--check-endpoint --json` and `--setup --url … --json`, and `--thinking-switch` only with `--setup --url`; prosefix refuses them elsewhere, with exit status 2. Without `--key-stdin`, a `--url` equal to the configured endpoint's uses its key, timeout and thinking switch, so a change of model keeps them. The configured endpoint is the one a plain run uses: from prosefix's config file, adjudicate's (`~/.config/adjudicate/config.toml`) or the `PROSEFIX_LLM_*` and `ADJUDICATE_LLM_*` variables. `--setup` writes a key that came from a variable as `api_key_env` naming it, never as its value. Another URL gets no key. The details are in the man page (`man prosefix`, or `man/prosefix.1` in the source).
216
219
 
217
220
  ## License
218
221
 
@@ -59,11 +59,13 @@ prosefix --doctor # tools found or missing, the endpoint, the settings file
59
59
 
60
60
  The endpoint comes from flags, `PROSEFIX_LLM_*` / `ADJUDICATE_LLM_*` environment variables, `~/.config/prosefix/config.toml` and `~/.config/adjudicate/config.toml`, never from a project file. Without a model, all rule-based tiers still run.
61
61
 
62
- **Questions without a model.** Some items need judgement but have a likely answer: a capitalised swap (`Color` to `Colour`), a serial comma, a number the guide may spell out, an abbreviation that may end a sentence, and a comma or full stop at a closing quote. Without a model, prosefix asks about each one whenever it can store your answer, that is, whenever it uses a decision cache. The question is listed for review, and the text is left as written. `--llm none` and `--no-cache` store nothing, so they do not ask: they apply the capitalised swap and list the others as plain review items. Before 0.3.0, only `--llm cached` asked.
62
+ **Questions without a model.** Some items need judgement but have a likely answer: a capitalised swap (`Color` to `Colour`), a serial comma, a number the guide may spell out, an abbreviation that may end a sentence, and a comma or full stop at a closing quote. Without a model, prosefix asks about each one whenever it can store your answer, that is, whenever it uses a decision cache. The question is listed for review, and the text is left as written. `--no-cache` reads and stores nothing, so it does not ask: it applies the capitalised swap and lists the others as plain review items. Before 0.3.0, only `--llm cached` asked.
63
+
64
+ **`--llm none`** contacts no model and reads only your own answers from the cache, never the model's. It applies them and asks the same questions as `--llm cached`, so the two write the same text when the cache holds only your answers. Before 0.3.1 it read no cache at all.
63
65
 
64
66
  ### Which English
65
67
 
66
- When nothing sets the variety (no `--target`, no project `target`, no front matter `prosefix: {target: …}` or `lang:`), prosefix reads the note and keeps the variety it is already written in. It counts the distinct words that only one variety spells that way (`colour`, `programme`, `finalise` against `color`, `program`, `finalize`), outside code and quotations; names, words in your accept lists and words both varieties accept do not count. Two or more British words, and at least twice as many as American ones, mean UK; the same the other way means US. A note with words of both varieties but no clear majority keeps its spellings as written (no variety conversion; everything else follows the US default), and a note with no such words at all uses US. The per-file line says which:
68
+ When nothing sets the variety (no `--target`, no project `target`, no front matter `prosefix: {target: …}` or `lang:`), prosefix reads the note and keeps the variety it is already written in. It counts the distinct words that only one variety spells that way (`colour`, `programme`, `finalise` against `color`, `program`, `finalize`), outside code and quotations; names, words in your accept lists and words both varieties accept do not count. Two or more British words, and at least twice as many as American ones, mean UK; the same the other way means US. A note with such words but no clear majority keeps its spellings, its outer quote marks and the order of its dates as written (no variety conversion; everything else follows the US default), and a note with no such words at all uses US. The per-file line says which:
67
69
 
68
70
  ```text
69
71
  prosefix: draft.md: en-GB (detected) · 6 change(s), 4 for review
@@ -162,25 +164,26 @@ The tiers are `variety`, `guide`, `ambiguous`, `numbers`, `serial-comma`, `abbre
162
164
  - `start` and `end`: UTF-16 offsets into `output`, not into the input, left out when they cannot be placed there;
163
165
  - `options`: the replacements on offer (keeping the text as written is always possible, and never listed);
164
166
  - `suggestion`: the model's pick even when it was too unsure to apply it, or null;
165
- - `confidence` and `reason`;
167
+ - `message`: the question in plain words, such as `Keep 'monday', or change it to 'Monday' or 'today'?`;
168
+ - `confidence` and `reason`: the model's reason, or why no model answered (`no model configured` or `model error`);
166
169
  - `explain`: a sentence or two on the rule, for the person answering, when the question has one;
167
170
  - `key`: what `--decide` takes.
168
171
 
169
- **One line per file.** `prosefix --json-lines` writes nothing to the notes either. It prints one line per file, `"type": "file"` followed by the file's entry, as each file finishes, in any order. Then it prints one `"type": "summary"` line with `schema`, `prosefix`, `endpoint` and `skipped`. Each line is compact JSON in ASCII. A file that fails, including a path that does not exist, gets a line with `"status": "error"`, and the exit status stays 0. A `--report` file that cannot be written makes it 2.
172
+ **One line per file.** `prosefix --json-lines` writes nothing to the notes either. It prints one line per file, `"type": "file"` followed by the file's entry, as each file finishes, in any order. Then it prints one `"type": "summary"` line with `schema`, `prosefix`, `endpoint` and `skipped`. `endpoint` is null when no model is used. Otherwise it has `url`, `model`, `source` and `error`: null, or the run's first model failure, given once rather than in every question. Each line is compact JSON in ASCII. A file that fails, including a path that does not exist, gets a line with `"status": "error"`, and the exit status stays 0. A `--report` file that cannot be written makes it 2.
170
173
 
171
174
  **Answers.** `prosefix --decide` reads answers as JSON on stdin and stores each in the cache that its note's path uses:
172
175
 
173
176
  ```json
174
177
  {"decisions":[
175
178
  {"path":"/v/essay.md","key":"3b9e0c1d2a4f5e6a7b8c9d0e","choice":"licence",
176
- "word":"license","options":["licence","license"]},
179
+ "word":"license","options":["licence","license"],"start":118,"end":125},
177
180
  {"path":"/v/essay.md","key":"…","choice":"KEEP"},
178
181
  {"path":"/v/notes.md","key":"…","choice":{"text":"licensed"}}]}
179
182
  ```
180
183
 
181
184
  `choice` is one of the options, `"KEEP"` to keep the text as written, or `{"text": …}` for your own words. It prints `{"written": 3, "caches": [...]}`. Malformed input prints `{"error": "…"}`, stores nothing and exits 2. The next run with the cache applies the answers, for example `prosefix --json-lines --llm cached /v/essay.md`.
182
185
 
183
- One answer can change the sentence of another question in the same note, and so that question's key. `word` is the text at the question's `start`:`end` in `output`. With `word` and `options`, prosefix carries such an answer over: an answer the run did not use moves to the one open question in the same note with the same word and options, and the note runs again, up to three times. An answer gets one chance to move: the next run of its note, normally the cached run right after `--decide`. An answer can also raise a question about the word it put in (`licence`, once chosen over `license`); prosefix answers that question `KEEP`.
186
+ One answer can change the sentence of another question in the same note, and so that question's key. `word` is the text at the question's `start`:`end` in `output`. With `word` and `options`, prosefix carries such an answer over: an answer the run did not use moves to the one open question in the same note with the same word and options, and the note runs again, up to three times. An answer gets one chance to move: the next run of its note, normally the cached run right after `--decide`. An answer also settles any other question on the same place, from either pass: once you choose `licence` over `license`, or keep `license`, prosefix doesn't ask whether that word should be the other one. It answers such a question `KEEP`. `start` and `end`, the question's UTF-16 offsets in `output`, give the place. Without them, only a question on the word an answer put in, with the same options, is settled.
184
187
 
185
188
  Known limits: an answer to a proofix compound question applies to every occurrence of that form. An answer whose edit overlaps a stylefix edit loses to it and is dropped without notice. An answer without `word` and `options` is not carried over.
186
189
 
@@ -190,7 +193,7 @@ Known limits: an answer to a proofix compound question applies to every occurren
190
193
  - `prosefix --check-endpoint --json [--url URL] [--model NAME]`: tests the endpoint and gives `ok`, `url`, `model`, `models`, `model_info`, `latency_ms` and `error`. `model_info` lists each model's `id` and `created` (Unix seconds, or null) in the server's order. It exits 1 when the test fails.
191
194
  - `prosefix --setup --url URL [--model NAME] [--thinking-switch] --json`: tests the endpoint and, only if the test passes, writes `~/.config/prosefix/config.toml` with mode 0600. It gives `ok`, `written`, `url`, `model` and `error`, and exits 1 when nothing was written.
192
195
 
193
- `--key-stdin` reads the API key from the first line of stdin; prosefix never prints it. It works only with `--check-endpoint --json` and `--setup --url … --json`, and `--thinking-switch` only with `--setup --url`; prosefix refuses them elsewhere, with exit status 2. Without `--key-stdin`, a `--url` equal to the one saved in prosefix's config file uses the saved key (`api_key`, or `api_key_env` by name), timeout and thinking switch, so a change of model keeps them. Another URL gets no key. The details are in the man page (`man prosefix`, or `man/prosefix.1` in the source).
196
+ `--key-stdin` reads the API key from the first line of stdin; prosefix never prints it. It works only with `--check-endpoint --json` and `--setup --url … --json`, and `--thinking-switch` only with `--setup --url`; prosefix refuses them elsewhere, with exit status 2. Without `--key-stdin`, a `--url` equal to the configured endpoint's uses its key, timeout and thinking switch, so a change of model keeps them. The configured endpoint is the one a plain run uses: from prosefix's config file, adjudicate's (`~/.config/adjudicate/config.toml`) or the `PROSEFIX_LLM_*` and `ADJUDICATE_LLM_*` variables. `--setup` writes a key that came from a variable as `api_key_env` naming it, never as its value. Another URL gets no key. The details are in the man page (`man prosefix`, or `man/prosefix.1` in the source).
194
197
 
195
198
  ## License
196
199
 
@@ -1,5 +1,5 @@
1
1
  '\" t
2
- .TH PROSEFIX 1 "November 2026" "prosefix 0.3.0" "User Commands"
2
+ .TH PROSEFIX 1 "November 2026" "prosefix 0.3.1" "User Commands"
3
3
  .SH NAME
4
4
  prosefix \- fix spelling, style, typos and punctuation in Markdown files, in place
5
5
  .SH SYNOPSIS
@@ -181,7 +181,10 @@ local Ollama.
181
181
  apply decisions already in the cache and never contact a model; items not in
182
182
  the cache are left as written and reported.
183
183
  .B none:
184
- rules only; the cache is neither read nor written, so nothing is asked (see
184
+ never contact a model and read only your own answers from the cache, never
185
+ the model's; it applies them and asks what
186
+ .B cached
187
+ asks (see
185
188
  .BR "REVIEW ITEMS" ).
186
189
  .TP
187
190
  .B \-\-url \fIURL\fR
@@ -195,9 +198,8 @@ Model name at the endpoint.
195
198
  Seconds per model request.
196
199
  .TP
197
200
  .B \-\-no\-cache
198
- Neither read nor write the decision cache. As with
199
- .BR "\-\-llm none" ,
200
- nothing is asked without a model.
201
+ Neither read nor write the decision cache. Nothing is asked without a model:
202
+ the capitalised swaps apply and other items are listed for review.
201
203
  .TP
202
204
  .B \-\-require \fITOOL\fR,...
203
205
  Exit 2 if any of
@@ -314,9 +316,9 @@ Capitalised words, words in the accept lists and words both varieties accept
314
316
  do not count, and a word counts once however often it appears. Two or more
315
317
  UK words and at least twice as many UK as US words mean UK; two or more US
316
318
  words and at least twice as many US as UK words mean US. Words of both
317
- varieties without such a majority leave the variety spellings as written: the
318
- spelling conversion is skipped for that note (everything else follows the US
319
- default). With no such words at all, the target is US. The per-file line
319
+ varieties without such a majority leave the variety spellings, the outer
320
+ quote marks and the order of dates as written: that conversion is skipped
321
+ for the note (everything else follows the US default). With no such words at all, the target is US. The per-file line
320
322
  says which:
321
323
  .PP
322
324
  .RS
@@ -372,13 +374,13 @@ that need judgement but have a likely answer: a capitalised swap (Color to
372
374
  Colour), a serial comma, a number the guide may spell out, an abbreviation
373
375
  that may end a sentence, and a comma or full stop at a closing quote. The
374
376
  text is left as written.
375
- .B "\-\-llm none"
376
- and
377
377
  .B \-\-no\-cache
378
- store nothing, so they do not ask: they apply the capitalised swap and list
379
- the others as plain review items. Before 0.3.0, only
378
+ reads and stores nothing, so it does not ask: it applies the capitalised swap
379
+ and lists the others as plain review items. Before 0.3.0, only
380
380
  .B "\-\-llm cached"
381
- asked.
381
+ asked. Before 0.3.1,
382
+ .B "\-\-llm none"
383
+ did not ask either.
382
384
  .PP
383
385
  The per-file and total lines go to standard output when the files are on
384
386
  disk, and to standard error when standard input is read (standard output then
@@ -557,7 +559,7 @@ prints one UTF\-8 document:
557
559
  .PP
558
560
  .RS
559
561
  .nf
560
- {"schema": 1, "prosefix": "0.3.0",
562
+ {"schema": 1, "prosefix": "0.3.1",
561
563
  "endpoint": {"url", "model", "source"} or null,
562
564
  "skipped": [{"what", "why", "fix"}],
563
565
  "files": [{"path", "status", "reason", "settings", "input_sha256",
@@ -685,8 +687,13 @@ and never listed.
685
687
  .B suggestion
686
688
  The model's pick, even when it was too unsure to apply it, or null.
687
689
  .TP
690
+ .B message
691
+ The question in plain words, for example
692
+ "Keep 'monday', or change it to 'Monday' or 'today'?".
693
+ .TP
688
694
  .BR confidence ", " reason
689
- The model's confidence (or null) and its reason.
695
+ The model's confidence (or null) and its reason, or why no model answered:
696
+ "no model configured" or "model error".
690
697
  .TP
691
698
  .B explain
692
699
  A sentence or two on the rule, for the person answering. Left out when the
@@ -715,6 +722,18 @@ holds
715
722
  .B endpoint
716
723
  and
717
724
  .BR skipped .
725
+ .B endpoint
726
+ is null when no model is used; otherwise it has
727
+ .BR url ,
728
+ .BR model ,
729
+ .B source
730
+ and
731
+ .BR error :
732
+ null, or the run's first model failure, given once rather than in every
733
+ question. The
734
+ .B \-\-json
735
+ document holds the same
736
+ .BR endpoint .
718
737
  Each line is ASCII, with other characters escaped, so a line break in the
719
738
  stream always ends a line. A file that fails, including a path that does not
720
739
  exist (reason "no such file"), gets a line with status
@@ -732,7 +751,8 @@ reads answers as JSON on standard input:
732
751
  .nf
733
752
  {"decisions": [
734
753
  {"path": "/v/essay.md", "key": "3b9e0c1d2a4f5e6a7b8c9d0e",
735
- "choice": "licence", "word": "license", "options": ["licence", "license"]},
754
+ "choice": "licence", "word": "license", "options": ["licence", "license"],
755
+ "start": 118, "end": 125},
736
756
  {"path": "/v/essay.md", "key": "...", "choice": "KEEP"},
737
757
  {"path": "/v/notes.md", "key": "...", "choice": {"text": "licensed"}}]}
738
758
  .fi
@@ -754,8 +774,16 @@ for your own words.
754
774
  in
755
775
  .BR output )
756
776
  and
757
- .B options
758
- are optional; copy them from the question. Each answer is stored with the
777
+ .BR options ,
778
+ .B start
779
+ and
780
+ .B end
781
+ are optional; copy them from the question.
782
+ .B start
783
+ and
784
+ .B end
785
+ are its UTF-16 offsets in
786
+ .BR output . Each answer is stored with the
759
787
  note's path in the cache that path uses: the project cache from its
760
788
  settings file, or the user cache. Every decision is checked before any is
761
789
  stored. On success prosefix prints
@@ -784,8 +812,14 @@ and
784
812
  .B \-\-check
785
813
  included.
786
814
  An
787
- applied answer can also raise a question about the word it put in (licence,
788
- once chosen over license); prosefix answers that question KEEP. Plain
815
+ answer also settles any other question on the same place, from either pass:
816
+ once licence is chosen over license, or license kept, prosefix does not ask
817
+ whether that word should be the other one, and answers such a question KEEP.
818
+ .B start
819
+ and
820
+ .B end
821
+ give the place; without them, only a question on the word an answer put in,
822
+ with the same options, is settled. Plain
789
823
  standard input without
790
824
  .B \-\-stdin\-filename
791
825
  has no path, so its answers are never carried over.
@@ -886,15 +920,20 @@ Without
886
920
  .BR \-\-key\-stdin ,
887
921
  a
888
922
  .B \-\-url
889
- equal to the url in prosefix's config file uses that file's api_key or
890
- api_key_env, timeout and thinking_switch, both in
923
+ equal to the configured endpoint's uses its api_key or api_key_env, timeout
924
+ and thinking_switch, both in
891
925
  .B \-\-check\-endpoint \-\-json
892
926
  and in
893
927
  .BR "\-\-setup \-\-url" ,
894
928
  so a change of model keeps them.
929
+ The configured endpoint is the one a plain run uses: from prosefix's config
930
+ file, adjudicate's, or the PROSEFIX_LLM_* and ADJUDICATE_LLM_* variables
931
+ (see
932
+ .BR ENVIRONMENT ).
895
933
  .B \-\-setup
896
- saves api_key_env as the variable's name, never its value; the test uses
897
- the variable when it is set. A different
934
+ saves api_key_env as the variable's name, never its value, and saves a key
935
+ from PROSEFIX_LLM_KEY or ADJUDICATE_LLM_KEY as api_key_env naming it; the
936
+ test uses the variable when it is set. A different
898
937
  .B \-\-url
899
938
  gets no key. A trailing slash and a trailing /chat/completions are removed
900
939
  from
@@ -1,3 +1,3 @@
1
1
  """prosefix: clean, consistent prose in Markdown."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.3.1"
@@ -286,6 +286,9 @@ def _decide() -> int:
286
286
  options = d.get("options", [])
287
287
  if not (isinstance(options, list) and all(isinstance(o, str) for o in options)):
288
288
  return error(f"{where}: options must be a list of strings")
289
+ span = [d.get("start"), d.get("end")]
290
+ if span != [None, None] and not (all(type(x) is int for x in span) and 0 <= span[0] <= span[1]):
291
+ return error(f"{where}: start and end must be given together, as offsets with start <= end")
289
292
  try:
290
293
  cache = cache_path(find_project(Path(d["path"])))
291
294
  except SettingsError as e:
@@ -293,6 +296,8 @@ def _decide() -> int:
293
296
  extra = {"path": str(Path(d["path"]).resolve()), "pending": True}
294
297
  if "options" in d:
295
298
  extra["options"] = options
299
+ if span != [None, None]:
300
+ extra["start"], extra["end"] = span
296
301
  plan.append((cache.absolute(), d["key"], choice, d.get("word", ""), extra))
297
302
  caches: dict[Path, Cache] = {}
298
303
  for path, key, choice, word, extra in plan:
@@ -450,10 +455,11 @@ def _main(argv=None) -> int:
450
455
  except ConfigError as e:
451
456
  _err(str(e))
452
457
  return 2
453
- mode = "off" if (args.no_cache or args.llm == "none") else "replay" if args.llm == "cached" else "use"
458
+ mode = ("off" if args.no_cache else "user" if args.llm == "none"
459
+ else "replay" if args.llm == "cached" else "use")
454
460
  # Ask about ambiguous items, even without a model, whenever an answer can be stored.
455
- # Every output mode then gives the same text, and the plain run and the --llm cached
456
- # run ask the same questions. --llm none and --no-cache apply the rules' defaults.
461
+ # Every output mode then gives the same text, and the plain run, --llm cached and
462
+ # --llm none ask the same questions. --no-cache applies the rules' defaults.
457
463
  replay = mode != "off"
458
464
 
459
465
  if args.require:
@@ -613,7 +619,8 @@ def _main(argv=None) -> int:
613
619
 
614
620
  n_changes = sum(len(r.changes) for r in changed)
615
621
  if args.json_lines:
616
- print(jsonout.line(jsonout.summary(ep, skipped_list), "summary"), flush=True)
622
+ print(jsonout.line(jsonout.summary(ep, skipped_list, jsonout.model_error(results)), "summary"),
623
+ flush=True)
617
624
  return 2 if report_failed else 0 # a file's failure is in its line
618
625
  if args.json:
619
626
  json.dump(jsonout.document(results, ep, skipped_list), sys.stdout, ensure_ascii=False, indent=1)
@@ -11,8 +11,8 @@ from pathlib import Path
11
11
  from typing import TextIO
12
12
 
13
13
  from adjudicate import ConfigError, resolve_endpoint
14
- from adjudicate.llm import (DEFAULT_TIMEOUT, Endpoint, LLMError, config_home, list_model_entries,
15
- read_config)
14
+ from adjudicate.llm import (DEFAULT_TIMEOUT, Endpoint, LLMError, config_home, configured_settings,
15
+ list_model_entries)
16
16
  from adjudicate.setup import PING, Prompter, save_config
17
17
 
18
18
  from . import __version__, tools
@@ -38,17 +38,24 @@ def normalize_url(url: str) -> str:
38
38
 
39
39
 
40
40
  def saved_for(url: str) -> dict:
41
- """The api_key or api_key_env, timeout and thinking_switch in prosefix's config file
42
- when that file's url is `url`, else {}. This lets a change of model keep the rest of
43
- the endpoint. api_key_env is the variable's name, not its value."""
41
+ """The api_key or api_key_env, timeout and thinking_switch of the configured endpoint
42
+ when its url is `url`, else {}. The configured endpoint is the one prosefix uses
43
+ without flags: from its config file, adjudicate's, or the *_LLM_* variables. This lets
44
+ a change of model keep the rest of the endpoint. A key is never read out of a
45
+ variable: api_key_env stays its name, and a key from PROSEFIX_LLM_KEY or
46
+ ADJUDICATE_LLM_KEY comes back as api_key_env naming that variable."""
44
47
  try:
45
- saved = read_config(config_path())
48
+ saved = configured_settings("prosefix")
46
49
  except ConfigError:
47
50
  return {}
48
51
  if "url" not in saved or normalize_url(saved["url"][0]) != normalize_url(url):
49
52
  return {}
50
- return {k: saved[k][0] for k in ("api_key", "api_key_env", "timeout", "thinking_switch")
51
- if k in saved}
53
+ out = {k: saved[k][0] for k in ("api_key", "api_key_env", "timeout", "thinking_switch")
54
+ if k in saved}
55
+ if "api_key" in saved and saved["api_key"][1].endswith("_LLM_KEY"): # env_layer's source: the name
56
+ out["api_key_env"] = saved["api_key"][1]
57
+ del out["api_key"]
58
+ return out
52
59
 
53
60
 
54
61
  def created(entry: dict) -> int | None:
@@ -19,6 +19,7 @@ from proofix.commas import CommaCache
19
19
  from stylefix import api as style
20
20
  from stylefix.cli import BUILTIN_ACCEPT
21
21
 
22
+ from .jsonout import utf16_offsets
22
23
  from .settings import FRONT, PROOF_TIERS, STYLE_TIERS, Settings
23
24
 
24
25
 
@@ -64,6 +65,16 @@ class SharedCache(_Flushable, Cache):
64
65
  return Cache.get(self, k)
65
66
 
66
67
 
68
+ class UserAnswers(SharedCache):
69
+ """The cache as --llm none sees it: the user's answers only. The model's
70
+ cached answers are never read, and never rewritten, since without a model
71
+ no new one arrives."""
72
+
73
+ def get(self, k: str) -> dict | None:
74
+ hit = SharedCache.get(self, k)
75
+ return hit if (hit or {}).get("decided_by") == "user" else None
76
+
77
+
67
78
  class SharedCommaCache(_Flushable, CommaCache):
68
79
  _base = CommaCache
69
80
 
@@ -94,13 +105,17 @@ _OPEN: dict[Path, Caches] = {}
94
105
 
95
106
 
96
107
  def caches_for(settings: Settings, mode: str) -> Caches:
97
- """mode: use (read and write), replay (read; written only if new answers arrive), off (none)."""
108
+ """mode: use (read and write), replay (read; written only if new answers arrive),
109
+ user (the user's answers only, for --llm none), off (none)."""
98
110
  if mode == "off" or settings.cache is None:
99
111
  return Caches(Cache(None), CommaCache(None))
100
112
  with _LOCK:
101
113
  if settings.cache not in _OPEN:
102
- _OPEN[settings.cache] = Caches(SharedCache(settings.cache),
103
- SharedCommaCache(settings.cache.with_name("commas.json")))
114
+ # comma placements are the model's: --llm none reads none of them
115
+ commas = (CommaCache(None) if mode == "user"
116
+ else SharedCommaCache(settings.cache.with_name("commas.json")))
117
+ answers = UserAnswers if mode == "user" else SharedCache
118
+ _OPEN[settings.cache] = Caches(answers(settings.cache), commas)
104
119
  return _OPEN[settings.cache]
105
120
 
106
121
 
@@ -266,9 +281,11 @@ def _carry_over(result: FileResult, path: Path, cache: SharedCache, used: list[d
266
281
  entries = cache.data.copy() # other workers add entries meanwhile
267
282
  pending = [(k, e) for k, e in entries.items()
268
283
  if e.get("pending") and e.get("path") == note and e.get("decided_by") == "user"]
269
- if not pending:
284
+ if not (pending or used):
270
285
  # A moved answer is pending, so the last call moved none: the text is as
271
286
  # it was then and nothing is left to settle. A big cache costs one pass.
287
+ # An answer used in this call can still settle a question that a settled
288
+ # one hid: one question per place is shown.
272
289
  return False
273
290
  unanswered = [q for q in result.review if q.options and q.start is not None
274
291
  and (entries.get(q.key) or {}).get("decided_by") != "user"]
@@ -285,8 +302,17 @@ def _carry_over(result: FileResult, path: Path, cache: SharedCache, used: list[d
285
302
  settled = []
286
303
  for e in used:
287
304
  options = e.get("options") or []
288
- # only an option that replaced the word: KEEP and free text are not options
289
- if e["choice"] in options and e["choice"].lower() != e.get("word", "").lower():
305
+ place = _answered_place(e, result)
306
+ if place is not None:
307
+ # what the user has seen at that place and turned down or kept
308
+ seen = {*options, e.get("word", ""), e["choice"]}
309
+ s, t = place
310
+ settled += [(q, list(q.options)) for q in unanswered
311
+ if q.start < t and s < q.end and result.output[q.start:q.end] == result.output[s:t]
312
+ and set(q.options) <= seen]
313
+ # without a place: only an option that replaced the word (KEEP and free text are
314
+ # not options) settles a question on the word it put in
315
+ elif e["choice"] in options and e["choice"].lower() != e.get("word", "").lower():
290
316
  settled += [(q, options) for q in unanswered
291
317
  if result.output[q.start:q.end].lower() == e["choice"].lower()
292
318
  and set(q.options) == set(options) and q.key not in before]
@@ -306,6 +332,33 @@ def _carry_over(result: FileResult, path: Path, cache: SharedCache, used: list[d
306
332
  return moved or bool(settled)
307
333
 
308
334
 
335
+ def _answered_place(e: dict, result: FileResult) -> tuple[int, int] | None:
336
+ """Where an answer's question was, as code-point offsets into result.output, or None.
337
+
338
+ --decide stores the question's UTF-16 `start` and `end` in the note's text as it
339
+ was then, which is this call's input. The place is followed through the changes
340
+ to the output: a change that overlaps it, the answer's own included, becomes part
341
+ of it. None when the answer has no place, or the word there is no longer its word."""
342
+ if "start" not in e:
343
+ return None
344
+ m = utf16_offsets(result.original)
345
+ try:
346
+ s, t = m.index(e["start"]), m.index(e["end"])
347
+ except ValueError: # past the end, or inside a surrogate pair
348
+ return None
349
+ if result.original[s:t] != e.get("word"):
350
+ return None
351
+ lo, hi = s, t # in the input
352
+ before = within = 0 # how much changes before the place, and in it, grow the text
353
+ for c in result.changes:
354
+ grow = len(c.after) - (c.end - c.start)
355
+ if c.start < s and c.end <= s:
356
+ before += grow
357
+ elif c.start < t or c.start == s: # overlaps the place, or is inserted at it
358
+ lo, hi, within = min(lo, c.start), max(hi, c.end), within + grow
359
+ return lo + before, hi + before + within
360
+
361
+
309
362
  def _process(label: str, text: str, settings: Settings, endpoint, caches: Caches,
310
363
  replay: bool, parallel: int,
311
364
  lt: LanguageToolRunner | None) -> tuple[FileResult, set[str]]:
@@ -410,11 +463,13 @@ def _run_once(body: str, settings: Settings, endpoint, caches: Caches, replay: b
410
463
  if not settings.variety_conversion:
411
464
  # no clear variety: stylefix's variety tiers (spellings, and words whose spelling
412
465
  # depends on sense) are skipped for this file, and its review of spellings from
413
- # the other variety is not shown: both varieties are as the writer left them
466
+ # the other variety is not shown: both varieties are as the writer left them.
467
+ # So are the outer quote marks and the order of dates (variety_conventions).
414
468
  style_skip |= VARIETY_TIERS
415
469
  style_opts = style.Options(target=settings.target, style=settings.style,
416
470
  accept=style_accept, parallel=parallel, skip=style_skip,
417
- require_vale=False, replay_cache=replay)
471
+ require_vale=False, replay_cache=replay,
472
+ variety_conventions=settings.variety_conversion)
418
473
  middle, first = body, []
419
474
  if "style" in settings.only:
420
475
  r = style.fix(body, style_opts, endpoint, caches.cache)
@@ -36,38 +36,68 @@ def file_entry(r) -> dict:
36
36
  "decided_by": c.decided_by, "confidence": round(c.confidence, 3),
37
37
  "depends_on": list(c.depends_on)} for c in r.changes]
38
38
  m = utf16_offsets(r.output)
39
- entry["review"] = [_review_item(i, m) for i in r.review]
39
+ entry["review"] = [_review_item(i, r.output, m) for i in r.review]
40
40
  entry["output"] = r.output
41
41
  return entry
42
42
 
43
43
 
44
- def _review_item(i, m: list[int]) -> dict:
44
+ # adjudicate's reason for an item whose batch the model failed: "model error: <details>"
45
+ MODEL_ERROR = "model error"
46
+ _FAILED = MODEL_ERROR + ":"
47
+
48
+
49
+ def _review_item(i, output: str, m: list[int]) -> dict:
45
50
  """A review item with options is a question: it also gets its span in output
46
- (m maps output's code points to UTF-16), its options, its explanation when it has
47
- one, and its cache key."""
51
+ (m maps output's code points to UTF-16), its options, its explanation when it
52
+ has one, and its cache key. Its message asks the question. Its reason gives no
53
+ error's details: model_error reports those once."""
48
54
  out = {"pass": i.pass_, "line": i.line, "kind": i.kind, "check": i.check, "message": i.message}
49
55
  if not i.options:
50
56
  return out
57
+ word = None
51
58
  if i.start is not None:
52
59
  out["start"], out["end"] = m[i.start], m[i.end]
60
+ word = output[i.start:i.end]
61
+ out["message"] = question(word, i.options)
53
62
  out.update(options=list(i.options), suggestion=i.suggestion,
54
63
  confidence=None if i.confidence is None else round(i.confidence, 3),
55
- reason=i.reason)
64
+ reason=MODEL_ERROR if i.reason.startswith(_FAILED) else i.reason)
56
65
  if i.explain:
57
66
  out["explain"] = i.explain
58
67
  out["key"] = i.key
59
68
  return out
60
69
 
61
70
 
62
- def summary(endpoint, skipped) -> dict:
71
+ def question(word: str | None, options) -> str:
72
+ """"Keep 'monday', or change it to 'Monday' or 'today'?" An option equal to the word
73
+ isn't repeated. Without a place in the output, the word is "it"."""
74
+ keep = "it" if word is None else f"'{word}'"
75
+ shown = [f"'{o}'" for o in options if o != word]
76
+ if not shown:
77
+ return f"Keep {keep}?"
78
+ choices = shown[0] if len(shown) == 1 else f"{', '.join(shown[:-1])} or {shown[-1]}"
79
+ return f"Keep {keep}, or change it to {choices}?"
80
+
81
+
82
+ def model_error(results) -> str | None:
83
+ """The first model failure among the results' questions: its details, once."""
84
+ for r in results:
85
+ for i in r.review:
86
+ if i.options and i.reason.startswith(_FAILED):
87
+ return i.reason.removeprefix(_FAILED).strip()
88
+ return None
89
+
90
+
91
+ def summary(endpoint, skipped, error: str | None = None) -> dict:
92
+ """error: the run's first model failure (model_error), or None."""
63
93
  ep = None if endpoint is None else {"url": endpoint.url, "model": endpoint.model,
64
- "source": endpoint.sources.get("url", "")}
94
+ "source": endpoint.sources.get("url", ""), "error": error}
65
95
  return {"schema": 1, "prosefix": __version__, "endpoint": ep,
66
96
  "skipped": [{"what": s.what, "why": s.why, "fix": s.fix} for s in skipped]}
67
97
 
68
98
 
69
99
  def document(results, endpoint, skipped) -> dict:
70
- return {**summary(endpoint, skipped), "files": [file_entry(r) for r in results]}
100
+ return {**summary(endpoint, skipped, model_error(results)), "files": [file_entry(r) for r in results]}
71
101
 
72
102
 
73
103
  def line(entry: dict, type_: str) -> str:
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "prosefix"
3
- version = "0.3.0"
3
+ version = "0.3.1"
4
4
  description = "Fix spelling, style, typos and punctuation in Markdown files, in place."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
7
7
  license = "MIT"
8
8
  license-files = ["LICENSE"]
9
9
  authors = [{ name = "Andrew Brož" }]
10
- dependencies = ["adjudicate>=0.3.6,<0.4", "stylefix>=0.10.1,<0.11", "proofix>=0.8.2,<0.9", "pyyaml>=6"]
10
+ dependencies = ["adjudicate>=0.3.7,<0.4", "stylefix>=0.10.2,<0.11", "proofix>=0.8.2,<0.9", "pyyaml>=6"]
11
11
  classifiers = [
12
12
  "Development Status :: 3 - Alpha",
13
13
  "Environment :: Console",
@@ -665,10 +665,48 @@ def test_json_question_without_explain_leaves_it_out():
665
665
  from adjudicate import ReviewItem
666
666
  item = ReviewItem(1, "question", "Which?", check="c", pass_="stylefix", start=0, end=1,
667
667
  options=("a", "b"), key="k", explain="")
668
- q = jsonout._review_item(item, jsonout.utf16_offsets("a"))
668
+ q = jsonout._review_item(item, "a", jsonout.utf16_offsets("a"))
669
669
  assert "explain" not in q and list(q)[-2:] == ["reason", "key"]
670
670
 
671
671
 
672
+ def _question(word="monday", options=("Monday", "Mondays", "money", "today"), reason="no model configured",
673
+ start=3):
674
+ from adjudicate import ReviewItem
675
+ return ReviewItem(1, "undecided", f"'{word}': {reason}", check="spelling", pass_="proofix",
676
+ start=start, end=None if start is None else start + len(word), options=options,
677
+ reason=reason, key="k")
678
+
679
+
680
+ @pytest.mark.parametrize("options, message", [
681
+ (("Monday", "Mondays", "money", "today"), "Keep 'monday', or change it to 'Monday', 'Mondays', 'money' or 'today'?"),
682
+ (("Monday",), "Keep 'monday', or change it to 'Monday'?"),
683
+ (("monday", "Monday"), "Keep 'monday', or change it to 'Monday'?"), # the word itself isn't repeated
684
+ ])
685
+ def test_json_question_message_is_a_question(options, message):
686
+ q = jsonout._review_item(_question(options=options), "on monday.", jsonout.utf16_offsets("on monday."))
687
+ assert q["message"] == message
688
+
689
+
690
+ def test_json_question_without_a_place_still_asks():
691
+ q = jsonout._review_item(_question(start=None), "on monday.", [])
692
+ assert q["message"] == "Keep it, or change it to 'Monday', 'Mondays', 'money' or 'today'?"
693
+
694
+
695
+ def test_json_model_error_is_in_the_summary_once():
696
+ from types import SimpleNamespace
697
+ detail = 'custom returned HTTP 500: {"error": "Cannot connect to host dgx-vllm:8000"}'
698
+ review = [_question(reason=f"model error: {detail}"), _question(word="licence", options=("license",),
699
+ reason=f"model error: {detail}")]
700
+ results = [SimpleNamespace(status="unchanged", review=review)]
701
+ assert jsonout.model_error(results) == detail
702
+ assert {jsonout._review_item(i, "on monday.", jsonout.utf16_offsets("on monday."))["reason"] for i in review} == {"model error"}
703
+ ep = SimpleNamespace(url="http://h/v1", model="m", sources={"url": "config"})
704
+ assert jsonout.summary(ep, [], detail)["endpoint"] == {"url": "http://h/v1", "model": "m",
705
+ "source": "config", "error": detail}
706
+ assert jsonout.summary(ep, [])["endpoint"]["error"] is None
707
+ assert jsonout.summary(None, [], detail)["endpoint"] is None
708
+
709
+
672
710
  @needs_vale
673
711
  def test_json_plain_and_cached_runs_ask_the_same_questions(tmp_path, capsys):
674
712
  p = tmp_path / "n.md"
@@ -734,16 +772,17 @@ def test_json_one_question_per_span_stylefix_first(tmp_path, capsys):
734
772
 
735
773
  @needs_vale
736
774
  def test_json_output_is_what_a_write_gives(tmp_path, capsys):
737
- # Without a model, a capitalised swap is a question when an answer can be stored,
738
- # and is applied under --llm none. --json and a write agree in both cases.
775
+ # Without a model, a capitalised swap is a question when an answer can be stored
776
+ # (--llm none included), and is applied under --no-cache. --json and a write agree.
739
777
  p = tmp_path / "n.md"
740
778
  outputs = {}
741
- for llm in ("auto", "none"):
779
+ for flags in (["--llm", "auto"], ["--llm", "none"], ["--llm", "none", "--no-cache"]):
742
780
  p.write_text("We like the Color of it.\n")
743
- main([str(p), "--json", "--target", "uk", "--llm", llm])
781
+ main([str(p), "--json", "--target", "uk", *flags])
744
782
  [f] = json.loads(capsys.readouterr().out)["files"]
745
- main([str(p), "--target", "uk", "--llm", llm, "-q"])
783
+ main([str(p), "--target", "uk", *flags, "-q"])
746
784
  assert p.read_text() == f["output"]
747
- outputs[llm] = (f["output"], [q["check"] for q in _questions(f)])
748
- assert outputs == {"auto": ("We like the Color of it.\n", ["capitalized"]),
749
- "none": ("We like the Colour of it.\n", [])}
785
+ outputs[" ".join(flags)] = (f["output"], [q["check"] for q in _questions(f)])
786
+ assert outputs == {"--llm auto": ("We like the Color of it.\n", ["capitalized"]),
787
+ "--llm none": ("We like the Color of it.\n", ["capitalized"]),
788
+ "--llm none --no-cache": ("We like the Colour of it.\n", [])}
@@ -329,3 +329,29 @@ def test_same_url_keeps_a_saved_key_variable(capsys, monkeypatch, isolated_llm_c
329
329
  assert code == 0 and tomllib.loads(path.read_text())["llm"]["api_key_env"] == "PROSEFIX_TEST_KEY"
330
330
  code, _, _ = run(capsys, monkeypatch, SETUP, stdin="typed\n")
331
331
  assert tomllib.loads(path.read_text())["llm"] == {"url": URL, "model": "m1", "api_key": "typed"}
332
+
333
+
334
+ def test_saved_key_comes_from_adjudicates_config_too(capsys, monkeypatch, isolated_llm_config):
335
+ # set up through adjudicate's shared config: prosefix's own file does not exist
336
+ server = Server(monkeypatch)
337
+ shared = isolated_llm_config / "adjudicate" / "config.toml"
338
+ shared.parent.mkdir(parents=True)
339
+ shared.write_text(f'[llm]\nurl = "{URL}"\nmodel = "m1"\napi_key = "shared-key"\n')
340
+ run(capsys, monkeypatch, ["--check-endpoint", "--json", "--url", URL, "--model", "m2"])
341
+ assert server.auth() == {"Bearer shared-key"}
342
+ code, _, _ = run(capsys, monkeypatch, ["--setup", "--json", "--url", URL, "--model", "m2"])
343
+ path = isolated_llm_config / "prosefix" / "config.toml"
344
+ assert code == 0 and tomllib.loads(path.read_text())["llm"] == {
345
+ "url": URL, "model": "m2", "api_key": "shared-key"}
346
+
347
+
348
+ def test_a_key_from_a_variable_is_saved_as_its_name(capsys, monkeypatch, isolated_llm_config):
349
+ server = Server(monkeypatch)
350
+ monkeypatch.setenv("ADJUDICATE_LLM_URL", URL)
351
+ monkeypatch.setenv("ADJUDICATE_LLM_KEY", "env-key")
352
+ run(capsys, monkeypatch, ["--check-endpoint", "--json", "--url", URL, "--model", "m2"])
353
+ assert server.auth() == {"Bearer env-key"}
354
+ code, _, _ = run(capsys, monkeypatch, ["--setup", "--json", "--url", URL, "--model", "m2"])
355
+ path = isolated_llm_config / "prosefix" / "config.toml"
356
+ assert code == 0 and "env-key" not in path.read_text()
357
+ assert tomllib.loads(path.read_text())["llm"]["api_key_env"] == "ADJUDICATE_LLM_KEY"
@@ -21,8 +21,8 @@ def decide(monkeypatch, capsys, doc) -> tuple[int, dict]:
21
21
  return code, json.loads(capsys.readouterr().out)
22
22
 
23
23
 
24
- def run_json(path: Path, capsys, *flags) -> dict:
25
- main([str(path), "--json", "--target", "uk", "--llm", "cached", *flags])
24
+ def run_json(path: Path, capsys, *flags, llm="cached") -> dict:
25
+ main([str(path), "--json", "--target", "uk", "--llm", llm, *flags])
26
26
  [f] = json.loads(capsys.readouterr().out)["files"]
27
27
  return f
28
28
 
@@ -42,6 +42,12 @@ def asked_on(f: dict, text: str) -> list[dict]:
42
42
  return [q for q in questions(f) if q["start"] < start + len(text) and start < q["end"]]
43
43
 
44
44
 
45
+ def answer(path: Path, f: dict, q: dict, choice) -> dict:
46
+ """A decision as the plugin sends it: word, options, start and end copied from the question."""
47
+ return {"path": str(path), "key": q["key"], "choice": choice, "word": word(f, q),
48
+ "options": q["options"], "start": q["start"], "end": q["end"]}
49
+
50
+
45
51
  def user_cache() -> Path:
46
52
  return Path(os.environ["XDG_CACHE_HOME"]) / "prosefix" / "cache.json"
47
53
 
@@ -78,6 +84,10 @@ def test_decisions_go_to_the_cache_each_path_resolves_to(tmp_path, monkeypatch,
78
84
  {"decisions": ["k"]},
79
85
  {"decisions": [{"path": "/n.md", "choice": "a"}]},
80
86
  {"decisions": [{"path": "", "key": "k", "choice": "a"}]},
87
+ {"decisions": [{"path": "/n.md", "key": "k", "choice": "a", "start": 3}]},
88
+ {"decisions": [{"path": "/n.md", "key": "k", "choice": "a", "start": 5, "end": 3}]},
89
+ {"decisions": [{"path": "/n.md", "key": "k", "choice": "a", "start": True, "end": 3}]},
90
+ {"decisions": [{"path": "/n.md", "key": "k", "choice": "a", "start": -1, "end": 3}]},
81
91
  {"decisions": [{"path": "/n.md", "key": 3, "choice": "a"}]},
82
92
  {"decisions": [{"path": "/n.md", "key": "k", "choice": ""}]},
83
93
  {"decisions": [{"path": "/n.md", "key": "k", "choice": ["a"]}]},
@@ -200,6 +210,91 @@ def test_keep_answer_settles_nothing_else(tmp_path, monkeypatch, capsys):
200
210
  assert [q["key"] for q in questions(f) if q["pass"] == "stylefix"] == [second["key"]]
201
211
 
202
212
 
213
+ @needs_vale
214
+ @needs_lt
215
+ def test_keep_answer_settles_the_other_question_on_its_place(tmp_path, monkeypatch, capsys):
216
+ # British "license" is a verb. Keeping it over stylefix's "licence" must not make
217
+ # LanguageTool ask whether "license" should be "licence" on the same word.
218
+ monkeypatch.setenv("PROSEFIX_NO_LT_SERVER", "1")
219
+ (tmp_path / "prosefix.toml").write_text("")
220
+ p = tmp_path / "n.md"
221
+ p.write_text("The team received the license on Monday.\n\nThe license is old.\n")
222
+ f = run_json(p, capsys)
223
+ first, second = [q for q in questions(f) if word(f, q) == "license"]
224
+ assert decide(monkeypatch, capsys, {"decisions": [answer(p, f, first, "license")]})[0] == 0
225
+ f = run_json(p, capsys)
226
+ assert f["output"] == p.read_text()
227
+ assert asked_on(f, "license") == [] # the first "license": nothing asked
228
+ assert second["key"] in [q["key"] for q in questions(f)]
229
+ again = run_json(p, capsys)
230
+ assert asked_on(again, "license") == []
231
+
232
+
233
+ @needs_vale
234
+ @needs_lt
235
+ def test_applied_answer_settles_the_other_question_on_its_place(tmp_path, monkeypatch, capsys):
236
+ monkeypatch.setenv("PROSEFIX_NO_LT_SERVER", "1")
237
+ (tmp_path / "prosefix.toml").write_text("")
238
+ p = tmp_path / "n.md"
239
+ p.write_text("The team received the licence on Monday.\n")
240
+ f = run_json(p, capsys)
241
+ [q] = [q for q in questions(f) if word(f, q) == "licence"]
242
+ assert decide(monkeypatch, capsys, {"decisions": [answer(p, f, q, "license")]})[0] == 0
243
+ f = run_json(p, capsys)
244
+ assert f["output"] == "The team received the license on Monday.\n"
245
+ assert asked_on(f, "license") == []
246
+ p.write_text(f["output"])
247
+ again = run_json(p, capsys)
248
+ assert again["status"] == "unchanged" and asked_on(again, "license") == []
249
+
250
+
251
+ @needs_lt
252
+ def test_answer_that_capitalises_a_word_applies(tmp_path, monkeypatch, capsys):
253
+ monkeypatch.setenv("PROSEFIX_NO_LT_SERVER", "1")
254
+ (tmp_path / "prosefix.toml").write_text("")
255
+ p = tmp_path / "n.md"
256
+ p.write_text("We met on monday at noon.\n")
257
+ f = run_json(p, capsys)
258
+ [q] = [q for q in questions(f) if word(f, q) == "monday"]
259
+ assert decide(monkeypatch, capsys, {"decisions": [answer(p, f, q, "Monday")]})[0] == 0
260
+ f = run_json(p, capsys)
261
+ assert f["output"] == "We met on Monday at noon.\n"
262
+ assert [c["decided_by"] for c in f["changes"]] == ["user"]
263
+
264
+
265
+ @needs_vale
266
+ def test_none_applies_answers_and_asks_as_cached_does(tmp_path, monkeypatch, capsys):
267
+ (tmp_path / "prosefix.toml").write_text("")
268
+ p = tmp_path / "n.md"
269
+ p.write_text("The meter is broken. We packed tents, stoves and maps.\n")
270
+ none, cached = run_json(p, capsys, llm="none"), run_json(p, capsys)
271
+ assert none["output"] == cached["output"]
272
+ assert [q["key"] for q in questions(none)] == [q["key"] for q in questions(cached)] != []
273
+ [q] = [q for q in questions(none) if q["check"] == "ambiguous"]
274
+ assert decide(monkeypatch, capsys, {"decisions": [answer(p, none, q, "metre")]})[0] == 0
275
+ none = run_json(p, capsys, llm="none")
276
+ assert "The metre is broken." in none["output"]
277
+ assert [c["decided_by"] for c in none["changes"]] == ["user"]
278
+ assert none["output"] == run_json(p, capsys)["output"]
279
+
280
+
281
+ @needs_vale
282
+ def test_none_ignores_the_models_answers(tmp_path, monkeypatch, capsys):
283
+ (tmp_path / "prosefix.toml").write_text("")
284
+ p = tmp_path / "n.md"
285
+ p.write_text("The meter is broken.\n")
286
+ [q] = [q for q in questions(run_json(p, capsys)) if q["check"] == "ambiguous"]
287
+ cache = tmp_path / ".prosefix" / "cache.json"
288
+ cache.parent.mkdir()
289
+ cache.write_text(json.dumps({q["key"]: {"word": "meter", "choice": "metre", "confidence": 0.9,
290
+ "reason": "a length", "context": ""}}))
291
+ assert "The metre is broken." in run_json(p, capsys)["output"]
292
+ none = run_json(p, capsys, llm="none")
293
+ assert none["output"] == "The meter is broken.\n"
294
+ assert q["key"] in [x["key"] for x in questions(none)]
295
+ assert json.loads(cache.read_text())[q["key"]]["choice"] == "metre" # never rewritten
296
+
297
+
203
298
  @needs_vale
204
299
  def test_question_open_before_the_answer_is_not_settled(tmp_path, monkeypatch, capsys):
205
300
  (tmp_path / "prosefix.toml").write_text("")
@@ -430,6 +430,13 @@ def test_undecided_variety_leaves_both_spellings():
430
430
  assert "color" in run(text, target="us").output
431
431
 
432
432
 
433
+
434
+ def test_undecided_variety_leaves_quote_marks_and_dates():
435
+ # After an answer tips a British note to unclear, its single quotes must not turn double.
436
+ text = "She called it \u2018the best weekend\u2019, on 5 December 2026.\n"
437
+ assert run(text, target="us", variety_conversion=False).output == text
438
+ assert run(text, target="us").output == "She called it \u201cthe best weekend,\u201d on December 5, 2026.\n"
439
+
433
440
  def test_model_removed_double_is_labelled_by_the_model(monkeypatch):
434
441
  from adjudicate.llm import Endpoint
435
442
 
@@ -529,3 +536,18 @@ def test_carry_over_stops_after_max_carries(tmp_path, monkeypatch):
529
536
  monkeypatch.setattr(engine, "_carry_over", lambda *a: calls.append(1) or True)
530
537
  engine.process("n.md", "Text.\n", s, None, caches, False, path=tmp_path / "n.md")
531
538
  assert len(calls) == engine.MAX_CARRIES and "pending" not in caches.cache.data["k"]
539
+
540
+
541
+ def test_answered_place_follows_the_changes_to_the_output():
542
+ from types import SimpleNamespace as NS
543
+ original = "A colour, the licence here.\n"
544
+ output = "A color, the new license there.\n"
545
+ changes = [NS(start=2, end=8, after="color"), # before the place: one shorter
546
+ NS(start=14, end=21, after="new license"), # the answer's own change, and more
547
+ NS(start=22, end=26, after="there")] # after the place: no effect
548
+ place = engine._answered_place({"start": 14, "end": 21, "word": "licence"},
549
+ NS(original=original, output=output, changes=changes))
550
+ assert output[slice(*place)] == "new license"
551
+ assert engine._answered_place({"start": 14, "end": 21, "word": "license"},
552
+ NS(original=original, output=output, changes=changes)) is None
553
+ assert engine._answered_place({"word": "licence"}, NS(original=original, output=output, changes=[])) is None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes