bots-garden/mini-mepublic Fork
⑂ 60e2e44
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

🐛 v2.2.2: tool feedback for small models (tickets 294-300, 307, 308)

- lsp: an empty diagnostics list is believed only once settled (#294);
  workspace files (go.mod, go.sum, package.json…) changed outside the
  tools are announced with workspace/didChangeWatchedFiles, and the read
  recall cache expires with them (#308)
- loop detector: no-op edits count as failures, errors recalled on a
  re-read (#295); near-identical successful bash commands (#297)
- plan tool: one update per finished task, a missing status means done,
  an answer after a detector stop (#296); plan-manager skill rewritten
- degenerate replies: blank-line runaway (#298), tool call written inside
  the reasoning handed back (#299)
- form feed written for \f repaired in write_file / edit_file (#300)
- a broken file read in circles: the fix is pointed at (#307)
- docs EN+FR; tickets 294-308, demos/notes-taker, sbxenv files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-12-05T20:27:10+01:00 Browse files
60e2e44 parent: 49b3393
modified .gitignore +2 -0
@@ -28,3 +28,5 @@ bob-the-smoll
2828 bob-coder
2929
3030 !demos/mlx-*
31+
32+validation
@@ -28,3 +28,5 @@ bob-the-smoll
28 bob-coder28 bob-coder
29 29
30 !demos/mlx-*30 !demos/mlx-*
31+
32+validation
added .tickets/issues/0294-lsp-diagnostics-say-clean-on-broken-go-files-aft.yaml +123 -0
new file mode 100644
@@ -0,0 +1,123 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 294
3+title: 'lsp diagnostics say "clean" on broken Go files after a go.mod appears (+ edit_file line range, control characters in diffs)'
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T06:49:42.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+body: |
18+ ## Seen in
19+
20+ `validation/mellum-2.2.1` (Mellum2 12B Instruct, mm 2.2.1, 2026-12-02), session
21+ `.mm/sessions/20261202-055938-9fe036cf.json`, traces `.mm/traces/`. Agent with
22+ `lsp.diagnosticsAfterEdit: true` and `diagnosticsAfterRead: true` (gopls).
23+
24+ ## 1. Diagnostics say "clean" on files that do not build (main bug)
25+
26+ - **Verified**: after the edits at messages #25, #27, #29 the tool results #26, #28, #30 say
27+ `no diagnostics: <file> is clean`. The files import `"../models"`, `"../persistence"`,
28+ `"internal/handlers"` and `"encoding/yaml"` (not a standard package): `go build ./...` and
29+ `gopls check` on the same files report every one of these errors.
30+ - Just before (#23) the model had created `label-api/go.mod` — the first go.mod of the workspace.
31+ - **Inferred, not reproduced**: `Diagnostics` (`internal/lsp/change.go`) takes the first
32+ publication after the didChange/didSave; gopls, reloading the workspace because of the new
33+ go.mod, first published an empty list, and mm took it as the answer.
34+ - **Effect**: the model had turned correct imports into wrong ones and was told the result was
35+ clean. A false "clean" is worse than no diagnostics.
36+
37+ ## 2. `edit_file` accepts an out-of-range `line`
38+
39+ - **Verified**: #29 sent `line: 1000000000000000`; #30 answered `1 edit(s) applied`.
40+
41+ ## 3. Control characters are invisible in diffs
42+
43+ - **Verified**: the model wrote `\func main` in a JSON string: `\f` became U+000C. The
44+ write_file diff (#9) shows `unc main()` with an invisible form feed; gopls said
45+ `illegal character U+000C`. The model could not see what to replace and its edit_file
46+ failed (#12).
47+
48+ ## Not in scope
49+
50+ The model's own errors (go.mod written last, plan loop at temperature 0) were handled in the
51+ agent's config, not in mm.
52+tasks:
53+ - id: 1
54+ title: "Reproduce: write a .go file importing a sibling package with no go.mod, then create go.mod, then edit the file — check what diagnosticsAfterEdit returns"
55+ state: closed
56+ priority: high
57+ author:
58+ name: k33g
59+ email: ph.charriere@gmail.com
60+ createdAt: 2026-12-02T06:49:42.000Z
61+ - id: 2
62+ title: "Fix Diagnostics (internal/lsp/change.go): do not take the first publication after the sync as final while gopls is (re)loading the workspace — wait for $/progress end or a quiet period, or pull"
63+ state: closed
64+ priority: high
65+ author:
66+ name: k33g
67+ email: ph.charriere@gmail.com
68+ createdAt: 2026-12-02T06:49:42.000Z
69+ - id: 3
70+ title: "Test: a go.mod created mid-session, then an edit with a wrong import must report the error"
71+ state: closed
72+ priority: high
73+ author:
74+ name: k33g
75+ email: ph.charriere@gmail.com
76+ createdAt: 2026-12-02T06:49:42.000Z
77+ - id: 4
78+ title: "edit_file: reject a `line` outside the file (line: 1000000000000000 was accepted)"
79+ state: closed
80+ priority: medium
81+ author:
82+ name: k33g
83+ email: ph.charriere@gmail.com
84+ createdAt: 2026-12-02T06:49:42.000Z
85+ - id: 5
86+ title: 'write_file / edit_file diffs: show control characters escaped (\f, \x00…) instead of invisibly'
87+ state: closed
88+ priority: medium
89+ author:
90+ name: k33g
91+ email: ph.charriere@gmail.com
92+ createdAt: 2026-12-02T06:49:42.000Z
93+ - id: 6
94+ title: "Docs EN+FR (lsp tool, edit_file reference) and re-run validation/mellum-2.2.1"
95+ state: closed
96+ priority: medium
97+ author:
98+ name: k33g
99+ email: ph.charriere@gmail.com
100+ createdAt: 2026-12-02T06:49:42.000Z
101+ updatedAt: 2026-12-05T09:05:00.000Z
102+ closedAt: 2026-12-05T09:05:00.000Z
103+comments:
104+ - id: 1
105+ author:
106+ name: k33g
107+ email: ph.charriere@gmail.com
108+ createdAt: 2026-12-04T18:40:00.000Z
109+ body: |
110+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
111+
112+ - Task 1: NOT reproduced with gopls v0.24.0 and a warm cache (the scenario of the session, files written before the first go.mod, then broken imports): gopls answered the errors in 7-47 ms. Kept as a permanent test, `internal/lsp/gopls_test.go` (skipped without gopls).
113+ - Task 2: `internal/lsp/settle.go` — errors are taken at once; an empty publication only once it stood alone 400 ms (`Client.settle`) and no `$/progress` work runs (mm now declares `window.workDoneProgress`). Wait over during a load: "no diagnostics yet … this does NOT mean the file is clean". Tests with a scripted fake server (`settle_test.go`).
114+ - Task 4: `fileedit.checkLine` refuses a line outside the file, unique old or not (test `TestLineOutsideTheFileIsRefused`; the ticket-241 test kept for a line inside the file).
115+ - Task 5: diffs show control characters escaped + a note (`fileedit/controlchars.go`).
116+ - Task 6: docs EN+FR done (reference tools/configuration, explanation lsp-tool). Re-run of validation/mellum-2.2.1 NOT done (no model in the sandbox).
117+ - id: 2
118+ author:
119+ name: k33g
120+ email: ph.charriere@gmail.com
121+ createdAt: 2026-12-05T09:05:00.000Z
122+ body: |
123+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
new file mode 100644
@@ -0,0 +1,123 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 294
3+title: 'lsp diagnostics say "clean" on broken Go files after a go.mod appears (+ edit_file line range, control characters in diffs)'
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T06:49:42.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+body: |
18+ ## Seen in
19+
20+ `validation/mellum-2.2.1` (Mellum2 12B Instruct, mm 2.2.1, 2026-12-02), session
21+ `.mm/sessions/20261202-055938-9fe036cf.json`, traces `.mm/traces/`. Agent with
22+ `lsp.diagnosticsAfterEdit: true` and `diagnosticsAfterRead: true` (gopls).
23+
24+ ## 1. Diagnostics say "clean" on files that do not build (main bug)
25+
26+ - **Verified**: after the edits at messages #25, #27, #29 the tool results #26, #28, #30 say
27+ `no diagnostics: <file> is clean`. The files import `"../models"`, `"../persistence"`,
28+ `"internal/handlers"` and `"encoding/yaml"` (not a standard package): `go build ./...` and
29+ `gopls check` on the same files report every one of these errors.
30+ - Just before (#23) the model had created `label-api/go.mod` — the first go.mod of the workspace.
31+ - **Inferred, not reproduced**: `Diagnostics` (`internal/lsp/change.go`) takes the first
32+ publication after the didChange/didSave; gopls, reloading the workspace because of the new
33+ go.mod, first published an empty list, and mm took it as the answer.
34+ - **Effect**: the model had turned correct imports into wrong ones and was told the result was
35+ clean. A false "clean" is worse than no diagnostics.
36+
37+ ## 2. `edit_file` accepts an out-of-range `line`
38+
39+ - **Verified**: #29 sent `line: 1000000000000000`; #30 answered `1 edit(s) applied`.
40+
41+ ## 3. Control characters are invisible in diffs
42+
43+ - **Verified**: the model wrote `\func main` in a JSON string: `\f` became U+000C. The
44+ write_file diff (#9) shows `unc main()` with an invisible form feed; gopls said
45+ `illegal character U+000C`. The model could not see what to replace and its edit_file
46+ failed (#12).
47+
48+ ## Not in scope
49+
50+ The model's own errors (go.mod written last, plan loop at temperature 0) were handled in the
51+ agent's config, not in mm.
52+tasks:
53+ - id: 1
54+ title: "Reproduce: write a .go file importing a sibling package with no go.mod, then create go.mod, then edit the file — check what diagnosticsAfterEdit returns"
55+ state: closed
56+ priority: high
57+ author:
58+ name: k33g
59+ email: ph.charriere@gmail.com
60+ createdAt: 2026-12-02T06:49:42.000Z
61+ - id: 2
62+ title: "Fix Diagnostics (internal/lsp/change.go): do not take the first publication after the sync as final while gopls is (re)loading the workspace — wait for $/progress end or a quiet period, or pull"
63+ state: closed
64+ priority: high
65+ author:
66+ name: k33g
67+ email: ph.charriere@gmail.com
68+ createdAt: 2026-12-02T06:49:42.000Z
69+ - id: 3
70+ title: "Test: a go.mod created mid-session, then an edit with a wrong import must report the error"
71+ state: closed
72+ priority: high
73+ author:
74+ name: k33g
75+ email: ph.charriere@gmail.com
76+ createdAt: 2026-12-02T06:49:42.000Z
77+ - id: 4
78+ title: "edit_file: reject a `line` outside the file (line: 1000000000000000 was accepted)"
79+ state: closed
80+ priority: medium
81+ author:
82+ name: k33g
83+ email: ph.charriere@gmail.com
84+ createdAt: 2026-12-02T06:49:42.000Z
85+ - id: 5
86+ title: 'write_file / edit_file diffs: show control characters escaped (\f, \x00…) instead of invisibly'
87+ state: closed
88+ priority: medium
89+ author:
90+ name: k33g
91+ email: ph.charriere@gmail.com
92+ createdAt: 2026-12-02T06:49:42.000Z
93+ - id: 6
94+ title: "Docs EN+FR (lsp tool, edit_file reference) and re-run validation/mellum-2.2.1"
95+ state: closed
96+ priority: medium
97+ author:
98+ name: k33g
99+ email: ph.charriere@gmail.com
100+ createdAt: 2026-12-02T06:49:42.000Z
101+ updatedAt: 2026-12-05T09:05:00.000Z
102+ closedAt: 2026-12-05T09:05:00.000Z
103+comments:
104+ - id: 1
105+ author:
106+ name: k33g
107+ email: ph.charriere@gmail.com
108+ createdAt: 2026-12-04T18:40:00.000Z
109+ body: |
110+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
111+
112+ - Task 1: NOT reproduced with gopls v0.24.0 and a warm cache (the scenario of the session, files written before the first go.mod, then broken imports): gopls answered the errors in 7-47 ms. Kept as a permanent test, `internal/lsp/gopls_test.go` (skipped without gopls).
113+ - Task 2: `internal/lsp/settle.go` — errors are taken at once; an empty publication only once it stood alone 400 ms (`Client.settle`) and no `$/progress` work runs (mm now declares `window.workDoneProgress`). Wait over during a load: "no diagnostics yet … this does NOT mean the file is clean". Tests with a scripted fake server (`settle_test.go`).
114+ - Task 4: `fileedit.checkLine` refuses a line outside the file, unique old or not (test `TestLineOutsideTheFileIsRefused`; the ticket-241 test kept for a line inside the file).
115+ - Task 5: diffs show control characters escaped + a note (`fileedit/controlchars.go`).
116+ - Task 6: docs EN+FR done (reference tools/configuration, explanation lsp-tool). Re-run of validation/mellum-2.2.1 NOT done (no model in the sandbox).
117+ - id: 2
118+ author:
119+ name: k33g
120+ email: ph.charriere@gmail.com
121+ createdAt: 2026-12-05T09:05:00.000Z
122+ body: |
123+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
added .tickets/issues/0295-loop-detector-misses-no-op-edits-alternating-with.yaml +121 -0
new file mode 100644
@@ -0,0 +1,121 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 295
3+title: Loop detector misses no-op edits alternating with reads; diagnostics not shown again on re-read
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T07:15:44.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 240
19+ - 294
20+body: |
21+ ## Seen in
22+
23+ `validation/mellum` (Mellum2 12B Instruct, mm 2.2.1, 2026-12-02 07:59-08:06), session
24+ `.mm/sessions/20261202-070027-b437a09f.json`, second turn ("check if the program compile").
25+
26+ - `go build` (#45): `api/storage/yaml.go:38:9: undefined: ioutil`, `:49:15: undefined: ioutil`.
27+ - Then **12 times** (#46 → #87): `edit_file` on the import block with `old` == `new`
28+ → `unchanged — already as asked: 1 edit(s) with identical old and new, nothing to change`,
29+ then `read_file api/storage/yaml.go`, then the same edit again. The user had to stop it.
30+ - Neither the loop detector nor `rereadLimit` reacted.
31+
32+ ## Why (verified in the code)
33+
34+ 1. **No-op edits count as success.** `internal/tools/files_evented.go:136` records an
35+ "unchanged" edit with `record` (success). The interleaved-repeat rule of
36+ [#240 — loop detector misses identical failures](.tickets/issues/0240-loop-detector-misses-identical-failures-between-ot.yaml)
37+ (`internal/detector/detector.go`, `seen(action)`) only applies to **failed** calls, and the
38+ consecutive rule never gets past 1 because a `read_file` comes between each edit. Same
39+ Mellum pattern as #240, with no-op edits instead of refused ones.
40+ 2. **A no-op edit resets the re-read state.** `internal/engine/reread.go` `changed()` counts
41+ every successful `write_file`/`edit_file` as a change, including an "unchanged" one.
42+ (Here `rereadLimit` would not have fired anyway: it only applies after a compression.)
43+ 3. **Diagnostics are not shown again.** `diagnosticsAfterRead` asks once per version of the
44+ file; the file never changed after #13, so the 12 reads carried no diagnostics. The model
45+ saw `undefined: ioutil` once (#45) and then only the file, with nothing pointing at line 38.
46+
47+ ## Proposal
48+
49+ - An edit_file / write_file that changes nothing is a **failed** call for the detector
50+ (`recordFailure`), so the #240 rule flags it after 3 occurrences in the window, whatever
51+ comes in between. Its output already says why; the loop instruction is added on top.
52+ - An "unchanged" edit is not a change for `reread.go`.
53+ - `diagnosticsAfterRead`: when the file still has **errors**, append them again on a re-read
54+ (a short form is enough: count + first errors), instead of once per version. Keep the
55+ once-per-version rule for warnings or a clean file.
56+
57+ Related: [#294 — lsp diagnostics say "clean" on broken Go files](.tickets/issues/0294-lsp-diagnostics-say-clean-on-broken-go-files-aft.yaml).
58+tasks:
59+ - id: 1
60+ title: Record a no-op edit_file / write_file as a failure for the loop detector (files_evented.go)
61+ state: closed
62+ priority: high
63+ author:
64+ name: k33g
65+ email: ph.charriere@gmail.com
66+ createdAt: 2026-12-02T07:15:44.000Z
67+ - id: 2
68+ title: "Test: edit(old==new) / read_file alternating 3 times is flagged, then the turn stops (WithStop)"
69+ state: closed
70+ priority: high
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-12-02T07:15:44.000Z
75+ - id: 3
76+ title: Do not count an unchanged edit as a change in reread.go
77+ state: closed
78+ priority: medium
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-12-02T07:15:44.000Z
83+ - id: 4
84+ title: diagnosticsAfterRead repeats the errors (short form) on a re-read of a file that still has errors
85+ state: closed
86+ priority: medium
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-12-02T07:15:44.000Z
91+ - id: 5
92+ title: Docs EN+FR (detector, diagnosticsAfterRead) and re-run validation/mellum
93+ state: closed
94+ priority: medium
95+ author:
96+ name: k33g
97+ email: ph.charriere@gmail.com
98+ createdAt: 2026-12-02T07:15:44.000Z
99+ updatedAt: 2026-12-05T09:05:00.000Z
100+ closedAt: 2026-12-05T09:05:00.000Z
101+comments:
102+ - id: 1
103+ author:
104+ name: k33g
105+ email: ph.charriere@gmail.com
106+ createdAt: 2026-12-04T18:40:00.000Z
107+ body: |
108+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
109+
110+ - Task 1: `recordChange` (tools/files_evented.go): a write/edit that changes nothing is a failed call for the detector (dry run excluded).
111+ - Task 2: `TestNoOpEditsBetweenReadsAreFlaggedThenStopped`: flagged at the 4th no-op edit (3 earlier occurrences), stopped after 3 flags.
112+ - Task 3: `reread.go` `changedAFile` reads the headline: refused, unchanged, dry run are not changes.
113+ - Task 4: `errorsRecall`: a re-read of an unchanged file with errors gets `still N error(s)` + the first 3 error lines; nothing for a clean file.
114+ - Task 5: docs EN+FR done. Re-run of validation/mellum NOT done.
115+ - id: 2
116+ author:
117+ name: k33g
118+ email: ph.charriere@gmail.com
119+ createdAt: 2026-12-05T09:05:00.000Z
120+ body: |
121+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
new file mode 100644
@@ -0,0 +1,121 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 295
3+title: Loop detector misses no-op edits alternating with reads; diagnostics not shown again on re-read
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T07:15:44.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 240
19+ - 294
20+body: |
21+ ## Seen in
22+
23+ `validation/mellum` (Mellum2 12B Instruct, mm 2.2.1, 2026-12-02 07:59-08:06), session
24+ `.mm/sessions/20261202-070027-b437a09f.json`, second turn ("check if the program compile").
25+
26+ - `go build` (#45): `api/storage/yaml.go:38:9: undefined: ioutil`, `:49:15: undefined: ioutil`.
27+ - Then **12 times** (#46 → #87): `edit_file` on the import block with `old` == `new`
28+ → `unchanged — already as asked: 1 edit(s) with identical old and new, nothing to change`,
29+ then `read_file api/storage/yaml.go`, then the same edit again. The user had to stop it.
30+ - Neither the loop detector nor `rereadLimit` reacted.
31+
32+ ## Why (verified in the code)
33+
34+ 1. **No-op edits count as success.** `internal/tools/files_evented.go:136` records an
35+ "unchanged" edit with `record` (success). The interleaved-repeat rule of
36+ [#240 — loop detector misses identical failures](.tickets/issues/0240-loop-detector-misses-identical-failures-between-ot.yaml)
37+ (`internal/detector/detector.go`, `seen(action)`) only applies to **failed** calls, and the
38+ consecutive rule never gets past 1 because a `read_file` comes between each edit. Same
39+ Mellum pattern as #240, with no-op edits instead of refused ones.
40+ 2. **A no-op edit resets the re-read state.** `internal/engine/reread.go` `changed()` counts
41+ every successful `write_file`/`edit_file` as a change, including an "unchanged" one.
42+ (Here `rereadLimit` would not have fired anyway: it only applies after a compression.)
43+ 3. **Diagnostics are not shown again.** `diagnosticsAfterRead` asks once per version of the
44+ file; the file never changed after #13, so the 12 reads carried no diagnostics. The model
45+ saw `undefined: ioutil` once (#45) and then only the file, with nothing pointing at line 38.
46+
47+ ## Proposal
48+
49+ - An edit_file / write_file that changes nothing is a **failed** call for the detector
50+ (`recordFailure`), so the #240 rule flags it after 3 occurrences in the window, whatever
51+ comes in between. Its output already says why; the loop instruction is added on top.
52+ - An "unchanged" edit is not a change for `reread.go`.
53+ - `diagnosticsAfterRead`: when the file still has **errors**, append them again on a re-read
54+ (a short form is enough: count + first errors), instead of once per version. Keep the
55+ once-per-version rule for warnings or a clean file.
56+
57+ Related: [#294 — lsp diagnostics say "clean" on broken Go files](.tickets/issues/0294-lsp-diagnostics-say-clean-on-broken-go-files-aft.yaml).
58+tasks:
59+ - id: 1
60+ title: Record a no-op edit_file / write_file as a failure for the loop detector (files_evented.go)
61+ state: closed
62+ priority: high
63+ author:
64+ name: k33g
65+ email: ph.charriere@gmail.com
66+ createdAt: 2026-12-02T07:15:44.000Z
67+ - id: 2
68+ title: "Test: edit(old==new) / read_file alternating 3 times is flagged, then the turn stops (WithStop)"
69+ state: closed
70+ priority: high
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-12-02T07:15:44.000Z
75+ - id: 3
76+ title: Do not count an unchanged edit as a change in reread.go
77+ state: closed
78+ priority: medium
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-12-02T07:15:44.000Z
83+ - id: 4
84+ title: diagnosticsAfterRead repeats the errors (short form) on a re-read of a file that still has errors
85+ state: closed
86+ priority: medium
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-12-02T07:15:44.000Z
91+ - id: 5
92+ title: Docs EN+FR (detector, diagnosticsAfterRead) and re-run validation/mellum
93+ state: closed
94+ priority: medium
95+ author:
96+ name: k33g
97+ email: ph.charriere@gmail.com
98+ createdAt: 2026-12-02T07:15:44.000Z
99+ updatedAt: 2026-12-05T09:05:00.000Z
100+ closedAt: 2026-12-05T09:05:00.000Z
101+comments:
102+ - id: 1
103+ author:
104+ name: k33g
105+ email: ph.charriere@gmail.com
106+ createdAt: 2026-12-04T18:40:00.000Z
107+ body: |
108+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
109+
110+ - Task 1: `recordChange` (tools/files_evented.go): a write/edit that changes nothing is a failed call for the detector (dry run excluded).
111+ - Task 2: `TestNoOpEditsBetweenReadsAreFlaggedThenStopped`: flagged at the 4th no-op edit (3 earlier occurrences), stopped after 3 flags.
112+ - Task 3: `reread.go` `changedAFile` reads the headline: refused, unchanged, dry run are not changes.
113+ - Task 4: `errorsRecall`: a re-read of an unchanged file with errors gets `still N error(s)` + the first 3 error lines; nothing for a clean file.
114+ - Task 5: docs EN+FR done. Re-run of validation/mellum NOT done.
115+ - id: 2
116+ author:
117+ name: k33g
118+ email: ph.charriere@gmail.com
119+ createdAt: 2026-12-05T09:05:00.000Z
120+ body: |
121+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
added .tickets/issues/0296-plan-tool-a-missing-status-ends-a-finished-turn-in.yaml +123 -0
new file mode 100644
@@ -0,0 +1,123 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 296
3+title: 'Plan tool: a missing "status" ends a finished turn in error; the description asks for too much bookkeeping'
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T08:04:17.000Z
9+updatedAt: 2026-12-05T09:06:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 240
19+ - 295
20+body: |
21+ ## Seen in
22+
23+ `validation/qwen-coder` (Qwen3-Coder-Next Q4_K_M, mm 2.2.1, 2026-12-02 08:52-08:58), session
24+ `.mm/sessions/20261202-075816-988ebf75.json`, 58 calls, prompt 51k tokens at the end.
25+
26+ - The work was **done and verified**: go build / go vet clean, the server built, run and tested
27+ with 10 curl calls, all correct (#101), labels.yaml written (#103).
28+ - Then `plan` `{"action":"update","taskId":6}` **without `status`**, 5 times identical
29+ (#106-#114; the raw SSE confirms the model omitted it). The loop detector ended the turn:
30+ `the model repeated the same plan call 6 times in a row with the same failing result`.
31+ The user got an error, no final answer — after a successful run.
32+ - Same omission at #52, recovered after one error. At 51k tokens it did not recover.
33+ - Earlier the same day: `validation/mellum-2.2.1` died on `plan update` with `tasks` instead of
34+ `status` (6×), and a qwen-coder run spent 10 of its 40 calls on plan bookkeeping before
35+ hitting maxTurns. **3 of the 4 failed runs of the day died on plan, not on the task.**
36+
37+ ## Causes (verified in the code)
38+
39+ 1. **The tool description asks for heavy bookkeeping** (`internal/tools/plan.go`, the example
40+ workflow): `update in_progress` → work → `update done` → `next` → "Always show the user the
41+ current plan status using the status action". 3 to 4 calls per task, and it contradicts
42+ agents whose prompt says "one update done per task".
43+ 2. **`status` is not required** by the schema (`required: [action]` only): nothing at
44+ generation time pushes the model to write it.
45+ 3. **A stuck tool loop ends the turn with an error** (`internal/tools/files.go` `StuckError`),
46+ even when the loop is bookkeeping after finished work. For repeated TEXT, mm already stops
47+ the model and hands back for an answer (`internal/engine/turn.go`, "stopped it and asked for
48+ the answer", `maxLoopRetries`).
49+
50+ ## Workaround in place
51+
52+ `planTool: false` in `validation/mellum` and `validation/qwen-coder` (reason in the files).
53+tasks:
54+ - id: 1
55+ title: 'Plan tool description (internal/tools/plan.go): one update with status done per finished task; drop the in_progress / next / "always show the status" ritual'
56+ state: closed
57+ priority: high
58+ author:
59+ name: k33g
60+ email: ph.charriere@gmail.com
61+ createdAt: 2026-12-02T08:04:17.000Z
62+ - id: 2
63+ title: 'update without status: decide — default to done, or make the schema require it per action (oneOf on action) — and test it'
64+ state: closed
65+ priority: high
66+ author:
67+ name: k33g
68+ email: ph.charriere@gmail.com
69+ createdAt: 2026-12-02T08:04:17.000Z
70+ - id: 3
71+ title: 'When the loop detector stops a turn (StuckError), hand back to the model for a final answer without tools, like the text-loop path in internal/engine/turn.go, instead of failing the turn'
72+ state: closed
73+ priority: high
74+ author:
75+ name: k33g
76+ email: ph.charriere@gmail.com
77+ createdAt: 2026-12-02T08:04:17.000Z
78+ - id: 4
79+ title: 'Tests: finished work + plan loop ends with an answer, not an error; the session keeps a summary of the work'
80+ state: closed
81+ priority: medium
82+ author:
83+ name: k33g
84+ email: ph.charriere@gmail.com
85+ createdAt: 2026-12-02T08:04:17.000Z
86+ - id: 5
87+ title: 'Docs EN+FR (plan tool reference, loop detector) and re-run validation/qwen-coder with planTool: true'
88+ state: closed
89+ priority: medium
90+ author:
91+ name: k33g
92+ email: ph.charriere@gmail.com
93+ createdAt: 2026-12-02T08:04:17.000Z
94+ updatedAt: 2026-12-05T09:05:00.000Z
95+ closedAt: 2026-12-05T09:05:00.000Z
96+comments:
97+ - id: 1
98+ author:
99+ name: k33g
100+ email: ph.charriere@gmail.com
101+ createdAt: 2026-12-04T18:40:00.000Z
102+ body: |
103+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
104+
105+ - Task 1: plan description rewritten: one `update` with status done per finished task, no call between steps nor after the last task (`next`/`status` still accepted).
106+ - Task 2: decided with the user: `update` without status AND without tasks = done, result says `(no status given: taken as done)`. With tasks and no status: the ticket-91 explained refusal is kept (the model was editing tasks).
107+ - Task 3: `engine/stuckanswer.go`: after a detector stop, the stopped calls get "not run", one more model call WITHOUT tools after a note; its answer ends the turn; the error stays only if that call fails, calls a tool or says nothing.
108+ - Task 4: `stuckanswer_test.go`. Not done: "the session keeps a summary of the work" beyond the answer itself (the answer is the summary).
109+ - Task 5: docs EN+FR done. Re-run of validation/qwen-coder with planTool: true NOT done. Note: `skills/plan-manager` still teaches the in_progress/next ritual (not changed: out of the ticket).
110+ - id: 2
111+ author:
112+ name: k33g
113+ email: ph.charriere@gmail.com
114+ createdAt: 2026-12-05T09:05:00.000Z
115+ body: |
116+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
117+ - id: 3
118+ author:
119+ name: k33g
120+ email: ph.charriere@gmail.com
121+ createdAt: 2026-12-05T09:06:00.000Z
122+ body: |
123+ `skills/plan-manager/SKILL.md` rewritten at the user's request to match the tool description: one `create`, then one `update` with `status: done` per finished task; no `in_progress`/`next` ritual, no mandatory `status` call or status line (mm shows the progress). The "skill and tool disagree" troubleshooting entry removed from docs EN+FR how-to/manage-plans-and-tasks.md. `go test ./internal/skills/` green.
new file mode 100644
@@ -0,0 +1,123 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 296
3+title: 'Plan tool: a missing "status" ends a finished turn in error; the description asks for too much bookkeeping'
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T08:04:17.000Z
9+updatedAt: 2026-12-05T09:06:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 240
19+ - 295
20+body: |
21+ ## Seen in
22+
23+ `validation/qwen-coder` (Qwen3-Coder-Next Q4_K_M, mm 2.2.1, 2026-12-02 08:52-08:58), session
24+ `.mm/sessions/20261202-075816-988ebf75.json`, 58 calls, prompt 51k tokens at the end.
25+
26+ - The work was **done and verified**: go build / go vet clean, the server built, run and tested
27+ with 10 curl calls, all correct (#101), labels.yaml written (#103).
28+ - Then `plan` `{"action":"update","taskId":6}` **without `status`**, 5 times identical
29+ (#106-#114; the raw SSE confirms the model omitted it). The loop detector ended the turn:
30+ `the model repeated the same plan call 6 times in a row with the same failing result`.
31+ The user got an error, no final answer — after a successful run.
32+ - Same omission at #52, recovered after one error. At 51k tokens it did not recover.
33+ - Earlier the same day: `validation/mellum-2.2.1` died on `plan update` with `tasks` instead of
34+ `status` (6×), and a qwen-coder run spent 10 of its 40 calls on plan bookkeeping before
35+ hitting maxTurns. **3 of the 4 failed runs of the day died on plan, not on the task.**
36+
37+ ## Causes (verified in the code)
38+
39+ 1. **The tool description asks for heavy bookkeeping** (`internal/tools/plan.go`, the example
40+ workflow): `update in_progress` → work → `update done` → `next` → "Always show the user the
41+ current plan status using the status action". 3 to 4 calls per task, and it contradicts
42+ agents whose prompt says "one update done per task".
43+ 2. **`status` is not required** by the schema (`required: [action]` only): nothing at
44+ generation time pushes the model to write it.
45+ 3. **A stuck tool loop ends the turn with an error** (`internal/tools/files.go` `StuckError`),
46+ even when the loop is bookkeeping after finished work. For repeated TEXT, mm already stops
47+ the model and hands back for an answer (`internal/engine/turn.go`, "stopped it and asked for
48+ the answer", `maxLoopRetries`).
49+
50+ ## Workaround in place
51+
52+ `planTool: false` in `validation/mellum` and `validation/qwen-coder` (reason in the files).
53+tasks:
54+ - id: 1
55+ title: 'Plan tool description (internal/tools/plan.go): one update with status done per finished task; drop the in_progress / next / "always show the status" ritual'
56+ state: closed
57+ priority: high
58+ author:
59+ name: k33g
60+ email: ph.charriere@gmail.com
61+ createdAt: 2026-12-02T08:04:17.000Z
62+ - id: 2
63+ title: 'update without status: decide — default to done, or make the schema require it per action (oneOf on action) — and test it'
64+ state: closed
65+ priority: high
66+ author:
67+ name: k33g
68+ email: ph.charriere@gmail.com
69+ createdAt: 2026-12-02T08:04:17.000Z
70+ - id: 3
71+ title: 'When the loop detector stops a turn (StuckError), hand back to the model for a final answer without tools, like the text-loop path in internal/engine/turn.go, instead of failing the turn'
72+ state: closed
73+ priority: high
74+ author:
75+ name: k33g
76+ email: ph.charriere@gmail.com
77+ createdAt: 2026-12-02T08:04:17.000Z
78+ - id: 4
79+ title: 'Tests: finished work + plan loop ends with an answer, not an error; the session keeps a summary of the work'
80+ state: closed
81+ priority: medium
82+ author:
83+ name: k33g
84+ email: ph.charriere@gmail.com
85+ createdAt: 2026-12-02T08:04:17.000Z
86+ - id: 5
87+ title: 'Docs EN+FR (plan tool reference, loop detector) and re-run validation/qwen-coder with planTool: true'
88+ state: closed
89+ priority: medium
90+ author:
91+ name: k33g
92+ email: ph.charriere@gmail.com
93+ createdAt: 2026-12-02T08:04:17.000Z
94+ updatedAt: 2026-12-05T09:05:00.000Z
95+ closedAt: 2026-12-05T09:05:00.000Z
96+comments:
97+ - id: 1
98+ author:
99+ name: k33g
100+ email: ph.charriere@gmail.com
101+ createdAt: 2026-12-04T18:40:00.000Z
102+ body: |
103+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
104+
105+ - Task 1: plan description rewritten: one `update` with status done per finished task, no call between steps nor after the last task (`next`/`status` still accepted).
106+ - Task 2: decided with the user: `update` without status AND without tasks = done, result says `(no status given: taken as done)`. With tasks and no status: the ticket-91 explained refusal is kept (the model was editing tasks).
107+ - Task 3: `engine/stuckanswer.go`: after a detector stop, the stopped calls get "not run", one more model call WITHOUT tools after a note; its answer ends the turn; the error stays only if that call fails, calls a tool or says nothing.
108+ - Task 4: `stuckanswer_test.go`. Not done: "the session keeps a summary of the work" beyond the answer itself (the answer is the summary).
109+ - Task 5: docs EN+FR done. Re-run of validation/qwen-coder with planTool: true NOT done. Note: `skills/plan-manager` still teaches the in_progress/next ritual (not changed: out of the ticket).
110+ - id: 2
111+ author:
112+ name: k33g
113+ email: ph.charriere@gmail.com
114+ createdAt: 2026-12-05T09:05:00.000Z
115+ body: |
116+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
117+ - id: 3
118+ author:
119+ name: k33g
120+ email: ph.charriere@gmail.com
121+ createdAt: 2026-12-05T09:06:00.000Z
122+ body: |
123+ `skills/plan-manager/SKILL.md` rewritten at the user's request to match the tool description: one `create`, then one `update` with `status: done` per finished task; no `in_progress`/`next` ritual, no mandatory `status` call or status line (mm shows the progress). The "skill and tool disagree" troubleshooting entry removed from docs EN+FR how-to/manage-plans-and-tasks.md. `go test ./internal/skills/` green.
added .tickets/issues/0297-detect-a-cycle-of-near-identical-successful-bash-c.yaml +112 -0
new file mode 100644
@@ -0,0 +1,112 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 297
3+title: Detect a cycle of near-identical successful bash commands (the model re-runs the same test and changes only timings)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T08:13:54.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - enhancement
12+ - priority::medium
13+ - kind::feature
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 240
19+ - 296
20+body: |
21+ ## Seen in
22+
23+ `validation/qwen-coder` (Qwen3-Coder-Next Q4_K_M, mm 2.2.1, 2026-12-02 09:05-09:10, no plan tool).
24+ The session and traces were deleted afterwards to clean the folder; the facts below were read before.
25+
26+ - The generated server deadlocked on every write (`Create` holds `mu.Lock()`, calls
27+ `saveToFile()` which locks again). GET worked; POST and everything after it timed out.
28+ - The test commands used `curl -s`, which hides curl's error: the model saw empty lines and
29+ `HTTP Status: 000`, concluded "the server exits after the first request", and for about
30+ **12 calls** alternated two kinds of bash commands — a single GET ("the server works") and the
31+ full test ("the server exits") — changing only `pkill`, `timeout N`, `sleep N`, `2>&1`.
32+ The user stopped it.
33+ - No detector fired: every command differed slightly and most exited 0, so neither the
34+ identical-repeat rule nor the "failing: N tool calls in a row" rule (ticket 160) applied, and
35+ the interleaved-failure rule of [#240](.tickets/issues/0240-loop-detector-misses-identical-failures-between-ot.yaml)
36+ only counts failed calls.
37+
38+ ## Idea (not decided)
39+
40+ Detect a cycle of **near-identical successful** bash commands: same command once normalised
41+ (numbers, `timeout N`, `sleep N`, `pkill …;` prefixes, redirections stripped), same output
42+ shape, no file changed in between. First tell the model, in the tool result, that it is
43+ running the same test again with the same outcome and should read the code instead.
44+
45+ ## Why it is only an enhancement
46+
47+ A model that re-runs a test after a real change is doing the right thing; similarity alone
48+ must not stop a turn. The agent-side fix (`curl -sS`, and a rule about locks taken twice)
49+ is already in `validation/*/.mm/agent.yaml`.
50+tasks:
51+ - id: 1
52+ title: 'Collect cases from the traces (validation/qwen-coder 2026-12-02 09:05) and decide the signal: normalised command similarity, same output shape, no file changed'
53+ state: closed
54+ priority: high
55+ author:
56+ name: k33g
57+ email: ph.charriere@gmail.com
58+ createdAt: 2026-12-02T08:13:54.000Z
59+ - id: 2
60+ title: 'Design: warn the model (a note in the tool result) before ever stopping the turn; never stop on similarity alone'
61+ state: closed
62+ priority: high
63+ author:
64+ name: k33g
65+ email: ph.charriere@gmail.com
66+ createdAt: 2026-12-02T08:13:54.000Z
67+ - id: 3
68+ title: 'Implement in internal/detector next to the ticket 160 failing rule, with tests on the recorded sequence'
69+ state: closed
70+ priority: medium
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-12-02T08:13:54.000Z
75+ - id: 4
76+ title: 'Show it to the user as a struggle line (struggle_wiring.go)'
77+ state: closed
78+ priority: low
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-12-02T08:13:54.000Z
83+ - id: 5
84+ title: 'Docs EN+FR (loop detector explanation) and re-run validation/qwen-coder'
85+ state: closed
86+ priority: medium
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-12-02T08:13:54.000Z
91+ updatedAt: 2026-12-05T09:05:00.000Z
92+ closedAt: 2026-12-05T09:05:00.000Z
93+comments:
94+ - id: 1
95+ author:
96+ name: k33g
97+ email: ph.charriere@gmail.com
98+ createdAt: 2026-12-04T18:40:00.000Z
99+ body: |
100+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
101+
102+ - Task 1: the traces of 09:05 were deleted; the signal was built from the ticket's description: command shape (pkill/kill/sleep/wait/true/: dropped, timeout prefix, redirections, trailing &, numbers → N) + output shape (numbers of 4+ digits and decimals → N, spacing) + no real file change since.
103+ - Task 2/3: `detector.WithSimilar(3)` (`detector/similar.go`), `Action.Shape`/`Action.Changed`, `Check`; bash sets the shape (`tools/bashshape.go`). A note in the tool result from the 3rd similar call; never a stop.
104+ - Task 4: struggle line `same test again: bash ×N with the same result, no file changed`.
105+ - Task 5: docs EN+FR done. Re-run of validation/qwen-coder NOT done.
106+ - id: 2
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-12-05T09:05:00.000Z
111+ body: |
112+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
new file mode 100644
@@ -0,0 +1,112 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 297
3+title: Detect a cycle of near-identical successful bash commands (the model re-runs the same test and changes only timings)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T08:13:54.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - enhancement
12+ - priority::medium
13+ - kind::feature
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 240
19+ - 296
20+body: |
21+ ## Seen in
22+
23+ `validation/qwen-coder` (Qwen3-Coder-Next Q4_K_M, mm 2.2.1, 2026-12-02 09:05-09:10, no plan tool).
24+ The session and traces were deleted afterwards to clean the folder; the facts below were read before.
25+
26+ - The generated server deadlocked on every write (`Create` holds `mu.Lock()`, calls
27+ `saveToFile()` which locks again). GET worked; POST and everything after it timed out.
28+ - The test commands used `curl -s`, which hides curl's error: the model saw empty lines and
29+ `HTTP Status: 000`, concluded "the server exits after the first request", and for about
30+ **12 calls** alternated two kinds of bash commands — a single GET ("the server works") and the
31+ full test ("the server exits") — changing only `pkill`, `timeout N`, `sleep N`, `2>&1`.
32+ The user stopped it.
33+ - No detector fired: every command differed slightly and most exited 0, so neither the
34+ identical-repeat rule nor the "failing: N tool calls in a row" rule (ticket 160) applied, and
35+ the interleaved-failure rule of [#240](.tickets/issues/0240-loop-detector-misses-identical-failures-between-ot.yaml)
36+ only counts failed calls.
37+
38+ ## Idea (not decided)
39+
40+ Detect a cycle of **near-identical successful** bash commands: same command once normalised
41+ (numbers, `timeout N`, `sleep N`, `pkill …;` prefixes, redirections stripped), same output
42+ shape, no file changed in between. First tell the model, in the tool result, that it is
43+ running the same test again with the same outcome and should read the code instead.
44+
45+ ## Why it is only an enhancement
46+
47+ A model that re-runs a test after a real change is doing the right thing; similarity alone
48+ must not stop a turn. The agent-side fix (`curl -sS`, and a rule about locks taken twice)
49+ is already in `validation/*/.mm/agent.yaml`.
50+tasks:
51+ - id: 1
52+ title: 'Collect cases from the traces (validation/qwen-coder 2026-12-02 09:05) and decide the signal: normalised command similarity, same output shape, no file changed'
53+ state: closed
54+ priority: high
55+ author:
56+ name: k33g
57+ email: ph.charriere@gmail.com
58+ createdAt: 2026-12-02T08:13:54.000Z
59+ - id: 2
60+ title: 'Design: warn the model (a note in the tool result) before ever stopping the turn; never stop on similarity alone'
61+ state: closed
62+ priority: high
63+ author:
64+ name: k33g
65+ email: ph.charriere@gmail.com
66+ createdAt: 2026-12-02T08:13:54.000Z
67+ - id: 3
68+ title: 'Implement in internal/detector next to the ticket 160 failing rule, with tests on the recorded sequence'
69+ state: closed
70+ priority: medium
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-12-02T08:13:54.000Z
75+ - id: 4
76+ title: 'Show it to the user as a struggle line (struggle_wiring.go)'
77+ state: closed
78+ priority: low
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-12-02T08:13:54.000Z
83+ - id: 5
84+ title: 'Docs EN+FR (loop detector explanation) and re-run validation/qwen-coder'
85+ state: closed
86+ priority: medium
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-12-02T08:13:54.000Z
91+ updatedAt: 2026-12-05T09:05:00.000Z
92+ closedAt: 2026-12-05T09:05:00.000Z
93+comments:
94+ - id: 1
95+ author:
96+ name: k33g
97+ email: ph.charriere@gmail.com
98+ createdAt: 2026-12-04T18:40:00.000Z
99+ body: |
100+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
101+
102+ - Task 1: the traces of 09:05 were deleted; the signal was built from the ticket's description: command shape (pkill/kill/sleep/wait/true/: dropped, timeout prefix, redirections, trailing &, numbers → N) + output shape (numbers of 4+ digits and decimals → N, spacing) + no real file change since.
103+ - Task 2/3: `detector.WithSimilar(3)` (`detector/similar.go`), `Action.Shape`/`Action.Changed`, `Check`; bash sets the shape (`tools/bashshape.go`). A note in the tool result from the 3rd similar call; never a stop.
104+ - Task 4: struggle line `same test again: bash ×N with the same result, no file changed`.
105+ - Task 5: docs EN+FR done. Re-run of validation/qwen-coder NOT done.
106+ - id: 2
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-12-05T09:05:00.000Z
111+ body: |
112+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
added .tickets/issues/0298-a-reply-made-of-blank-lines-up-to-the-token-limit.yaml +84 -0
new file mode 100644
@@ -0,0 +1,84 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 298
3+title: A reply made of blank lines up to the token limit is reported as a plain cut, not as a loop
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T09:05:30.000Z
9+updatedAt: 2026-12-05T08:45:00.000Z
10+labels:
11+ - bug
12+ - priority::medium
13+ - kind::bug
14+milestone: v2.2.2
15+epic: Providers (LLM Engine)
16+related:
17+ - 235
18+ - 236
19+body: |
20+ ## What happened
21+
22+ `validation/mellum` (Mellum2 12B-A2.5B Instruct Q8_0), 2026-12-02, run 09:52-09:55,
23+ last call (`.mm/traces-run-0952/20261202-095510.982-mellum-0030.response-200.sse`):
24+
25+ - one sentence ("Great! The build was successful. Now let's test the API…"),
26+ - then **3,935 blank lines** and a few LaTeX lines (`\begin{figure}`…),
27+ - `finish_reason: length`, 4,096 completion tokens (the whole `max_tokens`).
28+
29+ mm ended the turn with the ticket-236 label: *"answer cut at the limit
30+ (max_tokens 4096): raise sampling.max_tokens, or ask for a shorter answer"*.
31+ That advice is wrong here: a larger limit only buys more blank lines. The
32+ model degenerated; it did not run out of room.
33+
34+ ## Why it is missed
35+
36+ - `collapseLoops` / `loopedLines` (internal/engine/loops.go, ticket 235) skip
37+ blank lines on purpose, so a run of blank lines is never a loop.
38+ - The streaming watch (internal/engine/textloop.go) ignores units shorter than
39+ `loopMinUnit` (12), so it never cancels the call: the whole budget is spent
40+ (about 40 s here).
41+
42+ ## Expected
43+
44+ - A reply whose text is mostly whitespace (for example more than N blank lines
45+ in a row, or > 90 % blank once trimmed) is reported as a loop (severe
46+ struggle), not as "raise max_tokens".
47+ - The streaming watch cancels the call after a long run of blank lines, as it
48+ does for a repeated sentence.
49+ - Ideally the turn hands back to the model as for a text loop (turn.go), since
50+ it was about to run a test: the turn ended instead of continuing.
51+
52+ ## Acceptance criteria
53+
54+ - A unit test with the shape above (one sentence + thousands of `\n`, finish
55+ reason length) gets the loop label, not `cutAnswerLabel()`.
56+ - A normal answer with a few blank lines between paragraphs is unchanged.
57+tasks: []
58+comments:
59+ - id: 1
60+ author:
61+ name: k33g
62+ email: ph.charriere@gmail.com
63+ createdAt: 2026-12-02T12:50:00.000Z
64+ body: |
65+ Second occurrence, 2026-12-02 run 13:41 of `validation/mellum` (Mellum2 Instruct
66+ Q8_0). After 10 refused `edit_file` calls (wrong `line`, then the loop detector),
67+ the reply was a sentence followed by blank lines up to the limit
68+ (`validation/mellum/.mm/traces-run-1341/`, message 58). mm's nudge ("your last
69+ edit_file call failed…") got the same shape again (message 60), and the turn
70+ ended.
71+ - id: 2
72+ author:
73+ name: k33g
74+ email: ph.charriere@gmail.com
75+ createdAt: 2026-12-04T18:40:00.000Z
76+ body: |
77+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted. 40+ blank lines in a row in the final answer are collapsed to `[… N blank lines — removed by mm]` and reported as a severe loop (`the model looped: N blank lines in a row`, "a larger max_tokens would not help" when cut), never as "raise max_tokens"; the streaming watch cuts a call after 100 blank lines and hands it back once (own note). Acceptance tests: `engine/blanks_test.go`. Docs EN+FR done. Re-run NOT done.
78+ - id: 3
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-12-05T08:45:00.000Z
83+ body: |
84+ Closed by the user (2026-12-05): implemented and covered by unit tests; not seen again in the validation runs (validation/mellum21-thinking 2026-12-05 08:21, ALL OK). Reopen if it shows up again.
new file mode 100644
@@ -0,0 +1,84 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 298
3+title: A reply made of blank lines up to the token limit is reported as a plain cut, not as a loop
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T09:05:30.000Z
9+updatedAt: 2026-12-05T08:45:00.000Z
10+labels:
11+ - bug
12+ - priority::medium
13+ - kind::bug
14+milestone: v2.2.2
15+epic: Providers (LLM Engine)
16+related:
17+ - 235
18+ - 236
19+body: |
20+ ## What happened
21+
22+ `validation/mellum` (Mellum2 12B-A2.5B Instruct Q8_0), 2026-12-02, run 09:52-09:55,
23+ last call (`.mm/traces-run-0952/20261202-095510.982-mellum-0030.response-200.sse`):
24+
25+ - one sentence ("Great! The build was successful. Now let's test the API…"),
26+ - then **3,935 blank lines** and a few LaTeX lines (`\begin{figure}`…),
27+ - `finish_reason: length`, 4,096 completion tokens (the whole `max_tokens`).
28+
29+ mm ended the turn with the ticket-236 label: *"answer cut at the limit
30+ (max_tokens 4096): raise sampling.max_tokens, or ask for a shorter answer"*.
31+ That advice is wrong here: a larger limit only buys more blank lines. The
32+ model degenerated; it did not run out of room.
33+
34+ ## Why it is missed
35+
36+ - `collapseLoops` / `loopedLines` (internal/engine/loops.go, ticket 235) skip
37+ blank lines on purpose, so a run of blank lines is never a loop.
38+ - The streaming watch (internal/engine/textloop.go) ignores units shorter than
39+ `loopMinUnit` (12), so it never cancels the call: the whole budget is spent
40+ (about 40 s here).
41+
42+ ## Expected
43+
44+ - A reply whose text is mostly whitespace (for example more than N blank lines
45+ in a row, or > 90 % blank once trimmed) is reported as a loop (severe
46+ struggle), not as "raise max_tokens".
47+ - The streaming watch cancels the call after a long run of blank lines, as it
48+ does for a repeated sentence.
49+ - Ideally the turn hands back to the model as for a text loop (turn.go), since
50+ it was about to run a test: the turn ended instead of continuing.
51+
52+ ## Acceptance criteria
53+
54+ - A unit test with the shape above (one sentence + thousands of `\n`, finish
55+ reason length) gets the loop label, not `cutAnswerLabel()`.
56+ - A normal answer with a few blank lines between paragraphs is unchanged.
57+tasks: []
58+comments:
59+ - id: 1
60+ author:
61+ name: k33g
62+ email: ph.charriere@gmail.com
63+ createdAt: 2026-12-02T12:50:00.000Z
64+ body: |
65+ Second occurrence, 2026-12-02 run 13:41 of `validation/mellum` (Mellum2 Instruct
66+ Q8_0). After 10 refused `edit_file` calls (wrong `line`, then the loop detector),
67+ the reply was a sentence followed by blank lines up to the limit
68+ (`validation/mellum/.mm/traces-run-1341/`, message 58). mm's nudge ("your last
69+ edit_file call failed…") got the same shape again (message 60), and the turn
70+ ended.
71+ - id: 2
72+ author:
73+ name: k33g
74+ email: ph.charriere@gmail.com
75+ createdAt: 2026-12-04T18:40:00.000Z
76+ body: |
77+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted. 40+ blank lines in a row in the final answer are collapsed to `[… N blank lines — removed by mm]` and reported as a severe loop (`the model looped: N blank lines in a row`, "a larger max_tokens would not help" when cut), never as "raise max_tokens"; the streaming watch cuts a call after 100 blank lines and hands it back once (own note). Acceptance tests: `engine/blanks_test.go`. Docs EN+FR done. Re-run NOT done.
78+ - id: 3
79+ author:
80+ name: k33g
81+ email: ph.charriere@gmail.com
82+ createdAt: 2026-12-05T08:45:00.000Z
83+ body: |
84+ Closed by the user (2026-12-05): implemented and covered by unit tests; not seen again in the validation runs (validation/mellum21-thinking 2026-12-05 08:21, ALL OK). Reopen if it shows up again.
added .tickets/issues/0299-a-tool-call-written-inside-the-reasoning-ends-the.yaml +92 -0
new file mode 100644
@@ -0,0 +1,92 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 299
3+title: A tool call written inside the reasoning ends the turn with no answer
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T09:05:30.000Z
9+updatedAt: 2026-12-05T08:45:00.000Z
10+labels:
11+ - bug
12+ - priority::medium
13+ - kind::bug
14+milestone: v2.2.2
15+epic: Providers (LLM Engine)
16+related:
17+ - 232
18+body: |
19+ ## What happened
20+
21+ `validation/mellum-thinking` (Mellum2.1-12B-A2.5B-Thinking Q4_K_M, llmman,
22+ `enable_thinking: true`), 2026-12-02, run 09:52-10:00, last call
23+ (`.mm/traces-run-0952/20261202-100003.643-mellum-thinking-0027.response-200.sse`):
24+
25+ - `reasoning_content`: 8,577 characters, ending with
26+ `<tool_call>{"name": "read_file", "arguments": {"path": "main.go", "start": 110}}</tool_call>`
27+ - `content`: empty; no `tool_calls` delta; `finish_reason: stop`
28+ (2,476 completion tokens).
29+
30+ The model meant to call a tool, but the call stayed inside the reasoning.
31+ mm saw no text and no tool call, and the turn ended silently in the middle
32+ of the work (main.go still had a syntax error).
33+
34+ The 26 previous calls of the same run put their tool calls in `tool_calls`
35+ correctly: it happens once in a while, not always.
36+
37+ ## Why it is missed
38+
39+ - The `<tool_call>` recovery (internal/engine/xmlcalls.go, xmltools.go) reads
40+ the content only.
41+ - `retryCutReasoning` (turn.go, ticket 232) hands back a reply cut by the limit
42+ while reasoning; here the finish reason is `stop`, so it does not apply.
43+
44+ ## Expected (to decide)
45+
46+ - Either: an empty reply (no text, no tool call) whose reasoning ends with a
47+ complete `<tool_call>` block runs that call, with a struggle line saying so;
48+ - or, simpler: an empty reply after reasoning is handed back once, as for
49+ ticket 232 ("you wrote your tool call inside your reasoning: make it now").
50+
51+ ## Acceptance criteria
52+
53+ - A unit test with the shape above (reasoning ending in a `<tool_call>` block,
54+ empty content, finish reason stop) does not end the turn silently.
55+tasks: []
56+comments:
57+ - id: 1
58+ author:
59+ name: k33g
60+ email: ph.charriere@gmail.com
61+ createdAt: 2026-12-02T12:50:00.000Z
62+ body: |
63+ Second occurrence, 2026-12-02 run 13:41 of `validation/mellum-thinking`
64+ (Mellum2.1 Thinking Q4_K_M, reasoning on), call 20:
65+ `validation/mellum-thinking/.mm/traces-run-1341/20261202-134327.738-mellum-thinking-0020.response-200.sse`.
66+ The reasoning (4,655 characters) ends with
67+ `<tool_call>{"name": "read_file", "arguments": {"path": "main.go"}}</tool_call>`,
68+ the content is empty, and the finish reason is `stop`. The turn ended silently, with
69+ main.go still broken. 2 runs of 2 with reasoning on hit it.
70+ - id: 2
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-12-04T18:40:00.000Z
75+ body: |
76+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted. Decided with the user: hand back once (nothing from the reasoning is run). A reply with no text and no tool call whose reasoning holds a complete, parseable `<tool_call>` block is handed back with the block quoted (`engine/reasoningcall.go`); struggle `tool call in the reasoning — handed back 1/1`. Tests: `engine/reasoningcall_test.go`. Docs EN+FR done. Re-run of validation/mellum-thinking NOT done.
77+ - id: 3
78+ author:
79+ name: k33g
80+ email: ph.charriere@gmail.com
81+ createdAt: 2026-12-05T08:30:00.000Z
82+ body: |
83+ Re-run 2026-12-05 (`validation/mellum21-thinking`, traces `20261205-*`): the hand-back worked at call 31 (the model made the `go run` call). At call 33 the model wrote a call in its reasoning again — having just found the real bug (main() holds the mutex) — and the turn ended silently: the count was per turn (one generation), not per occurrence.
84+
85+ Fixed: `retryCallInReasoning` resets the count after a reply with a real tool call (`madeACall`); two in a row are still handed back once only. Test `TestToolCallInReasoningIsHandedBackAgainAfterARealCall` (fails without the fix). Docs EN+FR reference/cli.md.
86+ - id: 4
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-12-05T08:45:00.000Z
91+ body: |
92+ Closed by the user (2026-12-05): implemented and covered by unit tests; not seen again in the validation runs (validation/mellum21-thinking 2026-12-05 08:21, ALL OK). Reopen if it shows up again.
new file mode 100644
@@ -0,0 +1,92 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 299
3+title: A tool call written inside the reasoning ends the turn with no answer
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T09:05:30.000Z
9+updatedAt: 2026-12-05T08:45:00.000Z
10+labels:
11+ - bug
12+ - priority::medium
13+ - kind::bug
14+milestone: v2.2.2
15+epic: Providers (LLM Engine)
16+related:
17+ - 232
18+body: |
19+ ## What happened
20+
21+ `validation/mellum-thinking` (Mellum2.1-12B-A2.5B-Thinking Q4_K_M, llmman,
22+ `enable_thinking: true`), 2026-12-02, run 09:52-10:00, last call
23+ (`.mm/traces-run-0952/20261202-100003.643-mellum-thinking-0027.response-200.sse`):
24+
25+ - `reasoning_content`: 8,577 characters, ending with
26+ `<tool_call>{"name": "read_file", "arguments": {"path": "main.go", "start": 110}}</tool_call>`
27+ - `content`: empty; no `tool_calls` delta; `finish_reason: stop`
28+ (2,476 completion tokens).
29+
30+ The model meant to call a tool, but the call stayed inside the reasoning.
31+ mm saw no text and no tool call, and the turn ended silently in the middle
32+ of the work (main.go still had a syntax error).
33+
34+ The 26 previous calls of the same run put their tool calls in `tool_calls`
35+ correctly: it happens once in a while, not always.
36+
37+ ## Why it is missed
38+
39+ - The `<tool_call>` recovery (internal/engine/xmlcalls.go, xmltools.go) reads
40+ the content only.
41+ - `retryCutReasoning` (turn.go, ticket 232) hands back a reply cut by the limit
42+ while reasoning; here the finish reason is `stop`, so it does not apply.
43+
44+ ## Expected (to decide)
45+
46+ - Either: an empty reply (no text, no tool call) whose reasoning ends with a
47+ complete `<tool_call>` block runs that call, with a struggle line saying so;
48+ - or, simpler: an empty reply after reasoning is handed back once, as for
49+ ticket 232 ("you wrote your tool call inside your reasoning: make it now").
50+
51+ ## Acceptance criteria
52+
53+ - A unit test with the shape above (reasoning ending in a `<tool_call>` block,
54+ empty content, finish reason stop) does not end the turn silently.
55+tasks: []
56+comments:
57+ - id: 1
58+ author:
59+ name: k33g
60+ email: ph.charriere@gmail.com
61+ createdAt: 2026-12-02T12:50:00.000Z
62+ body: |
63+ Second occurrence, 2026-12-02 run 13:41 of `validation/mellum-thinking`
64+ (Mellum2.1 Thinking Q4_K_M, reasoning on), call 20:
65+ `validation/mellum-thinking/.mm/traces-run-1341/20261202-134327.738-mellum-thinking-0020.response-200.sse`.
66+ The reasoning (4,655 characters) ends with
67+ `<tool_call>{"name": "read_file", "arguments": {"path": "main.go"}}</tool_call>`,
68+ the content is empty, and the finish reason is `stop`. The turn ended silently, with
69+ main.go still broken. 2 runs of 2 with reasoning on hit it.
70+ - id: 2
71+ author:
72+ name: k33g
73+ email: ph.charriere@gmail.com
74+ createdAt: 2026-12-04T18:40:00.000Z
75+ body: |
76+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted. Decided with the user: hand back once (nothing from the reasoning is run). A reply with no text and no tool call whose reasoning holds a complete, parseable `<tool_call>` block is handed back with the block quoted (`engine/reasoningcall.go`); struggle `tool call in the reasoning — handed back 1/1`. Tests: `engine/reasoningcall_test.go`. Docs EN+FR done. Re-run of validation/mellum-thinking NOT done.
77+ - id: 3
78+ author:
79+ name: k33g
80+ email: ph.charriere@gmail.com
81+ createdAt: 2026-12-05T08:30:00.000Z
82+ body: |
83+ Re-run 2026-12-05 (`validation/mellum21-thinking`, traces `20261205-*`): the hand-back worked at call 31 (the model made the `go run` call). At call 33 the model wrote a call in its reasoning again — having just found the real bug (main() holds the mutex) — and the turn ended silently: the count was per turn (one generation), not per occurrence.
84+
85+ Fixed: `retryCallInReasoning` resets the count after a reply with a real tool call (`madeACall`); two in a row are still handed back once only. Test `TestToolCallInReasoningIsHandedBackAgainAfterARealCall` (fails without the fix). Docs EN+FR reference/cli.md.
86+ - id: 4
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-12-05T08:45:00.000Z
91+ body: |
92+ Closed by the user (2026-12-05): implemented and covered by unit tests; not seen again in the validation runs (validation/mellum21-thinking 2026-12-05 08:21, ALL OK). Reopen if it shows up again.
added .tickets/issues/0300-repair-a-form-feed-written-for-f-in-code-written.yaml +161 -0
new file mode 100644
@@ -0,0 +1,161 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 300
3+title: Repair a form feed written for a backslash-f in code written by write_file and edit_file (study first)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T09:22:35.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - enhancement
12+ - priority::medium
13+ - kind::feature
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 294
19+body: |
20+ ## The problem
21+
22+ Mellum models (Mellum2 12B-A2.5B Instruct Q8_0, Mellum2.1-12B-A2.5B-Thinking
23+ Q4_K_M) write a backslash before `func` in the JSON arguments of `write_file`
24+ (`"…\n\func main()…"`). JSON reads `\f` as U+000C (form feed), so the file
25+ gets `<FF>unc main()`. Go then says `invalid character U+000C`.
26+
27+ **4 Mellum runs of 4** on 2026-12-02 (validation/mellum, validation/mellum-thinking)
28+ hit it. Each time the model lost many calls: it cannot see the character
29+ (ticket #294, item 3: invisible in diffs), and when the system prompt gives the
30+ exact fix (`perl -pi -e 's/\x0c/\nf/g' main.go`), the model writes its own
31+ command instead, which deletes the character and leaves `unc main()`
32+ (10:11 run: about 10 calls lost, then a broken heredoc rewrite).
33+
34+ A prompt rule does not fix it: the tool has to.
35+
36+ ## The idea
37+
38+ When `write_file` / `edit_file` receive text where U+000C is directly
39+ followed by a lowercase letter that, with an `f` in front, starts a likely
40+ word (`unc`, `or`, `mt.`, `alse`, `loat`…), mm would write `\n` + `f`
41+ (or `f` alone) instead, and say so in the tool output
42+ ("mm: repaired 1 form feed (U+000C) that stood for \"\\f\" → \"\\nf\" at line 21").
43+
44+ ## Before implementing: a study of relevance and non-regression
45+
46+ This changes what the model asked to write, so it needs a real study first.
47+ It is NOT to be implemented on intuition. To establish:
48+
49+ - **Relevance**
50+ - which models and which providers produce it (only Mellum? only with
51+ llmman / llama.cpp? does the chat template or the GGUF matter?);
52+ - which shapes appear in the traces: `\func`, `\for`, `\fmt`, `\false`… and
53+ whether the intended text was `\n` + `f` or just `f`;
54+ - whether a provider-side fix exists instead (template, grammar).
55+ - **Non-regression** — files where U+000C is legitimate must never change:
56+ - binary-ish or data files, PDF/PostScript fragments, test fixtures that
57+ contain form feeds on purpose, Go/C sources with `'\f'` written as a
58+ real character, text files using form feeds as page breaks (old C
59+ sources, RFC texts, Makefiles);
60+ - `edit_file` `old` strings that must match an existing form feed;
61+ - the repair must apply only to the new text of the call, never to the
62+ rest of an existing file.
63+ - **Scope options to compare**: repair only in source files of known
64+ languages; repair only when the file did not contain U+000C before;
65+ warn without repairing (show `\f` in the diff, ticket #294 item 3) as the
66+ lighter alternative; a config switch (default to be decided).
67+ - **Tests**: unit tests for every shape above (repair and no-repair),
68+ plus a re-run of validation/mellum and validation/mellum-thinking to
69+ measure the calls saved.
70+
71+ ## Acceptance criteria
72+
73+ - A written study (shapes seen in the traces, cases where U+000C is
74+ legitimate, chosen scope, why) before any code.
75+ - No change to any file that legitimately contains U+000C (tests prove it).
76+ - The model is told every repair made.
77+tasks:
78+ - id: 1
79+ title: Collect the shapes from the traces of validation/mellum* and demos/mellum2
80+ state: closed
81+ priority: high
82+ author:
83+ name: k33g
84+ email: ph.charriere@gmail.com
85+ createdAt: 2026-12-02T09:22:35.000Z
86+ - id: 2
87+ title: List the legitimate uses of U+000C that must never change
88+ state: closed
89+ priority: high
90+ author:
91+ name: k33g
92+ email: ph.charriere@gmail.com
93+ createdAt: 2026-12-02T09:22:35.000Z
94+ - id: 3
95+ title: Choose the scope (repair, warn only, config switch) and write it down
96+ state: closed
97+ priority: medium
98+ author:
99+ name: k33g
100+ email: ph.charriere@gmail.com
101+ createdAt: 2026-12-02T09:22:35.000Z
102+ - id: 4
103+ title: Implement with repair and no-repair tests, then re-run the Mellum validation agents
104+ state: closed
105+ priority: medium
106+ author:
107+ name: k33g
108+ email: ph.charriere@gmail.com
109+ createdAt: 2026-12-02T09:22:35.000Z
110+ updatedAt: 2026-12-05T09:05:00.000Z
111+ closedAt: 2026-12-05T09:05:00.000Z
112+comments:
113+ - id: 1
114+ author:
115+ name: k33g
116+ email: ph.charriere@gmail.com
117+ createdAt: 2026-12-02T12:50:00.000Z
118+ body: |
119+ Data for task 1 (runs of 2026-12-02 13:36-13:41):
120+ - `validation/mellum` (Mellum2 Instruct Q8_0): `\func` → `<FF>unc` again (6 Mellum2/2.1-Thinking
121+ runs of 6 so far). Repaired by `edit_file` with old `"\func saveLabels() {"`:
122+ the old string decodes to the same form feed, so it matched.
123+ - `validation/mellum-thinking` (Mellum2.1 Thinking Q4_K_M): two form feeds; its own
124+ `perl -pi -e 's/\x0c/\n/g'` (not the command the prompt gives) left `unc loadLabels()`.
125+ - `validation/mellum21` (Mellum2.1 **Instruct** Q8_0): no form feed in 1 run, so the
126+ shape may depend on the model version. Task 1 has to cover Mellum2.1 Instruct too.
127+ - id: 2
128+ author:
129+ name: k33g
130+ email: ph.charriere@gmail.com
131+ createdAt: 2026-12-03T07:35:00.000Z
132+ body: |
133+ `validation/mellum21-thinking` (Mellum2.1 Thinking **Q8_0**, reasoning on),
134+ 2026-12-03 08:19: `\func` → `<FF>unc loadLabels()` again, in the first
135+ write_file. So the quant is not the cause (Q4_K_M and Q8_0 both do it).
136+ The model's own `perl -pi -e 's/\x0c//g'` left `unc`; it then repaired it
137+ with edit_file `unc loadLabels()` → `func loadLabels()` (4 calls lost).
138+ Run archived in `validation/mellum21-thinking/.mm/` (traces of 2026-12-03 08:19-08:24).
139+ - id: 3
140+ author:
141+ name: k33g
142+ email: ph.charriere@gmail.com
143+ createdAt: 2026-12-04T18:40:00.000Z
144+ body: |
145+ Study and implementation, branch `feature/v2.2.2` (2026-12-04), uncommitted. Scope chosen with the user: narrow repair.
146+
147+ Study (traces of validation/, distinct tool calls):
148+ - 8 U+000C in write_file/edit_file arguments: Mellum2 Instruct Q8_0 (4), Mellum2.1 Thinking Q4_K_M (3) and Q8_0 (1); none from Mellum2.1 Instruct (2 runs), Qwen3-Coder, qwen-search. All on llmman. So: the model, not the quant nor the provider (no provider-side fix: `\f` is valid JSON a grammar would have to forbid).
149+ - Every one at the start of a line (after `\n`, or at the start of an edit's old) before `unc ` (func): the intent was `\n\nfunc`.
150+ - 1 was in an edit_file `old`, on purpose, to match the form feed already in the file → old is never repaired.
151+ - 1 more in a bash command (an awk regex): out of scope.
152+ Legitimate U+000C: page breaks alone on their line (C/Python/Lisp/Emacs sources, RFC texts, Makefiles), form feeds inside a line (string literals), data/text files, files already holding one, edit_file old texts.
153+ Rule: FF at the start of a line (after optional spaces/tabs) before [a-z], in content / edits[].new only, files with a known source extension, file holding no FF yet → `\n`+FF becomes `\n\nf`, indented or at the start becomes `f`. The model gets `[mm: repaired N form feed(s) …]` at the END of the output (the headline stays first), the user a 🩹 notice. No config switch.
154+ Tests: `tools/formfeed_test.go` (repair and no-repair). Docs EN+FR done. Re-run of the Mellum agents NOT done (no model in the sandbox).
155+ - id: 4
156+ author:
157+ name: k33g
158+ email: ph.charriere@gmail.com
159+ createdAt: 2026-12-05T09:05:00.000Z
160+ body: |
161+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
new file mode 100644
@@ -0,0 +1,161 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 300
3+title: Repair a form feed written for a backslash-f in code written by write_file and edit_file (study first)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T09:22:35.000Z
9+updatedAt: 2026-12-05T09:05:00.000Z
10+labels:
11+ - enhancement
12+ - priority::medium
13+ - kind::feature
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 294
19+body: |
20+ ## The problem
21+
22+ Mellum models (Mellum2 12B-A2.5B Instruct Q8_0, Mellum2.1-12B-A2.5B-Thinking
23+ Q4_K_M) write a backslash before `func` in the JSON arguments of `write_file`
24+ (`"…\n\func main()…"`). JSON reads `\f` as U+000C (form feed), so the file
25+ gets `<FF>unc main()`. Go then says `invalid character U+000C`.
26+
27+ **4 Mellum runs of 4** on 2026-12-02 (validation/mellum, validation/mellum-thinking)
28+ hit it. Each time the model lost many calls: it cannot see the character
29+ (ticket #294, item 3: invisible in diffs), and when the system prompt gives the
30+ exact fix (`perl -pi -e 's/\x0c/\nf/g' main.go`), the model writes its own
31+ command instead, which deletes the character and leaves `unc main()`
32+ (10:11 run: about 10 calls lost, then a broken heredoc rewrite).
33+
34+ A prompt rule does not fix it: the tool has to.
35+
36+ ## The idea
37+
38+ When `write_file` / `edit_file` receive text where U+000C is directly
39+ followed by a lowercase letter that, with an `f` in front, starts a likely
40+ word (`unc`, `or`, `mt.`, `alse`, `loat`…), mm would write `\n` + `f`
41+ (or `f` alone) instead, and say so in the tool output
42+ ("mm: repaired 1 form feed (U+000C) that stood for \"\\f\" → \"\\nf\" at line 21").
43+
44+ ## Before implementing: a study of relevance and non-regression
45+
46+ This changes what the model asked to write, so it needs a real study first.
47+ It is NOT to be implemented on intuition. To establish:
48+
49+ - **Relevance**
50+ - which models and which providers produce it (only Mellum? only with
51+ llmman / llama.cpp? does the chat template or the GGUF matter?);
52+ - which shapes appear in the traces: `\func`, `\for`, `\fmt`, `\false`… and
53+ whether the intended text was `\n` + `f` or just `f`;
54+ - whether a provider-side fix exists instead (template, grammar).
55+ - **Non-regression** — files where U+000C is legitimate must never change:
56+ - binary-ish or data files, PDF/PostScript fragments, test fixtures that
57+ contain form feeds on purpose, Go/C sources with `'\f'` written as a
58+ real character, text files using form feeds as page breaks (old C
59+ sources, RFC texts, Makefiles);
60+ - `edit_file` `old` strings that must match an existing form feed;
61+ - the repair must apply only to the new text of the call, never to the
62+ rest of an existing file.
63+ - **Scope options to compare**: repair only in source files of known
64+ languages; repair only when the file did not contain U+000C before;
65+ warn without repairing (show `\f` in the diff, ticket #294 item 3) as the
66+ lighter alternative; a config switch (default to be decided).
67+ - **Tests**: unit tests for every shape above (repair and no-repair),
68+ plus a re-run of validation/mellum and validation/mellum-thinking to
69+ measure the calls saved.
70+
71+ ## Acceptance criteria
72+
73+ - A written study (shapes seen in the traces, cases where U+000C is
74+ legitimate, chosen scope, why) before any code.
75+ - No change to any file that legitimately contains U+000C (tests prove it).
76+ - The model is told every repair made.
77+tasks:
78+ - id: 1
79+ title: Collect the shapes from the traces of validation/mellum* and demos/mellum2
80+ state: closed
81+ priority: high
82+ author:
83+ name: k33g
84+ email: ph.charriere@gmail.com
85+ createdAt: 2026-12-02T09:22:35.000Z
86+ - id: 2
87+ title: List the legitimate uses of U+000C that must never change
88+ state: closed
89+ priority: high
90+ author:
91+ name: k33g
92+ email: ph.charriere@gmail.com
93+ createdAt: 2026-12-02T09:22:35.000Z
94+ - id: 3
95+ title: Choose the scope (repair, warn only, config switch) and write it down
96+ state: closed
97+ priority: medium
98+ author:
99+ name: k33g
100+ email: ph.charriere@gmail.com
101+ createdAt: 2026-12-02T09:22:35.000Z
102+ - id: 4
103+ title: Implement with repair and no-repair tests, then re-run the Mellum validation agents
104+ state: closed
105+ priority: medium
106+ author:
107+ name: k33g
108+ email: ph.charriere@gmail.com
109+ createdAt: 2026-12-02T09:22:35.000Z
110+ updatedAt: 2026-12-05T09:05:00.000Z
111+ closedAt: 2026-12-05T09:05:00.000Z
112+comments:
113+ - id: 1
114+ author:
115+ name: k33g
116+ email: ph.charriere@gmail.com
117+ createdAt: 2026-12-02T12:50:00.000Z
118+ body: |
119+ Data for task 1 (runs of 2026-12-02 13:36-13:41):
120+ - `validation/mellum` (Mellum2 Instruct Q8_0): `\func` → `<FF>unc` again (6 Mellum2/2.1-Thinking
121+ runs of 6 so far). Repaired by `edit_file` with old `"\func saveLabels() {"`:
122+ the old string decodes to the same form feed, so it matched.
123+ - `validation/mellum-thinking` (Mellum2.1 Thinking Q4_K_M): two form feeds; its own
124+ `perl -pi -e 's/\x0c/\n/g'` (not the command the prompt gives) left `unc loadLabels()`.
125+ - `validation/mellum21` (Mellum2.1 **Instruct** Q8_0): no form feed in 1 run, so the
126+ shape may depend on the model version. Task 1 has to cover Mellum2.1 Instruct too.
127+ - id: 2
128+ author:
129+ name: k33g
130+ email: ph.charriere@gmail.com
131+ createdAt: 2026-12-03T07:35:00.000Z
132+ body: |
133+ `validation/mellum21-thinking` (Mellum2.1 Thinking **Q8_0**, reasoning on),
134+ 2026-12-03 08:19: `\func` → `<FF>unc loadLabels()` again, in the first
135+ write_file. So the quant is not the cause (Q4_K_M and Q8_0 both do it).
136+ The model's own `perl -pi -e 's/\x0c//g'` left `unc`; it then repaired it
137+ with edit_file `unc loadLabels()` → `func loadLabels()` (4 calls lost).
138+ Run archived in `validation/mellum21-thinking/.mm/` (traces of 2026-12-03 08:19-08:24).
139+ - id: 3
140+ author:
141+ name: k33g
142+ email: ph.charriere@gmail.com
143+ createdAt: 2026-12-04T18:40:00.000Z
144+ body: |
145+ Study and implementation, branch `feature/v2.2.2` (2026-12-04), uncommitted. Scope chosen with the user: narrow repair.
146+
147+ Study (traces of validation/, distinct tool calls):
148+ - 8 U+000C in write_file/edit_file arguments: Mellum2 Instruct Q8_0 (4), Mellum2.1 Thinking Q4_K_M (3) and Q8_0 (1); none from Mellum2.1 Instruct (2 runs), Qwen3-Coder, qwen-search. All on llmman. So: the model, not the quant nor the provider (no provider-side fix: `\f` is valid JSON a grammar would have to forbid).
149+ - Every one at the start of a line (after `\n`, or at the start of an edit's old) before `unc ` (func): the intent was `\n\nfunc`.
150+ - 1 was in an edit_file `old`, on purpose, to match the form feed already in the file → old is never repaired.
151+ - 1 more in a bash command (an awk regex): out of scope.
152+ Legitimate U+000C: page breaks alone on their line (C/Python/Lisp/Emacs sources, RFC texts, Makefiles), form feeds inside a line (string literals), data/text files, files already holding one, edit_file old texts.
153+ Rule: FF at the start of a line (after optional spaces/tabs) before [a-z], in content / edits[].new only, files with a known source extension, file holding no FF yet → `\n`+FF becomes `\n\nf`, indented or at the start becomes `f`. The model gets `[mm: repaired N form feed(s) …]` at the END of the output (the headline stays first), the user a 🩹 notice. No config switch.
154+ Tests: `tools/formfeed_test.go` (repair and no-repair). Docs EN+FR done. Re-run of the Mellum agents NOT done (no model in the sandbox).
155+ - id: 4
156+ author:
157+ name: k33g
158+ email: ph.charriere@gmail.com
159+ createdAt: 2026-12-05T09:05:00.000Z
160+ body: |
161+ Last task closed by the user's decision (2026-12-05): the docs EN+FR were done on 2026-12-04; the re-run part is dropped — validation/qwen-coder is no longer run (the model is too big for the MacBook Air used now) and validation/mellum / mellum-thinking (Mellum2) are no longer checked: validation stays on the Mellum2.1 agents. The fix rests on its unit tests.
added .tickets/issues/0301-reload-a-new-skill-or-updated-without-restarting.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 301
3+title: Reload a new skill (or updated) without restarting mini me
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T16:08:14.429Z
9+updatedAt: 2026-12-02T16:08:14.429Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 301
3+title: Reload a new skill (or updated) without restarting mini me
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-02T16:08:14.429Z
9+updatedAt: 2026-12-02T16:08:14.429Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0302-do-we-need-improvements-per-model.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 302
3+title: Do we need improvements per model?
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-03T05:23:06.098Z
9+updatedAt: 2026-12-04T18:09:34.915Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 302
3+title: Do we need improvements per model?
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-03T05:23:06.098Z
9+updatedAt: 2026-12-04T18:09:34.915Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0303-create-a-test-protocol.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 303
3+title: Create a test protocol
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-03T05:23:25.572Z
9+updatedAt: 2026-12-04T18:09:49.210Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 303
3+title: Create a test protocol
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-03T05:23:25.572Z
9+updatedAt: 2026-12-04T18:09:49.210Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0304-make-a-selection-of-the-demos-agents-and-make-th.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 304
3+title: Make a selection of the ./demos/ agents and make them some ready to use agent in the wizard
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-03T06:41:31.446Z
9+updatedAt: 2026-12-03T06:41:31.446Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 304
3+title: Make a selection of the ./demos/ agents and make them some ready to use agent in the wizard
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-03T06:41:31.446Z
9+updatedAt: 2026-12-03T06:41:31.446Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0305-what-is-the-llamacpp-lazy-mode.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 305
3+title: What is the llamacpp --lazy-mode?
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-04T04:08:37.088Z
9+updatedAt: 2026-12-04T04:08:37.088Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 305
3+title: What is the llamacpp --lazy-mode?
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-04T04:08:37.088Z
9+updatedAt: 2026-12-04T04:08:37.088Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0306-mm-init-for-llamacpp-check-the-port-of-the-gener.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 306
3+title: mm init for llamacpp, check the port of the generates url in the comments
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-04T04:13:07.449Z
9+updatedAt: 2026-12-04T18:10:04.462Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 306
3+title: mm init for llamacpp, check the port of the generates url in the comments
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-04T04:13:07.449Z
9+updatedAt: 2026-12-04T18:10:04.462Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0307-reading-a-broken-file-in-circles-point-at-the-fix.yaml +104 -0
new file mode 100644
@@ -0,0 +1,104 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 307
3+title: A model reads a broken file in circles without editing it — point at the line and the edit_file call
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-04T22:00:00.000Z
9+updatedAt: 2026-12-04T22:00:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 241
19+ - 292
20+ - 295
21+body: |
22+ ## Seen in
23+
24+ `validation/mellum21-thinking` (Mellum2.1 12B Thinking Q8_0, mm v2.2.2 branch, 2026-12-04 22:39-22:54),
25+ traces `.mm/traces/20261204-22*`.
26+
27+ - The model wrote the whole `main.go` with one `}` too many at the end (its own content, `…r))\n}\n}`).
28+ - Diagnostics after the write: `error main.go:142:1 expected declaration, found '}' [syntax]`.
29+ - Its reasoning says "remove the extra brace at line 142", then hesitates: `}` is not unique as an
30+ `edit_file` old text. It reads main.go 8 times (start 142, 139, none, 130, 20, 130, 120…), 20 s to
31+ 4 min of reasoning each, and never edits. The user stopped it after 15 minutes; `maxTurns: 80`
32+ would have taken over an hour.
33+
34+ ## Why nothing reacted
35+
36+ - Loop detector: the reads succeed and their arguments differ.
37+ - Re-read rule (#292): only after a compression.
38+ - Diagnostics recall (#295): each read says "unchanged since you were told, still 1 error(s)" — true,
39+ but it does not say what to do, and the model does not think of edit_file's `line` (#241).
40+
41+ ## Proposal
42+
43+ Count the reads of a file whose diagnostics are unchanged and hold errors (the recalls of #295).
44+ From the 2nd recall on, append a note after the recall: the file was read N times since it last
45+ changed and the error did not move; the text of the first error's line; a ready `edit_file` call
46+ with `line` and that text as `old` (unique thanks to `line`). The count starts again when the file
47+ changes. Also shown to the user (🔁).
48+tasks:
49+ - id: 1
50+ title: Count recalls per file version; from the 2nd, append the fix note with the error line and an edit_file call using line
51+ state: closed
52+ priority: high
53+ author:
54+ name: k33g
55+ email: ph.charriere@gmail.com
56+ createdAt: 2026-12-04T22:00:00.000Z
57+ - id: 2
58+ title: "Tests: no note at the 1st recall, note at the 2nd with line text and call, count reset when the file changes, no note without errors"
59+ state: closed
60+ priority: high
61+ author:
62+ name: k33g
63+ email: ph.charriere@gmail.com
64+ createdAt: 2026-12-04T22:00:00.000Z
65+ - id: 3
66+ title: Docs EN+FR (lsp diagnosticsAfterRead, struggling models)
67+ state: closed
68+ priority: medium
69+ author:
70+ name: k33g
71+ email: ph.charriere@gmail.com
72+ createdAt: 2026-12-04T22:00:00.000Z
73+ - id: 4
74+ title: Re-run validation/mellum21-thinking
75+ state: closed
76+ priority: medium
77+ author:
78+ name: k33g
79+ email: ph.charriere@gmail.com
80+ createdAt: 2026-12-04T22:00:00.000Z
81+comments:
82+ - id: 1
83+ author:
84+ name: k33g
85+ email: ph.charriere@gmail.com
86+ createdAt: 2026-12-04T22:30:00.000Z
87+ body: |
88+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
89+
90+ - Task 1: `editdiag.go` counts the recalls of each version with errors (`diagnosed.recalls`); `readcircle.go` `fixNudge` appends, from the 2nd recall, `[mm: you have read <path> N times since it last changed, and the error has not moved …]` with the first error's line text and an `edit_file` call using `line` (JSON without HTML escaping); 🔁 notice for the user.
91+ - Task 2: `readcircle_test.go` — no note at the 1st recall, note at the 2nd and count at the 3rd, the suggested call fixes a file where `}` appears twice, count reset on a new version, nothing for a clean file, `fixHint` cases (blank line, line outside the file, unparsable error).
92+ - Task 3: docs EN+FR (reference/configuration, explanation/struggling-models, how-to/navigate-code-with-lsp).
93+ - Task 4: re-run NOT done.
94+ - id: 2
95+ author:
96+ name: k33g
97+ email: ph.charriere@gmail.com
98+ createdAt: 2026-12-05T08:30:00.000Z
99+ body: |
100+ Re-run 2026-12-05 07:42-08:02 (`validation/mellum21-thinking/.mm/traces/20261205-*`), on the main.go left with the extra `}`.
101+
102+ - Read 1 got the diagnostics, read 2 the recall, read 3 the note: two calls later the model sent `edit_file {"line": 142, "old": "}", "new": ""}` — fixed. Last night it read 8 times and never edited.
103+ - Defect found: on `could not import gopkg.in/yaml.v3` (go.mod without the require — and still reported after `go get`, see below) the note's ready call was `"new": ""` on the import line: a deletion. Fixed: the suggested `new` is now the old text (copied as is, it changes nothing), and the note says to fix the cause the error names (go.mod for an import). Test updated.
104+ - Not from this ticket: the diagnostics stayed stale after `go get` (bash): gopls is not told that go.mod changed, and the recall is keyed by the file only. Proposed as a separate ticket.
new file mode 100644
@@ -0,0 +1,104 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 307
3+title: A model reads a broken file in circles without editing it — point at the line and the edit_file call
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-04T22:00:00.000Z
9+updatedAt: 2026-12-04T22:00:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 241
19+ - 292
20+ - 295
21+body: |
22+ ## Seen in
23+
24+ `validation/mellum21-thinking` (Mellum2.1 12B Thinking Q8_0, mm v2.2.2 branch, 2026-12-04 22:39-22:54),
25+ traces `.mm/traces/20261204-22*`.
26+
27+ - The model wrote the whole `main.go` with one `}` too many at the end (its own content, `…r))\n}\n}`).
28+ - Diagnostics after the write: `error main.go:142:1 expected declaration, found '}' [syntax]`.
29+ - Its reasoning says "remove the extra brace at line 142", then hesitates: `}` is not unique as an
30+ `edit_file` old text. It reads main.go 8 times (start 142, 139, none, 130, 20, 130, 120…), 20 s to
31+ 4 min of reasoning each, and never edits. The user stopped it after 15 minutes; `maxTurns: 80`
32+ would have taken over an hour.
33+
34+ ## Why nothing reacted
35+
36+ - Loop detector: the reads succeed and their arguments differ.
37+ - Re-read rule (#292): only after a compression.
38+ - Diagnostics recall (#295): each read says "unchanged since you were told, still 1 error(s)" — true,
39+ but it does not say what to do, and the model does not think of edit_file's `line` (#241).
40+
41+ ## Proposal
42+
43+ Count the reads of a file whose diagnostics are unchanged and hold errors (the recalls of #295).
44+ From the 2nd recall on, append a note after the recall: the file was read N times since it last
45+ changed and the error did not move; the text of the first error's line; a ready `edit_file` call
46+ with `line` and that text as `old` (unique thanks to `line`). The count starts again when the file
47+ changes. Also shown to the user (🔁).
48+tasks:
49+ - id: 1
50+ title: Count recalls per file version; from the 2nd, append the fix note with the error line and an edit_file call using line
51+ state: closed
52+ priority: high
53+ author:
54+ name: k33g
55+ email: ph.charriere@gmail.com
56+ createdAt: 2026-12-04T22:00:00.000Z
57+ - id: 2
58+ title: "Tests: no note at the 1st recall, note at the 2nd with line text and call, count reset when the file changes, no note without errors"
59+ state: closed
60+ priority: high
61+ author:
62+ name: k33g
63+ email: ph.charriere@gmail.com
64+ createdAt: 2026-12-04T22:00:00.000Z
65+ - id: 3
66+ title: Docs EN+FR (lsp diagnosticsAfterRead, struggling models)
67+ state: closed
68+ priority: medium
69+ author:
70+ name: k33g
71+ email: ph.charriere@gmail.com
72+ createdAt: 2026-12-04T22:00:00.000Z
73+ - id: 4
74+ title: Re-run validation/mellum21-thinking
75+ state: closed
76+ priority: medium
77+ author:
78+ name: k33g
79+ email: ph.charriere@gmail.com
80+ createdAt: 2026-12-04T22:00:00.000Z
81+comments:
82+ - id: 1
83+ author:
84+ name: k33g
85+ email: ph.charriere@gmail.com
86+ createdAt: 2026-12-04T22:30:00.000Z
87+ body: |
88+ Implemented on branch `feature/v2.2.2` (2026-12-04), uncommitted.
89+
90+ - Task 1: `editdiag.go` counts the recalls of each version with errors (`diagnosed.recalls`); `readcircle.go` `fixNudge` appends, from the 2nd recall, `[mm: you have read <path> N times since it last changed, and the error has not moved …]` with the first error's line text and an `edit_file` call using `line` (JSON without HTML escaping); 🔁 notice for the user.
91+ - Task 2: `readcircle_test.go` — no note at the 1st recall, note at the 2nd and count at the 3rd, the suggested call fixes a file where `}` appears twice, count reset on a new version, nothing for a clean file, `fixHint` cases (blank line, line outside the file, unparsable error).
92+ - Task 3: docs EN+FR (reference/configuration, explanation/struggling-models, how-to/navigate-code-with-lsp).
93+ - Task 4: re-run NOT done.
94+ - id: 2
95+ author:
96+ name: k33g
97+ email: ph.charriere@gmail.com
98+ createdAt: 2026-12-05T08:30:00.000Z
99+ body: |
100+ Re-run 2026-12-05 07:42-08:02 (`validation/mellum21-thinking/.mm/traces/20261205-*`), on the main.go left with the extra `}`.
101+
102+ - Read 1 got the diagnostics, read 2 the recall, read 3 the note: two calls later the model sent `edit_file {"line": 142, "old": "}", "new": ""}` — fixed. Last night it read 8 times and never edited.
103+ - Defect found: on `could not import gopkg.in/yaml.v3` (go.mod without the require — and still reported after `go get`, see below) the note's ready call was `"new": ""` on the import line: a deletion. Fixed: the suggested `new` is now the old text (copied as is, it changes nothing), and the note says to fix the cause the error names (go.mod for an import). Test updated.
104+ - Not from this ticket: the diagnostics stayed stale after `go get` (bash): gopls is not told that go.mod changed, and the recall is keyed by the file only. Proposed as a separate ticket.
added .tickets/issues/0308-lsp-diagnostics-stale-after-go-mod-go-sum-change.yaml +112 -0
new file mode 100644
@@ -0,0 +1,112 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 308
3+title: lsp diagnostics stale after go.mod / go.sum change through bash (go get, go mod tidy)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-05T08:46:00.000Z
9+updatedAt: 2026-12-05T19:30:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 294
19+ - 307
20+body: |
21+ ## Seen in
22+
23+ `validation/mellum21-thinking` (Mellum2.1 12B-A2.5B Thinking Q8_0, branch `feature/v2.2.2`),
24+ runs of 2026-12-05 07:42 and 08:21, traces `validation/mellum21-thinking/.mm/traces/20261205-*`.
25+
26+ The model writes main.go importing `gopkg.in/yaml.v3`, then runs `go get gopkg.in/yaml.v3`
27+ through bash (`go: added gopkg.in/yaml.v3 v3.0.1`). The next diagnostics mm shows still say
28+ `could not import gopkg.in/yaml.v3 (no required module provides package …)` and
29+ `undefined: yaml`, after a later `edit_file` on main.go as well (08:21 run, request 17).
30+ The build passes. The model then spends calls on `go mod tidy`, `go list -m`, `go mod download`,
31+ re-reads of go.mod — chasing an error that no longer exists.
32+
33+ ## Cause (read in the code, not yet reproduced in a test)
34+
35+ 1. mm never tells gopls that go.mod / go.sum changed when the change does not go through
36+ `write_file` / `edit_file`: no `workspace/didChangeWatchedFiles` is sent. gopls keeps the
37+ module graph it loaded and keeps answering with the old import error.
38+ 2. The recall cache (`editDiag.seen`, `internal/tools/editdiag.go`) is keyed by the file's own
39+ stamp (modification time + size). A read of an unchanged main.go recalls the old errors even
40+ when go.mod changed underneath; #307's fix note can then point at a fix for an error that is gone.
41+
42+ Same family as the open question of #294 (a false `clean` after a go.mod appears).
43+
44+ ## Expected
45+
46+ - After a bash command (or any tool) changes go.mod / go.sum / go.work, gopls gets
47+ `workspace/didChangeWatchedFiles` before the next diagnostics are asked.
48+ - The recall cache does not serve diagnostics older than the last change of those files.
49+ - No cost when nothing changed (no extra wait on every call).
50+tasks:
51+ - id: 1
52+ title: 'Reproduce in a test: file importing a module not in go.mod, diagnostics, go get through bash, diagnostics again (real gopls if available, else the fake client)'
53+ state: closed
54+ priority: high
55+ author:
56+ name: k33g
57+ email: ph.charriere@gmail.com
58+ createdAt: 2026-12-05T08:46:00.000Z
59+ updatedAt: 2026-12-05T09:10:00.000Z
60+ closedAt: 2026-12-05T09:10:00.000Z
61+ - id: 2
62+ title: 'Detect a change of go.mod / go.sum / go.work after each tool call (stamp before / after) and send workspace/didChangeWatchedFiles to the servers that asked for it'
63+ state: closed
64+ priority: high
65+ author:
66+ name: k33g
67+ email: ph.charriere@gmail.com
68+ createdAt: 2026-12-05T08:46:00.000Z
69+ updatedAt: 2026-12-05T09:10:00.000Z
70+ closedAt: 2026-12-05T09:10:00.000Z
71+ - id: 3
72+ title: 'Invalidate editDiag.seen when those files change (key the cache on the file stamp + the module files stamp)'
73+ state: closed
74+ priority: high
75+ author:
76+ name: k33g
77+ email: ph.charriere@gmail.com
78+ createdAt: 2026-12-05T08:46:00.000Z
79+ updatedAt: 2026-12-05T09:10:00.000Z
80+ closedAt: 2026-12-05T09:10:00.000Z
81+ - id: 4
82+ title: Docs EN+FR (lsp tool explanation, navigate-code-with-lsp how-to) and re-run validation/mellum21-thinking
83+ state: closed
84+ priority: medium
85+ author:
86+ name: k33g
87+ email: ph.charriere@gmail.com
88+ createdAt: 2026-12-05T08:46:00.000Z
89+ updatedAt: 2026-12-05T19:30:00.000Z
90+ closedAt: 2026-12-05T19:30:00.000Z
91+comments:
92+ - id: 1
93+ author:
94+ name: k33g
95+ email: ph.charriere@gmail.com
96+ createdAt: 2026-12-05T09:10:00.000Z
97+ body: |
98+ Implemented on branch `feature/v2.2.2`, uncommitted.
99+
100+ - Reproduced with the real gopls (`lsp/gopls_test.go` `TestDiagnosticsWithGoplsAfterGoModChangesOutsideTheTools`: main.go imports a module, go.mod is rewritten behind the client's back with require + replace; before the fix: `could not import example.com/dep` "as last published" after a 20 s wait; after: clean in 1.5 s).
101+ - `lsp/watch.go`: `notifyWatched`, called by `sync` (under `s.mu`, before the didOpen/didChange): the workspace files (go.mod, go.sum, go.work, go.work.sum, package.json, package-lock.json, tsconfig.json, jsconfig.json, Cargo.toml, Cargo.lock, pyproject.toml, requirements.txt) of the file's directory and every directory above it up to the root, plus those of every open document; stamp = mtime + size; first sight records only; one `workspace/didChangeWatchedFiles` with Created / Changed / Deleted. No capability declared: gopls handles the notification anyway (measured). Test `TestWorkspaceFileChangesAreAnnounced` (fake server).
102+ - `tools/editdiag.go`: `fileStamp.workspace` (stamps of those files) — a re-read recalls errors only while neither the file nor its workspace files changed. Test `TestDiagnosticsAfterReadAskAgainWhenGoModChanged`.
103+ - All three tests fail without the fix. `go test ./...`, `go vet ./...` green; quality gate PASS (run 39; run 38 flagged `sync` with 6 returns → split into `readOnDisk` + `syncText`).
104+ - Docs EN+FR: explanation/lsp-tool.md (new section), how-to/navigate-code-with-lsp.md (variant). Task 4 stays open for the re-run of validation/mellum21-thinking.
105+ - id: 2
106+ author:
107+ name: k33g
108+ email: ph.charriere@gmail.com
109+ createdAt: 2026-12-05T19:30:00.000Z
110+ body: |
111+ Re-run 2026-12-05 20:06-20:23 of `validation/mellum21-thinking` (mm rebuilt with #308, alone on the server): **ALL OK**, 18 calls, ~17 min on the MacBook Air M4. The stale case did not occur: the model ran `go get gopkg.in/yaml.v3` BEFORE writing main.go, so gopls started on a complete go.mod (no `could not import` at any point). The fix itself is covered by the real-gopls test `TestDiagnosticsWithGoplsAfterGoModChangesOutsideTheTools`. Task 4 closed (docs done, re-run done); reopen if a run shows `could not import` after a `go get` again.
112+
new file mode 100644
@@ -0,0 +1,112 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 308
3+title: lsp diagnostics stale after go.mod / go.sum change through bash (go get, go mod tidy)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-12-05T08:46:00.000Z
9+updatedAt: 2026-12-05T19:30:00.000Z
10+labels:
11+ - bug
12+ - priority::high
13+ - kind::bug
14+ - builtin tool
15+milestone: v2.2.2
16+epic: Builtin tools
17+related:
18+ - 294
19+ - 307
20+body: |
21+ ## Seen in
22+
23+ `validation/mellum21-thinking` (Mellum2.1 12B-A2.5B Thinking Q8_0, branch `feature/v2.2.2`),
24+ runs of 2026-12-05 07:42 and 08:21, traces `validation/mellum21-thinking/.mm/traces/20261205-*`.
25+
26+ The model writes main.go importing `gopkg.in/yaml.v3`, then runs `go get gopkg.in/yaml.v3`
27+ through bash (`go: added gopkg.in/yaml.v3 v3.0.1`). The next diagnostics mm shows still say
28+ `could not import gopkg.in/yaml.v3 (no required module provides package …)` and
29+ `undefined: yaml`, after a later `edit_file` on main.go as well (08:21 run, request 17).
30+ The build passes. The model then spends calls on `go mod tidy`, `go list -m`, `go mod download`,
31+ re-reads of go.mod — chasing an error that no longer exists.
32+
33+ ## Cause (read in the code, not yet reproduced in a test)
34+
35+ 1. mm never tells gopls that go.mod / go.sum changed when the change does not go through
36+ `write_file` / `edit_file`: no `workspace/didChangeWatchedFiles` is sent. gopls keeps the
37+ module graph it loaded and keeps answering with the old import error.
38+ 2. The recall cache (`editDiag.seen`, `internal/tools/editdiag.go`) is keyed by the file's own
39+ stamp (modification time + size). A read of an unchanged main.go recalls the old errors even
40+ when go.mod changed underneath; #307's fix note can then point at a fix for an error that is gone.
41+
42+ Same family as the open question of #294 (a false `clean` after a go.mod appears).
43+
44+ ## Expected
45+
46+ - After a bash command (or any tool) changes go.mod / go.sum / go.work, gopls gets
47+ `workspace/didChangeWatchedFiles` before the next diagnostics are asked.
48+ - The recall cache does not serve diagnostics older than the last change of those files.
49+ - No cost when nothing changed (no extra wait on every call).
50+tasks:
51+ - id: 1
52+ title: 'Reproduce in a test: file importing a module not in go.mod, diagnostics, go get through bash, diagnostics again (real gopls if available, else the fake client)'
53+ state: closed
54+ priority: high
55+ author:
56+ name: k33g
57+ email: ph.charriere@gmail.com
58+ createdAt: 2026-12-05T08:46:00.000Z
59+ updatedAt: 2026-12-05T09:10:00.000Z
60+ closedAt: 2026-12-05T09:10:00.000Z
61+ - id: 2
62+ title: 'Detect a change of go.mod / go.sum / go.work after each tool call (stamp before / after) and send workspace/didChangeWatchedFiles to the servers that asked for it'
63+ state: closed
64+ priority: high
65+ author:
66+ name: k33g
67+ email: ph.charriere@gmail.com
68+ createdAt: 2026-12-05T08:46:00.000Z
69+ updatedAt: 2026-12-05T09:10:00.000Z
70+ closedAt: 2026-12-05T09:10:00.000Z
71+ - id: 3
72+ title: 'Invalidate editDiag.seen when those files change (key the cache on the file stamp + the module files stamp)'
73+ state: closed
74+ priority: high
75+ author:
76+ name: k33g
77+ email: ph.charriere@gmail.com
78+ createdAt: 2026-12-05T08:46:00.000Z
79+ updatedAt: 2026-12-05T09:10:00.000Z
80+ closedAt: 2026-12-05T09:10:00.000Z
81+ - id: 4
82+ title: Docs EN+FR (lsp tool explanation, navigate-code-with-lsp how-to) and re-run validation/mellum21-thinking
83+ state: closed
84+ priority: medium
85+ author:
86+ name: k33g
87+ email: ph.charriere@gmail.com
88+ createdAt: 2026-12-05T08:46:00.000Z
89+ updatedAt: 2026-12-05T19:30:00.000Z
90+ closedAt: 2026-12-05T19:30:00.000Z
91+comments:
92+ - id: 1
93+ author:
94+ name: k33g
95+ email: ph.charriere@gmail.com
96+ createdAt: 2026-12-05T09:10:00.000Z
97+ body: |
98+ Implemented on branch `feature/v2.2.2`, uncommitted.
99+
100+ - Reproduced with the real gopls (`lsp/gopls_test.go` `TestDiagnosticsWithGoplsAfterGoModChangesOutsideTheTools`: main.go imports a module, go.mod is rewritten behind the client's back with require + replace; before the fix: `could not import example.com/dep` "as last published" after a 20 s wait; after: clean in 1.5 s).
101+ - `lsp/watch.go`: `notifyWatched`, called by `sync` (under `s.mu`, before the didOpen/didChange): the workspace files (go.mod, go.sum, go.work, go.work.sum, package.json, package-lock.json, tsconfig.json, jsconfig.json, Cargo.toml, Cargo.lock, pyproject.toml, requirements.txt) of the file's directory and every directory above it up to the root, plus those of every open document; stamp = mtime + size; first sight records only; one `workspace/didChangeWatchedFiles` with Created / Changed / Deleted. No capability declared: gopls handles the notification anyway (measured). Test `TestWorkspaceFileChangesAreAnnounced` (fake server).
102+ - `tools/editdiag.go`: `fileStamp.workspace` (stamps of those files) — a re-read recalls errors only while neither the file nor its workspace files changed. Test `TestDiagnosticsAfterReadAskAgainWhenGoModChanged`.
103+ - All three tests fail without the fix. `go test ./...`, `go vet ./...` green; quality gate PASS (run 39; run 38 flagged `sync` with 6 returns → split into `readOnDisk` + `syncText`).
104+ - Docs EN+FR: explanation/lsp-tool.md (new section), how-to/navigate-code-with-lsp.md (variant). Task 4 stays open for the re-run of validation/mellum21-thinking.
105+ - id: 2
106+ author:
107+ name: k33g
108+ email: ph.charriere@gmail.com
109+ createdAt: 2026-12-05T19:30:00.000Z
110+ body: |
111+ Re-run 2026-12-05 20:06-20:23 of `validation/mellum21-thinking` (mm rebuilt with #308, alone on the server): **ALL OK**, 18 calls, ~17 min on the MacBook Air M4. The stale case did not occur: the model ran `go get gopkg.in/yaml.v3` BEFORE writing main.go, so gopls started on a complete go.mod (no `could not import` at any point). The fix itself is covered by the real-gopls test `TestDiagnosticsWithGoplsAfterGoModChangesOutsideTheTools`. Task 4 closed (docs done, re-run done); reopen if a run shows `could not import` after a `go get` again.
112+
modified .tickets/milestones.yaml +3 -0
@@ -87,3 +87,6 @@ milestones:
8787 - title: v2.2.1
8888 state: closed
8989 description: Fixes after v2.2.0 — compaction inside a turn on small windows (tickets 289-292)
90+ - title: v2.2.2
91+ state: open
92+ description: Fixes after v2.2.1 — tool feedback that misleads small models (lsp diagnostics, no-op edits, loop detection, plan tool) and degenerate replies (blank-line runaway, tool call inside the reasoning, form feed written for backslash-f, a broken file read in circles, diagnostics stale after go.mod changes) — tickets 294-300, 307 and 308
@@ -87,3 +87,6 @@ milestones:
87 - title: v2.2.187 - title: v2.2.1
88 state: closed88 state: closed
89 description: Fixes after v2.2.0 — compaction inside a turn on small windows (tickets 289-292)89 description: Fixes after v2.2.0 — compaction inside a turn on small windows (tickets 289-292)
90+ - title: v2.2.2
91+ state: open
92+ description: Fixes after v2.2.1 — tool feedback that misleads small models (lsp diagnostics, no-op edits, loop detection, plan tool) and degenerate replies (blank-line runaway, tool call inside the reasoning, form feed written for backslash-f, a broken file read in circles, diagnostics stale after go.mod changes) — tickets 294-300, 307 and 308
modified demos/gemma-coder/agent.yaml +9 -4
@@ -30,11 +30,16 @@
3030
3131 # ─── Model and server ────────────────────────────────────────────────────────
3232
33-provider: llmman
34-model: hf.co/unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
33+# provider: llmman
34+# model: hf.co/unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
3535
36-baseUrl: http://127.0.0.1:17434/v1
37-fallback: http://host.docker.internal:17434/v1
36+# baseUrl: http://127.0.0.1:17434/v1
37+# fallback: http://host.docker.internal:17434/v1
38+
39+provider: llamacpp
40+model: unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
41+baseUrl: http://127.0.0.1:9931/v1
42+fallback: http://host.docker.internal:9931/v1
3843
3944 contextWindow: 0
4045
@@ -30,11 +30,16 @@
30 30
31 # ─── Model and server ────────────────────────────────────────────────────────31 # ─── Model and server ────────────────────────────────────────────────────────
32 32
33-provider: llmman33+# provider: llmman
34-model: hf.co/unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M34+# model: hf.co/unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
35 35
36-baseUrl: http://127.0.0.1:17434/v136+# baseUrl: http://127.0.0.1:17434/v1
37-fallback: http://host.docker.internal:17434/v137+# fallback: http://host.docker.internal:17434/v1
38+
39+provider: llamacpp
40+model: unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
41+baseUrl: http://127.0.0.1:9931/v1
42+fallback: http://host.docker.internal:9931/v1
38 43
39 contextWindow: 044 contextWindow: 0
40 45
added demos/notes-taker/.gitignore +4 -0
new file mode 100644
@@ -0,0 +1,4 @@
1+!.mm
2+sessions
3+traces
4+check-search.log
new file mode 100644
@@ -0,0 +1,4 @@
1+!.mm
2+sessions
3+traces
4+check-search.log
added demos/notes-taker/.mm/agent.yaml +178 -0
new file mode 100644
@@ -0,0 +1,178 @@
1+# 🐱 Bob — a coding agent: reads and changes the project, runs commands.
2+#
3+# Written by `mm init`. Every value says why it has that value; change
4+# them as you watch the agent work:
5+# https://rickub.com/bots-garden/mini-me/blob/main/guides/agent-settings-for-small-models.md
6+#
7+# model family: gemma
8+# usage: developer
9+# machine: medium — a workstation, models up to about 30B
10+# model facts: read from llamacpp: native window 4096 tokens; reasoning switch enable_thinking (default off)
11+#
12+# Where the numbers come from (the tag before their comment):
13+# [card] from the model card or the GGUF, not measured — re-read the new card
14+# [guide] the settings guide's row for this machine
15+# [rule] a rule of thumb, not specific to this model
16+#
17+# mm or mm tui started from the project root (it finds .mm/agent.yaml)
18+
19+provider: llamacpp
20+# The model. Chosen for it (family gemma): sampling (temperature, top_p,
21+# top_k, max_tokens) and sampling.chat_template_kwargs (enable_thinking).
22+# Change the model and redo them together — running mm init again is the
23+# quick way.
24+#model: unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
25+model: unsloth/gemma-4-E4B-it-GGUF:Q4_K_M
26+# No baseUrl: llamacpp's defaults apply. For the record:
27+# baseUrl: "http://127.0.0.1:9931/v1"
28+# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer)
29+# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer
30+# Nothing answers at this address: mm starts llama-server (router mode, this
31+# model, downloaded on first use) and stops it with the last mm session using
32+# it. A server you started yourself is never stopped. false: start it yourself.
33+llamacpp:
34+ autoStart: true
35+ # Launch settings, the Llama app's values: each key is one llama-server
36+ # flag; remove a key and llama-server keeps its own default.
37+ # ctxSize: 32768 # --ctx-size (default: the model's own window)
38+ modelsMax: 0 # --models-max: 0 = no limit on loaded models (default 4)
39+ modelsMemoryMargin: 1024 # --models-memory-margin: MiB kept free (default 0 = off)
40+ fitTarget: 1024 # --fit-target: MiB margin per device (default 1024)
41+ sleepIdleSeconds: 300 # --sleep-idle-seconds: free the model when idle (default -1 = never)
42+ specDefault: true # --spec-default: default speculative decoding
43+ # serverArgs: [] # any other flag
44+
45+# 0 = mm asks the server for the window it serves (the model's native window
46+# is 4096 tokens; the server may serve less)
47+contextWindow: 0
48+# your answer: tools run without asking
49+yolo: true
50+# usage developer
51+bashTool: true
52+editTools: true
53+planTool: false
54+askUserTool: true
55+# unload the model from the server's memory when mm exits; false keeps it
56+# loaded (faster next start, or another tool uses it)
57+unloadOnExit: true
58+# your answer: a <name>.md or <name>/SKILL.md per skill, in .mm/skills/ —
59+# relative to the directory mm is started from, the project root (see
60+# https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)
61+skillsDir: .mm/skills
62+# usage developer
63+maxTurns: 40
64+# [guide] settings guide, row "Small/medium model, general coding agent"
65+maxOutput: 24000
66+firstTokenTimeout: 10m
67+watchdogTimeout: 5m
68+bashTimeout: 60s
69+
70+sampling:
71+ # [card] family gemma: Gemma 4 GGUF sampling 1.0 / 0.95 / 64
72+ # (demos/gemini-style); precise 0.2 measured with gemma-4-E4B (demos/hooks,
73+ # guards); enable_thinking is off by default in the template
74+ temperature: 0.2
75+ top_p: 0.9
76+ top_k: 64
77+ # [rule] reasoning on: room for the thoughts plus a whole tool call
78+ max_tokens: 32768
79+ # one tool call per reply: small models run a check before the change it
80+ # checks has landed otherwise
81+ parallel_tool_calls: false
82+ chat_template_kwargs:
83+ # reasoning on: code and multi-step work; the template's default is off
84+ # (read from the chat template)
85+ enable_thinking: true
86+
87+context:
88+ # compress the history before the window is full (settings guide, every row)
89+ enabled: true
90+ # mm's default: 75 % of the window the server serves, a quarter left for the
91+ # next question and its tool outputs
92+ threshold: 75
93+
94+sessions:
95+ # your answer: every conversation is saved; /sessions lists them, /resume
96+ # reopens one
97+ enabled: true
98+ # relative to the directory mm is started from: one folder per project
99+ dir: .mm/sessions
100+
101+agentsMd:
102+ # An AGENTS.md in the project directory is added to the system prompt.
103+ enabled: true
104+
105+acp:
106+ name: 🐱 bob
107+ title: "🐱 Bob (developer)"
108+
109+trace:
110+ enabled: true
111+
112+# Variables: {{date}}, {{cwd}}, {{env.NAME}}, {{config.NAME}} (a variables: section) — replaced when a conversation starts.
113+# Rewritten for the real use of this folder (3 sessions read): Bob takes
114+# meeting notes in a YAML file, the user types short fragments in French. What
115+# the generic coding prompt got wrong there: it named a plan tool that is off
116+# (planTool: false); one answer came out in English; each answer re-printed the
117+# whole section; "le kickoff était hier" was filed as "hier"; a remark on
118+# Office 365 licences went into a feature's description; the skills folder
119+# convention (one folder per skill) had to be taught by the user.
120+system: |
121+ Your name is 🐱 Bob.
122+ You are a meeting note-taker in a terminal, in the notes folder ({{cwd}}).
123+ Today is {{date}}.
124+ The user types short fragments during or after a meeting ("le RFP sera lancé
125+ en janvier"). Each message is a fact to file, not a question: file it, then
126+ confirm. Never ask permission. You are not a coding agent here: no go, npm
127+ or pip; bash only for ls, mkdir, mv.
128+
129+ The notes file
130+ 1. One file per meeting: meeting_<client>.yaml, in the current folder. None
131+ yet: read the note_taking skill (read_skill) and create it with that
132+ structure. Several: use the one you last worked in, or ask which.
133+ 2. Read it once before your first change. After that use edit_file with
134+ small edits; never rewrite an existing file with write_file.
135+ 3. File each fact where it belongs:
136+ key_points = presented, decided, important
137+ questions_asked = who asked what, and the answer
138+ remarks = constraints, context, side notes (licences, budget, air-gap)
139+ to_research = to look into
140+ next_steps = future steps and their dates
141+ todo = immediate tasks, with the owner
142+ A fact about something already noted goes into that item, not a
143+ duplicate; a correction replaces the old text.
144+ 4. Write only what the user said: invent no name, date or number, draw no
145+ conclusion. Unsure of the section or of who "ils" is: file it in
146+ remarks as said and name the doubt in your reply.
147+ 5. A relative date ("hier", "vendredi") becomes YYYY-MM-DD, computed from
148+ today. Not sure of the calculation: keep the user's word and say so.
149+ 6. Keep the YAML valid: same indentation as the lines around (2 spaces per
150+ level), quotes around a value containing ": ". The tool output shows the
151+ changed lines: check them, fix a broken structure at once.
152+ 7. Notes and replies are in the language of the user's last message; the
153+ keys stay as the skill gives them.
154+
155+ Your reply
156+ - After a note: ONE short line, what you added and under which key
157+ ("Ajouté dans next_steps."). Do not print the file or the section
158+ again unless asked.
159+ - Never state the content of a file or the output of a command you did not
160+ read or run in this answer.
161+
162+ Reports and skills
163+ - A report ($report_generator, "fais le compte-rendu"): read the
164+ report_generator skill and the YAML, write report_<client>.md in
165+ the current folder. Only what the YAML contains.
166+ - A skill is a folder: .mm/skills/<name>/SKILL.md.
167+
168+# Next: skills https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md
169+# MCP servers https://rickub.com/bots-garden/mini-me/blob/main/docs/en/tutorials/mcp-getting-started.md
170+# hooks https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/guard-the-agent-with-hooks.md
171+# sessions https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/keep-sessions.md
172+bashBackground: stop
173+
174+# A wrong path is repaired (/meeting_x.yaml → meeting_x.yaml) or refused with a
175+# relative suggestion; files stay inside the notes folder.
176+workspace:
177+ confine: true
178+ repairPaths: true
\ No newline at end of file
new file mode 100644
@@ -0,0 +1,178 @@
1+# 🐱 Bob — a coding agent: reads and changes the project, runs commands.
2+#
3+# Written by `mm init`. Every value says why it has that value; change
4+# them as you watch the agent work:
5+# https://rickub.com/bots-garden/mini-me/blob/main/guides/agent-settings-for-small-models.md
6+#
7+# model family: gemma
8+# usage: developer
9+# machine: medium — a workstation, models up to about 30B
10+# model facts: read from llamacpp: native window 4096 tokens; reasoning switch enable_thinking (default off)
11+#
12+# Where the numbers come from (the tag before their comment):
13+# [card] from the model card or the GGUF, not measured — re-read the new card
14+# [guide] the settings guide's row for this machine
15+# [rule] a rule of thumb, not specific to this model
16+#
17+# mm or mm tui started from the project root (it finds .mm/agent.yaml)
18+
19+provider: llamacpp
20+# The model. Chosen for it (family gemma): sampling (temperature, top_p,
21+# top_k, max_tokens) and sampling.chat_template_kwargs (enable_thinking).
22+# Change the model and redo them together — running mm init again is the
23+# quick way.
24+#model: unsloth/gemma-4-26B-A4B-it-GGUF:Q4_K_M
25+model: unsloth/gemma-4-E4B-it-GGUF:Q4_K_M
26+# No baseUrl: llamacpp's defaults apply. For the record:
27+# baseUrl: "http://127.0.0.1:9931/v1"
28+# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer)
29+# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer
30+# Nothing answers at this address: mm starts llama-server (router mode, this
31+# model, downloaded on first use) and stops it with the last mm session using
32+# it. A server you started yourself is never stopped. false: start it yourself.
33+llamacpp:
34+ autoStart: true
35+ # Launch settings, the Llama app's values: each key is one llama-server
36+ # flag; remove a key and llama-server keeps its own default.
37+ # ctxSize: 32768 # --ctx-size (default: the model's own window)
38+ modelsMax: 0 # --models-max: 0 = no limit on loaded models (default 4)
39+ modelsMemoryMargin: 1024 # --models-memory-margin: MiB kept free (default 0 = off)
40+ fitTarget: 1024 # --fit-target: MiB margin per device (default 1024)
41+ sleepIdleSeconds: 300 # --sleep-idle-seconds: free the model when idle (default -1 = never)
42+ specDefault: true # --spec-default: default speculative decoding
43+ # serverArgs: [] # any other flag
44+
45+# 0 = mm asks the server for the window it serves (the model's native window
46+# is 4096 tokens; the server may serve less)
47+contextWindow: 0
48+# your answer: tools run without asking
49+yolo: true
50+# usage developer
51+bashTool: true
52+editTools: true
53+planTool: false
54+askUserTool: true
55+# unload the model from the server's memory when mm exits; false keeps it
56+# loaded (faster next start, or another tool uses it)
57+unloadOnExit: true
58+# your answer: a <name>.md or <name>/SKILL.md per skill, in .mm/skills/ —
59+# relative to the directory mm is started from, the project root (see
60+# https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md)
61+skillsDir: .mm/skills
62+# usage developer
63+maxTurns: 40
64+# [guide] settings guide, row "Small/medium model, general coding agent"
65+maxOutput: 24000
66+firstTokenTimeout: 10m
67+watchdogTimeout: 5m
68+bashTimeout: 60s
69+
70+sampling:
71+ # [card] family gemma: Gemma 4 GGUF sampling 1.0 / 0.95 / 64
72+ # (demos/gemini-style); precise 0.2 measured with gemma-4-E4B (demos/hooks,
73+ # guards); enable_thinking is off by default in the template
74+ temperature: 0.2
75+ top_p: 0.9
76+ top_k: 64
77+ # [rule] reasoning on: room for the thoughts plus a whole tool call
78+ max_tokens: 32768
79+ # one tool call per reply: small models run a check before the change it
80+ # checks has landed otherwise
81+ parallel_tool_calls: false
82+ chat_template_kwargs:
83+ # reasoning on: code and multi-step work; the template's default is off
84+ # (read from the chat template)
85+ enable_thinking: true
86+
87+context:
88+ # compress the history before the window is full (settings guide, every row)
89+ enabled: true
90+ # mm's default: 75 % of the window the server serves, a quarter left for the
91+ # next question and its tool outputs
92+ threshold: 75
93+
94+sessions:
95+ # your answer: every conversation is saved; /sessions lists them, /resume
96+ # reopens one
97+ enabled: true
98+ # relative to the directory mm is started from: one folder per project
99+ dir: .mm/sessions
100+
101+agentsMd:
102+ # An AGENTS.md in the project directory is added to the system prompt.
103+ enabled: true
104+
105+acp:
106+ name: 🐱 bob
107+ title: "🐱 Bob (developer)"
108+
109+trace:
110+ enabled: true
111+
112+# Variables: {{date}}, {{cwd}}, {{env.NAME}}, {{config.NAME}} (a variables: section) — replaced when a conversation starts.
113+# Rewritten for the real use of this folder (3 sessions read): Bob takes
114+# meeting notes in a YAML file, the user types short fragments in French. What
115+# the generic coding prompt got wrong there: it named a plan tool that is off
116+# (planTool: false); one answer came out in English; each answer re-printed the
117+# whole section; "le kickoff était hier" was filed as "hier"; a remark on
118+# Office 365 licences went into a feature's description; the skills folder
119+# convention (one folder per skill) had to be taught by the user.
120+system: |
121+ Your name is 🐱 Bob.
122+ You are a meeting note-taker in a terminal, in the notes folder ({{cwd}}).
123+ Today is {{date}}.
124+ The user types short fragments during or after a meeting ("le RFP sera lancé
125+ en janvier"). Each message is a fact to file, not a question: file it, then
126+ confirm. Never ask permission. You are not a coding agent here: no go, npm
127+ or pip; bash only for ls, mkdir, mv.
128+
129+ The notes file
130+ 1. One file per meeting: meeting_<client>.yaml, in the current folder. None
131+ yet: read the note_taking skill (read_skill) and create it with that
132+ structure. Several: use the one you last worked in, or ask which.
133+ 2. Read it once before your first change. After that use edit_file with
134+ small edits; never rewrite an existing file with write_file.
135+ 3. File each fact where it belongs:
136+ key_points = presented, decided, important
137+ questions_asked = who asked what, and the answer
138+ remarks = constraints, context, side notes (licences, budget, air-gap)
139+ to_research = to look into
140+ next_steps = future steps and their dates
141+ todo = immediate tasks, with the owner
142+ A fact about something already noted goes into that item, not a
143+ duplicate; a correction replaces the old text.
144+ 4. Write only what the user said: invent no name, date or number, draw no
145+ conclusion. Unsure of the section or of who "ils" is: file it in
146+ remarks as said and name the doubt in your reply.
147+ 5. A relative date ("hier", "vendredi") becomes YYYY-MM-DD, computed from
148+ today. Not sure of the calculation: keep the user's word and say so.
149+ 6. Keep the YAML valid: same indentation as the lines around (2 spaces per
150+ level), quotes around a value containing ": ". The tool output shows the
151+ changed lines: check them, fix a broken structure at once.
152+ 7. Notes and replies are in the language of the user's last message; the
153+ keys stay as the skill gives them.
154+
155+ Your reply
156+ - After a note: ONE short line, what you added and under which key
157+ ("Ajouté dans next_steps."). Do not print the file or the section
158+ again unless asked.
159+ - Never state the content of a file or the output of a command you did not
160+ read or run in this answer.
161+
162+ Reports and skills
163+ - A report ($report_generator, "fais le compte-rendu"): read the
164+ report_generator skill and the YAML, write report_<client>.md in
165+ the current folder. Only what the YAML contains.
166+ - A skill is a folder: .mm/skills/<name>/SKILL.md.
167+
168+# Next: skills https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/add-a-skill.md
169+# MCP servers https://rickub.com/bots-garden/mini-me/blob/main/docs/en/tutorials/mcp-getting-started.md
170+# hooks https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/guard-the-agent-with-hooks.md
171+# sessions https://rickub.com/bots-garden/mini-me/blob/main/docs/en/how-to/keep-sessions.md
172+bashBackground: stop
173+
174+# A wrong path is repaired (/meeting_x.yaml → meeting_x.yaml) or refused with a
175+# relative suggestion; files stay inside the notes folder.
176+workspace:
177+ confine: true
178+ repairPaths: true
\ No newline at end of file\ No newline at end of file
added demos/notes-taker/.mm/skills/note_taking/SKILL.md +49 -0
new file mode 100644
@@ -0,0 +1,49 @@
1+# Meeting Note Taking Skill
2+
3+This skill describes the process of documenting a meeting in a structured YAML format.
4+
5+## Objective
6+To capture and organize information from a meeting to ensure all key points, decisions, questions, and tasks are recorded and actionable.
7+
8+## Process
9+
10+1. **Identify Key Information**: During the meeting, listen for and note down:
11+ * **Key Points (`key_points`)**: Main topics discussed, decisions made, or important information shared.
12+ * **Questions Asked (`questions_asked`)**: Questions raised by participants, including who asked them and any context or answers provided.
13+ * **Remarks (`remarks`)**: Observations, constraints, or side notes that are relevant but don't fit into other categories.
14+ * **Research Tasks (`to_research`)**: Things that need further investigation or clarification.
15+ * **Next Steps (`next_steps`)**: Planned future actions or upcoming milestones (e.g., RFP dates).
16+ * **To-Do Items (`todo`)**: Immediate tasks for the team or individuals.
17+
18+2. **Structure in YAML**: Use a structured YAML file to organize these notes. A recommended structure is:
19+
20+```yaml
21+meeting:
22+ client: <Client Name>
23+ subject: <Meeting Subject>
24+ key_points:
25+ <category>:
26+ <sub-category>:
27+ <property>: <description>
28+ questions_asked:
29+ - author: <Name>
30+ subject: <Subject>
31+ notes: <Details>
32+ remarks:
33+ - <Remark 1>
34+ - <Remark 2>
35+ to_research:
36+ - <Research Task 1>
37+ next_steps:
38+ - <Next Step 1>
39+ todo:
40+ - <To-do 1>
41+```
42+
43+3. **Iterative Updates**: Update the file continuously during or immediately after the meeting as new information becomes available.
44+
45+## Best Practices
46+* **Be Concise**: Use clear and brief descriptions.
47+* **Be Specific**: Include names, dates, and specific details whenever possible.
48+* **Maintain Structure**: Keep the YAML hierarchy consistent to make it easy to read and parse.
49+* **Capture Context**: For questions or remarks, include enough context so that someone reading the notes later can understand the significance.
new file mode 100644
@@ -0,0 +1,49 @@
1+# Meeting Note Taking Skill
2+
3+This skill describes the process of documenting a meeting in a structured YAML format.
4+
5+## Objective
6+To capture and organize information from a meeting to ensure all key points, decisions, questions, and tasks are recorded and actionable.
7+
8+## Process
9+
10+1. **Identify Key Information**: During the meeting, listen for and note down:
11+ * **Key Points (`key_points`)**: Main topics discussed, decisions made, or important information shared.
12+ * **Questions Asked (`questions_asked`)**: Questions raised by participants, including who asked them and any context or answers provided.
13+ * **Remarks (`remarks`)**: Observations, constraints, or side notes that are relevant but don't fit into other categories.
14+ * **Research Tasks (`to_research`)**: Things that need further investigation or clarification.
15+ * **Next Steps (`next_steps`)**: Planned future actions or upcoming milestones (e.g., RFP dates).
16+ * **To-Do Items (`todo`)**: Immediate tasks for the team or individuals.
17+
18+2. **Structure in YAML**: Use a structured YAML file to organize these notes. A recommended structure is:
19+
20+```yaml
21+meeting:
22+ client: <Client Name>
23+ subject: <Meeting Subject>
24+ key_points:
25+ <category>:
26+ <sub-category>:
27+ <property>: <description>
28+ questions_asked:
29+ - author: <Name>
30+ subject: <Subject>
31+ notes: <Details>
32+ remarks:
33+ - <Remark 1>
34+ - <Remark 2>
35+ to_research:
36+ - <Research Task 1>
37+ next_steps:
38+ - <Next Step 1>
39+ todo:
40+ - <To-do 1>
41+```
42+
43+3. **Iterative Updates**: Update the file continuously during or immediately after the meeting as new information becomes available.
44+
45+## Best Practices
46+* **Be Concise**: Use clear and brief descriptions.
47+* **Be Specific**: Include names, dates, and specific details whenever possible.
48+* **Maintain Structure**: Keep the YAML hierarchy consistent to make it easy to read and parse.
49+* **Capture Context**: For questions or remarks, include enough context so that someone reading the notes later can understand the significance.
added demos/notes-taker/.mm/skills/report_generator/SKILL.md +71 -0
new file mode 100644
@@ -0,0 +1,71 @@
1+# Report Generation Skill
2+
3+This skill describes the process of transforming structured meeting notes from a YAML file into a well-formatted, professional Markdown report.
4+
5+## Objective
6+To convert raw, structured data into a readable, aesthetically pleasing, and organized document suitable for sharing with stakeholders.
7+
8+## Process
9+
10+1. **Analyze the Source YAML**: Read the `meeting_*.yaml` file and understand its hierarchy:
11+ * `client`, `subject` (Metadata)
12+ * `key_points` (Key features/points)
13+ * `questions_asked` (Q&A session)
14+ * `remarks` (Observations/Constraints)
15+ * `to_research` (Research items)
16+ * `next_steps` (Next steps/Timeline)
17+ * `todo` (Action items)
18+
19+2. **Define the Markdown Structure**: Use Markdown elements to create visual hierarchy:
20+ * `#` for the main title (e.g., `# Meeting report: [Subject]`)
21+ * `##` for major sections (e.g., `## Key Points`, `## Questions & Answers`)
22+ * `###` for sub-sections if necessary.
23+ * `**Bold**` for emphasis (names, dates, key terms).
24+ * `*` or `-` for bulleted lists.
25+ * `|` for tables (useful for `questions_asked` or `key_points` if they are highly structured).
26+ * `> ` for blockquotes (useful for important remarks or warnings).
27+
28+3. **Mapping Logic**:
29+ * **Header**: Title + Client + Date (if available).
30+ * **Executive Summary / Key Points**: Use nested lists or tables to present `key_points`.
31+ * **Discussion Details**: Present `questions_asked` as a list or a table with columns: **Author**, **Subject**, and **Notes**.
32+ * **Observations**: Use a bulleted list for `remarks`.
33+ * **Action Plan**: Group `to_research`, `next_steps`, and `todo` into a clear "Actions & Next Steps" section. Use checkboxes `- [ ]` for `todo` to make them look like a real task list.
34+
35+4. **Refinement**:
36+ * Ensure consistent indentation.
37+ * Check for spelling and grammar.
38+ * Add a "Generated by 🐱 Bob" footer.
39+
40+## Example Template
41+
42+```markdown
43+# Meeting report: [Subject]
44+**Client:** [Client]
45+
46+## 📌 Key Points
47+[Content from key_points]
48+
49+## 💬 Questions & Answers
50+| Author | Subject | Notes |
51+| :--- | :--- | :--- |
52+| [Name] | [Subject] | [Notes] |
53+
54+## 📝 Remarks & Observations
55+* [Remark 1]
56+* [Remark 2]
57+
58+## 🚀 Actions & Next Steps
59+### To research
60+* [Research item]
61+
62+### Next steps
63+* [Next step]
64+
65+### ✅ To do
66+- [ ] [Task 1]
67+- [ ] [Task 2]
68+
69+---
70+*Generated by 🐱 Bob*
71+```
new file mode 100644
@@ -0,0 +1,71 @@
1+# Report Generation Skill
2+
3+This skill describes the process of transforming structured meeting notes from a YAML file into a well-formatted, professional Markdown report.
4+
5+## Objective
6+To convert raw, structured data into a readable, aesthetically pleasing, and organized document suitable for sharing with stakeholders.
7+
8+## Process
9+
10+1. **Analyze the Source YAML**: Read the `meeting_*.yaml` file and understand its hierarchy:
11+ * `client`, `subject` (Metadata)
12+ * `key_points` (Key features/points)
13+ * `questions_asked` (Q&A session)
14+ * `remarks` (Observations/Constraints)
15+ * `to_research` (Research items)
16+ * `next_steps` (Next steps/Timeline)
17+ * `todo` (Action items)
18+
19+2. **Define the Markdown Structure**: Use Markdown elements to create visual hierarchy:
20+ * `#` for the main title (e.g., `# Meeting report: [Subject]`)
21+ * `##` for major sections (e.g., `## Key Points`, `## Questions & Answers`)
22+ * `###` for sub-sections if necessary.
23+ * `**Bold**` for emphasis (names, dates, key terms).
24+ * `*` or `-` for bulleted lists.
25+ * `|` for tables (useful for `questions_asked` or `key_points` if they are highly structured).
26+ * `> ` for blockquotes (useful for important remarks or warnings).
27+
28+3. **Mapping Logic**:
29+ * **Header**: Title + Client + Date (if available).
30+ * **Executive Summary / Key Points**: Use nested lists or tables to present `key_points`.
31+ * **Discussion Details**: Present `questions_asked` as a list or a table with columns: **Author**, **Subject**, and **Notes**.
32+ * **Observations**: Use a bulleted list for `remarks`.
33+ * **Action Plan**: Group `to_research`, `next_steps`, and `todo` into a clear "Actions & Next Steps" section. Use checkboxes `- [ ]` for `todo` to make them look like a real task list.
34+
35+4. **Refinement**:
36+ * Ensure consistent indentation.
37+ * Check for spelling and grammar.
38+ * Add a "Generated by 🐱 Bob" footer.
39+
40+## Example Template
41+
42+```markdown
43+# Meeting report: [Subject]
44+**Client:** [Client]
45+
46+## 📌 Key Points
47+[Content from key_points]
48+
49+## 💬 Questions & Answers
50+| Author | Subject | Notes |
51+| :--- | :--- | :--- |
52+| [Name] | [Subject] | [Notes] |
53+
54+## 📝 Remarks & Observations
55+* [Remark 1]
56+* [Remark 2]
57+
58+## 🚀 Actions & Next Steps
59+### To research
60+* [Research item]
61+
62+### Next steps
63+* [Next step]
64+
65+### ✅ To do
66+- [ ] [Task 1]
67+- [ ] [Task 2]
68+
69+---
70+*Generated by 🐱 Bob*
71+```
added demos/notes-taker/HANDOFF.md +34 -0
new file mode 100644
@@ -0,0 +1,34 @@
1+# Handoff — notes-taker (Bob), 2026-12-03
2+
3+Where the work stopped, for whoever continues on this agent. The project-wide record is in `.memory/` at the repository root (`handoffs/2026-12-03-notes-taker-prompt.md`); this file is the one that travels with the demo.
4+
5+## State
6+
7+- Bob is an `mm` agent that takes meeting notes in `meeting_<client>.yaml` and builds `report_<client>.md` on request. Model `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M`, reasoning on, config in `.mm/agent.yaml`.
8+- **The system prompt was rewritten** (405 words) after reading the three real sessions in `.mm/sessions/` (made with the old generic coding-agent prompt). The faults seen and the rule answering each are in the READMEs.
9+- **Done today**: prompt rewritten; `lsp:` block (gopls) removed; YAML keys now English in both skills and in the prompt (`meeting`, `subject`, `key_points`, `questions_asked`, `author`, `remarks`, `to_research`, `next_steps`, `todo`); report template fully English; `README.en.md` and `README.fr.md` written.
10+- The config loads (checked with `config.Load` in a throwaway test, removed afterwards).
11+
12+## Not done
13+
14+- **Bob has never been run with the new prompt or the English keys.** Nothing here is measured. The READMEs say so; the example session in them is an illustration, not a recording.
15+- The user's older notes file `reunion_nanoco.yaml` (on their Mac, `~/Documents/bob-agent/`, not reachable from the sandbox) has the old French keys. The user chose to delete it; I could not (see below).
16+
17+## Next steps
18+
19+1. Run a short real session (`cd demos/notes-taker && mm`) with fragments in French and check, in this order:
20+ - the reply is in the language of the user's message, one line, no section re-printed;
21+ - the facts land in the right key (a licence remark → `remarks`, not a feature description);
22+ - `edit_file` is used after the first read, never `write_file` on the existing file;
23+ - "hier" / "vendredi" become correct `YYYY-MM-DD` dates;
24+ - `$report_generator` writes `report_<client>.md` from the YAML only.
25+2. Put the real run in the READMEs in place of the illustration, and update their "Limits" section.
26+3. If dates are wrong: remove rule 5 of the prompt (or give Bob a `date` recipe) rather than making the prompt longer — the window is 4096 tokens native and every word counts.
27+
28+## Traps
29+
30+- Edit the sections in **two** places and keep them identical: the YAML example in `.mm/skills/note_taking/SKILL.md` and the one-line definitions in the prompt (rule 3).
31+- The skills are read from the directory `mm` starts in: always start it from this folder.
32+- `yolo: true` — tools run without asking. `workspace.confine` is what limits the reach; do not remove it.
33+- The sandbox has no PyYAML. To check that `agent.yaml` still loads, write a throwaway test in `internal/config` calling `Load("../../demos/notes-taker/.mm/agent.yaml")`, run it, and delete it.
34+- Not deleted: `~/Documents/bob-agent/reunion_nanoco.yaml` and `compte_rendu_nanoco.md` (outside the sandbox; the user removes them with `rm`).
new file mode 100644
@@ -0,0 +1,34 @@
1+# Handoff — notes-taker (Bob), 2026-12-03
2+
3+Where the work stopped, for whoever continues on this agent. The project-wide record is in `.memory/` at the repository root (`handoffs/2026-12-03-notes-taker-prompt.md`); this file is the one that travels with the demo.
4+
5+## State
6+
7+- Bob is an `mm` agent that takes meeting notes in `meeting_<client>.yaml` and builds `report_<client>.md` on request. Model `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M`, reasoning on, config in `.mm/agent.yaml`.
8+- **The system prompt was rewritten** (405 words) after reading the three real sessions in `.mm/sessions/` (made with the old generic coding-agent prompt). The faults seen and the rule answering each are in the READMEs.
9+- **Done today**: prompt rewritten; `lsp:` block (gopls) removed; YAML keys now English in both skills and in the prompt (`meeting`, `subject`, `key_points`, `questions_asked`, `author`, `remarks`, `to_research`, `next_steps`, `todo`); report template fully English; `README.en.md` and `README.fr.md` written.
10+- The config loads (checked with `config.Load` in a throwaway test, removed afterwards).
11+
12+## Not done
13+
14+- **Bob has never been run with the new prompt or the English keys.** Nothing here is measured. The READMEs say so; the example session in them is an illustration, not a recording.
15+- The user's older notes file `reunion_nanoco.yaml` (on their Mac, `~/Documents/bob-agent/`, not reachable from the sandbox) has the old French keys. The user chose to delete it; I could not (see below).
16+
17+## Next steps
18+
19+1. Run a short real session (`cd demos/notes-taker && mm`) with fragments in French and check, in this order:
20+ - the reply is in the language of the user's message, one line, no section re-printed;
21+ - the facts land in the right key (a licence remark → `remarks`, not a feature description);
22+ - `edit_file` is used after the first read, never `write_file` on the existing file;
23+ - "hier" / "vendredi" become correct `YYYY-MM-DD` dates;
24+ - `$report_generator` writes `report_<client>.md` from the YAML only.
25+2. Put the real run in the READMEs in place of the illustration, and update their "Limits" section.
26+3. If dates are wrong: remove rule 5 of the prompt (or give Bob a `date` recipe) rather than making the prompt longer — the window is 4096 tokens native and every word counts.
27+
28+## Traps
29+
30+- Edit the sections in **two** places and keep them identical: the YAML example in `.mm/skills/note_taking/SKILL.md` and the one-line definitions in the prompt (rule 3).
31+- The skills are read from the directory `mm` starts in: always start it from this folder.
32+- `yolo: true` — tools run without asking. `workspace.confine` is what limits the reach; do not remove it.
33+- The sandbox has no PyYAML. To check that `agent.yaml` still loads, write a throwaway test in `internal/config` calling `Load("../../demos/notes-taker/.mm/agent.yaml")`, run it, and delete it.
34+- Not deleted: `~/Documents/bob-agent/reunion_nanoco.yaml` and `compte_rendu_nanoco.md` (outside the sandbox; the user removes them with `rm`).
added demos/notes-taker/README.en.md +130 -0
new file mode 100644
@@ -0,0 +1,130 @@
1+# Bob the note-taker: meeting notes with a 4B model that never leaves your laptop
2+
3+*[Version française](README.fr.md)*
4+
5+You are in a meeting. Someone says the RFP launches in January, someone else asks about air-gapped mode, and you promised to look into token costs. You type three short lines, you do not even finish your sentences, and when the meeting ends the notes are already sorted, in a file, ready to turn into a report.
6+
7+That is what this demo does. **Bob** is an `mm` agent that takes meeting notes in a YAML file and, on request, turns them into a Markdown report. It runs on a **small local model** (Gemma 4 E4B, about 4 billion parameters) through llama.cpp: nothing is sent to a cloud, which matters when the notes are about a client.
8+
9+| | |
10+|---|---|
11+| Model | `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M`, reasoning on |
12+| Server | llama.cpp, started by `mm` itself (`autoStart`) and stopped when `mm` exits |
13+| Tools | `bash`, `read_file` / `write_file` / `edit_file`, `read_skill`, `ask_user` — no plan tool, no LSP |
14+| Skills | `note_taking` (the YAML structure), `report_generator` (the Markdown report) |
15+| Notes file | one YAML file per meeting, `meeting_<client>.yaml`, in the folder you start from |
16+
17+## Why this is a good job for a small model
18+
19+Small models are bad at long chains: write five files that import each other, keep a plan in mind, recover from a compiler error three steps later. Taking notes is the opposite job.
20+
21+- **Each message is one small action.** *Read a fragment, decide which section it belongs to, add one line.* There is no chain to lose.
22+- **The structure is not in the model's head.** The skill gives the sections once (`key_points`, `questions_asked`, `remarks`, `to_research`, `next_steps`, `todo`); the model only has to choose among six names.
23+- **The file is the memory.** Bob does not have to remember the meeting: the YAML does. After a context compaction, he reads the file again and carries on.
24+- **Small edits instead of rewrites.** Asked to rewrite a 60-line file, a small model drops or garbles lines. Bob uses `edit_file` with a few lines at a time, and the tool shows the changed lines so he can check them.
25+- **The report cannot invent anything.** It is generated from the YAML only, so a wrong sentence in the report means a wrong line in the notes, which you can see and fix.
26+- **Short answers save the window.** A one-line confirmation per note costs a few dozen tokens. Re-printing the section after each note, which Bob did at first, fills a small window quickly.
27+- **It stays private.** Meeting notes are exactly the kind of text you do not want to paste into a hosted service.
28+
29+## Prerequisites
30+
31+- `mm` and `llama-server` (llama.cpp) installed.
32+- Nothing else: with `autoStart: true`, `mm` starts `llama-server` and downloads the model on the first run.
33+
34+## Run
35+
36+```bash
37+cd demos/notes-taker
38+mm # or: mm tui
39+```
40+
41+`mm` finds `.mm/agent.yaml` in the folder it starts from. The notes file and the report are created in that same folder.
42+
43+## A session
44+
45+Type the way you would take notes. The replies below show what the prompt asks Bob to do (illustration, not a recording):
46+
47+```text
48+> Meeting with Acme about the sandbox offer. Alice and Bruno are there.
49+Created meeting_acme.yaml (client: Acme, subject: sandbox offer).
50+
51+> the RFP will be launched in January, answer expected in Q1
52+Added to next_steps.
53+
54+> decision takes about 3 weeks
55+Added to next_steps (RFP item).
56+
57+> they have Office 365 licences, fixed price, so tokens are not a concern for now
58+Added to remarks.
59+
60+> Bruno asks if the sandbox works fully air-gapped
61+Added to questions_asked (author: Bruno). The answer is not noted yet.
62+
63+> the kickoff was yesterday
64+Added to next_steps: kickoff 2026-12-02 (computed from today, 2026-12-03).
65+
66+> $report_generator
67+Wrote report_acme.md.
68+```
69+
70+The YAML behind it follows the `note_taking` skill:
71+
72+```yaml
73+meeting:
74+ client: Acme
75+ subject: Sandbox offer
76+ questions_asked:
77+ - author: Bruno
78+ subject: Air-gapped mode
79+ notes: Does the sandbox work fully air-gapped? (no answer yet)
80+ remarks:
81+ - Office 365 licences, fixed price: tokens are not a concern for now
82+ next_steps:
83+ - RFP launched in January, answer expected in Q1, decision in about 3 weeks (kickoff 2026-12-02)
84+```
85+
86+You can also correct Bob in plain words ("no, that was Alice, not Bruno") and he replaces the line instead of adding a second one.
87+
88+## What the system prompt does
89+
90+The prompt is about 400 words, short on purpose: the model's native window is 4096 tokens, and the tool descriptions and the skills come on top. It was rewritten after reading three real sessions where a generic coding-agent prompt was used for note-taking. Each rule answers something that was seen:
91+
92+| Seen in the sessions | Rule in the prompt |
93+|---|---|
94+| The prompt named a plan tool that was switched off | No plan tool mentioned |
95+| One answer came out in English to a French user | Reply in the language of the user's last message |
96+| After each note, the whole section was printed again, plus "ready for the next one" | One short line: what was added, under which key |
97+| "The kickoff was yesterday" was written as "yesterday" | Relative dates become `YYYY-MM-DD`, computed from `{{date}}` |
98+| A remark about licences ended up in a feature's `description` | Each section has a one-line definition; a doubt goes to `remarks`, said out loud |
99+| Skills had to be explained by the user (one folder per skill) | The convention is written in the prompt |
100+| Risk with any small model: rewriting the whole file | Read once, then `edit_file` only |
101+
102+## Notable settings (`.mm/agent.yaml`)
103+
104+| Setting | Value | Why |
105+|---|---|---|
106+| `sampling.temperature` | `0.2` | Filing a fact is not creative work |
107+| `sampling.chat_template_kwargs.enable_thinking` | `true` | The model thinks before choosing a section |
108+| `sampling.parallel_tool_calls` | `false` | One tool call per reply: a check must not run before the change it checks |
109+| `context.enabled` / `threshold` | `true` / `75` | The history is compacted before the window is full; the file keeps the facts anyway |
110+| `workspace.confine` / `repairPaths` | `true` | Bob stays in the notes folder; `/meeting_x.yaml` is repaired to `meeting_x.yaml` |
111+| `bashTimeout` | `60s` | A stuck command does not freeze a live meeting |
112+| `maxTurns` | `40` | Plenty for one note |
113+| `yolo` | `true` | Tools run without asking: it is a notes folder, and `confine` limits the reach |
114+| `planTool` | `false` | One note, one action: there is nothing to plan |
115+
116+## Make it yours
117+
118+- **Change the sections**: edit `.mm/skills/note_taking/SKILL.md` (the YAML example) and the one-line definitions in the prompt, so both say the same thing. Add a `decisions` section, drop `to_research`, rename keys.
119+- **Change the report**: edit the Markdown template at the end of `.mm/skills/report_generator/SKILL.md`.
120+- **Change the model**: change `model` and redo `sampling` with it (running `mm init` again is the quick way). A larger model will follow the rules more reliably; the prompt still applies.
121+- **Ask Bob for a new skill**: *"in .mm/skills, create a skill that explains how we do X"*. A skill is a folder: `.mm/skills/<name>/SKILL.md`.
122+
123+## Limits
124+
125+- **Not measured.** Unlike other demos of this repository, this agent has no measured series of runs. The prompt was improved after reading three real sessions; it has not been re-run with the model since.
126+- **Dates.** Computing "next Friday" is arithmetic, and small models make mistakes. If the result is wrong, check it. If it keeps failing, drop rule 5 of the prompt and write dates yourself.
127+- **Filing is a judgement.** Bob can put a fact in the wrong section. Because every change is one visible line, it is quick to spot and to correct.
128+- **One meeting per file**, and the folder is assumed to hold one active file; with several, Bob asks which one.
129+- **Existing notes with other keys** (for example an older file with French keys) are not migrated. Rename the keys by hand, or ask Bob to do it before the meeting.
130+- **Reports are English.** The report template is in English; the content follows the language of the notes.
new file mode 100644
@@ -0,0 +1,130 @@
1+# Bob the note-taker: meeting notes with a 4B model that never leaves your laptop
2+
3+*[Version française](README.fr.md)*
4+
5+You are in a meeting. Someone says the RFP launches in January, someone else asks about air-gapped mode, and you promised to look into token costs. You type three short lines, you do not even finish your sentences, and when the meeting ends the notes are already sorted, in a file, ready to turn into a report.
6+
7+That is what this demo does. **Bob** is an `mm` agent that takes meeting notes in a YAML file and, on request, turns them into a Markdown report. It runs on a **small local model** (Gemma 4 E4B, about 4 billion parameters) through llama.cpp: nothing is sent to a cloud, which matters when the notes are about a client.
8+
9+| | |
10+|---|---|
11+| Model | `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M`, reasoning on |
12+| Server | llama.cpp, started by `mm` itself (`autoStart`) and stopped when `mm` exits |
13+| Tools | `bash`, `read_file` / `write_file` / `edit_file`, `read_skill`, `ask_user` — no plan tool, no LSP |
14+| Skills | `note_taking` (the YAML structure), `report_generator` (the Markdown report) |
15+| Notes file | one YAML file per meeting, `meeting_<client>.yaml`, in the folder you start from |
16+
17+## Why this is a good job for a small model
18+
19+Small models are bad at long chains: write five files that import each other, keep a plan in mind, recover from a compiler error three steps later. Taking notes is the opposite job.
20+
21+- **Each message is one small action.** *Read a fragment, decide which section it belongs to, add one line.* There is no chain to lose.
22+- **The structure is not in the model's head.** The skill gives the sections once (`key_points`, `questions_asked`, `remarks`, `to_research`, `next_steps`, `todo`); the model only has to choose among six names.
23+- **The file is the memory.** Bob does not have to remember the meeting: the YAML does. After a context compaction, he reads the file again and carries on.
24+- **Small edits instead of rewrites.** Asked to rewrite a 60-line file, a small model drops or garbles lines. Bob uses `edit_file` with a few lines at a time, and the tool shows the changed lines so he can check them.
25+- **The report cannot invent anything.** It is generated from the YAML only, so a wrong sentence in the report means a wrong line in the notes, which you can see and fix.
26+- **Short answers save the window.** A one-line confirmation per note costs a few dozen tokens. Re-printing the section after each note, which Bob did at first, fills a small window quickly.
27+- **It stays private.** Meeting notes are exactly the kind of text you do not want to paste into a hosted service.
28+
29+## Prerequisites
30+
31+- `mm` and `llama-server` (llama.cpp) installed.
32+- Nothing else: with `autoStart: true`, `mm` starts `llama-server` and downloads the model on the first run.
33+
34+## Run
35+
36+```bash
37+cd demos/notes-taker
38+mm # or: mm tui
39+```
40+
41+`mm` finds `.mm/agent.yaml` in the folder it starts from. The notes file and the report are created in that same folder.
42+
43+## A session
44+
45+Type the way you would take notes. The replies below show what the prompt asks Bob to do (illustration, not a recording):
46+
47+```text
48+> Meeting with Acme about the sandbox offer. Alice and Bruno are there.
49+Created meeting_acme.yaml (client: Acme, subject: sandbox offer).
50+
51+> the RFP will be launched in January, answer expected in Q1
52+Added to next_steps.
53+
54+> decision takes about 3 weeks
55+Added to next_steps (RFP item).
56+
57+> they have Office 365 licences, fixed price, so tokens are not a concern for now
58+Added to remarks.
59+
60+> Bruno asks if the sandbox works fully air-gapped
61+Added to questions_asked (author: Bruno). The answer is not noted yet.
62+
63+> the kickoff was yesterday
64+Added to next_steps: kickoff 2026-12-02 (computed from today, 2026-12-03).
65+
66+> $report_generator
67+Wrote report_acme.md.
68+```
69+
70+The YAML behind it follows the `note_taking` skill:
71+
72+```yaml
73+meeting:
74+ client: Acme
75+ subject: Sandbox offer
76+ questions_asked:
77+ - author: Bruno
78+ subject: Air-gapped mode
79+ notes: Does the sandbox work fully air-gapped? (no answer yet)
80+ remarks:
81+ - Office 365 licences, fixed price: tokens are not a concern for now
82+ next_steps:
83+ - RFP launched in January, answer expected in Q1, decision in about 3 weeks (kickoff 2026-12-02)
84+```
85+
86+You can also correct Bob in plain words ("no, that was Alice, not Bruno") and he replaces the line instead of adding a second one.
87+
88+## What the system prompt does
89+
90+The prompt is about 400 words, short on purpose: the model's native window is 4096 tokens, and the tool descriptions and the skills come on top. It was rewritten after reading three real sessions where a generic coding-agent prompt was used for note-taking. Each rule answers something that was seen:
91+
92+| Seen in the sessions | Rule in the prompt |
93+|---|---|
94+| The prompt named a plan tool that was switched off | No plan tool mentioned |
95+| One answer came out in English to a French user | Reply in the language of the user's last message |
96+| After each note, the whole section was printed again, plus "ready for the next one" | One short line: what was added, under which key |
97+| "The kickoff was yesterday" was written as "yesterday" | Relative dates become `YYYY-MM-DD`, computed from `{{date}}` |
98+| A remark about licences ended up in a feature's `description` | Each section has a one-line definition; a doubt goes to `remarks`, said out loud |
99+| Skills had to be explained by the user (one folder per skill) | The convention is written in the prompt |
100+| Risk with any small model: rewriting the whole file | Read once, then `edit_file` only |
101+
102+## Notable settings (`.mm/agent.yaml`)
103+
104+| Setting | Value | Why |
105+|---|---|---|
106+| `sampling.temperature` | `0.2` | Filing a fact is not creative work |
107+| `sampling.chat_template_kwargs.enable_thinking` | `true` | The model thinks before choosing a section |
108+| `sampling.parallel_tool_calls` | `false` | One tool call per reply: a check must not run before the change it checks |
109+| `context.enabled` / `threshold` | `true` / `75` | The history is compacted before the window is full; the file keeps the facts anyway |
110+| `workspace.confine` / `repairPaths` | `true` | Bob stays in the notes folder; `/meeting_x.yaml` is repaired to `meeting_x.yaml` |
111+| `bashTimeout` | `60s` | A stuck command does not freeze a live meeting |
112+| `maxTurns` | `40` | Plenty for one note |
113+| `yolo` | `true` | Tools run without asking: it is a notes folder, and `confine` limits the reach |
114+| `planTool` | `false` | One note, one action: there is nothing to plan |
115+
116+## Make it yours
117+
118+- **Change the sections**: edit `.mm/skills/note_taking/SKILL.md` (the YAML example) and the one-line definitions in the prompt, so both say the same thing. Add a `decisions` section, drop `to_research`, rename keys.
119+- **Change the report**: edit the Markdown template at the end of `.mm/skills/report_generator/SKILL.md`.
120+- **Change the model**: change `model` and redo `sampling` with it (running `mm init` again is the quick way). A larger model will follow the rules more reliably; the prompt still applies.
121+- **Ask Bob for a new skill**: *"in .mm/skills, create a skill that explains how we do X"*. A skill is a folder: `.mm/skills/<name>/SKILL.md`.
122+
123+## Limits
124+
125+- **Not measured.** Unlike other demos of this repository, this agent has no measured series of runs. The prompt was improved after reading three real sessions; it has not been re-run with the model since.
126+- **Dates.** Computing "next Friday" is arithmetic, and small models make mistakes. If the result is wrong, check it. If it keeps failing, drop rule 5 of the prompt and write dates yourself.
127+- **Filing is a judgement.** Bob can put a fact in the wrong section. Because every change is one visible line, it is quick to spot and to correct.
128+- **One meeting per file**, and the folder is assumed to hold one active file; with several, Bob asks which one.
129+- **Existing notes with other keys** (for example an older file with French keys) are not migrated. Rename the keys by hand, or ask Bob to do it before the meeting.
130+- **Reports are English.** The report template is in English; the content follows the language of the notes.
added demos/notes-taker/README.fr.md +130 -0
new file mode 100644
@@ -0,0 +1,130 @@
1+# Bob, le preneur de notes : des comptes-rendus de réunion avec un modèle de 4B qui ne quitte pas votre portable
2+
3+*[English version](README.en.md)*
4+
5+Vous êtes en réunion. Quelqu'un annonce que le RFP sera lancé en janvier, un autre demande si le mode air-gap est possible, et vous avez promis de regarder les coûts en tokens. Vous tapez trois lignes courtes, sans même finir vos phrases, et à la fin de la réunion les notes sont déjà rangées, dans un fichier, prêtes à devenir un compte-rendu.
6+
7+C'est ce que fait cette démo. **Bob** est un agent `mm` qui prend des notes de réunion dans un fichier YAML et, à la demande, en tire un rapport Markdown. Il tourne sur un **petit modèle local** (Gemma 4 E4B, environ 4 milliards de paramètres) via llama.cpp : rien n'est envoyé dans un cloud, ce qui compte quand les notes parlent d'un client.
8+
9+| | |
10+|---|---|
11+| Modèle | `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M`, raisonnement activé |
12+| Serveur | llama.cpp, lancé par `mm` lui-même (`autoStart`) et arrêté quand `mm` se termine |
13+| Outils | `bash`, `read_file` / `write_file` / `edit_file`, `read_skill`, `ask_user` — pas d'outil de plan, pas de LSP |
14+| Skills | `note_taking` (la structure YAML), `report_generator` (le rapport Markdown) |
15+| Fichier de notes | un fichier YAML par réunion, `meeting_<client>.yaml`, dans le dossier de lancement |
16+
17+## Pourquoi c'est un bon travail pour un petit modèle
18+
19+Les petits modèles sont mauvais sur les longues chaînes : écrire cinq fichiers qui s'importent, garder un plan en tête, se remettre d'une erreur de compilation trois étapes plus tard. Prendre des notes est le travail inverse.
20+
21+- **Chaque message est une petite action.** *Lire un fragment, décider de sa section, ajouter une ligne.* Il n'y a pas de chaîne à perdre.
22+- **La structure n'est pas dans la tête du modèle.** La skill donne les sections une fois pour toutes (`key_points`, `questions_asked`, `remarks`, `to_research`, `next_steps`, `todo`) ; le modèle n'a qu'à choisir parmi six noms.
23+- **Le fichier est la mémoire.** Bob n'a pas à se souvenir de la réunion : le YAML s'en charge. Après une compaction du contexte, il relit le fichier et continue.
24+- **De petites modifications plutôt que des réécritures.** À qui demande de réécrire un fichier de 60 lignes, un petit modèle perd ou déforme des lignes. Bob utilise `edit_file` quelques lignes à la fois, et l'outil montre les lignes modifiées pour qu'il les vérifie.
25+- **Le rapport ne peut rien inventer.** Il est généré à partir du YAML seul : une phrase fausse dans le rapport, c'est une ligne fausse dans les notes, que vous voyez et corrigez.
26+- **Des réponses courtes ménagent la fenêtre.** Une confirmation d'une ligne par note coûte quelques dizaines de tokens. Réafficher la section après chaque note, ce que Bob faisait au début, remplit vite une petite fenêtre.
27+- **Ça reste privé.** Des notes de réunion sont exactement le genre de texte qu'on ne veut pas coller dans un service hébergé.
28+
29+## Prérequis
30+
31+- `mm` et `llama-server` (llama.cpp) installés.
32+- Rien d'autre : avec `autoStart: true`, `mm` démarre `llama-server` et télécharge le modèle au premier lancement.
33+
34+## Lancer
35+
36+```bash
37+cd demos/notes-taker
38+mm # ou : mm tui
39+```
40+
41+`mm` trouve `.mm/agent.yaml` dans le dossier d'où il est lancé. Le fichier de notes et le rapport sont créés dans ce même dossier.
42+
43+## Une session
44+
45+Tapez comme vous prendriez des notes. Les réponses ci-dessous montrent ce que le prompt demande à Bob (illustration, pas un enregistrement) :
46+
47+```text
48+> Réunion avec Acme sur l'offre sandbox. Alice et Bruno sont là.
49+Créé meeting_acme.yaml (client: Acme, subject: offre sandbox).
50+
51+> le RFP sera lancé en janvier, réponse en Q1
52+Ajouté dans next_steps.
53+
54+> la durée de décision est de l'ordre de 3 semaines
55+Ajouté dans next_steps (élément RFP).
56+
57+> ils ont des licences Office 365, prix fixe, donc pas de souci de tokens pour le moment
58+Ajouté dans remarks.
59+
60+> Bruno demande si la sandbox marche en air-gap complet
61+Ajouté dans questions_asked (author: Bruno). La réponse n'est pas encore notée.
62+
63+> le kickoff était hier
64+Ajouté dans next_steps : kickoff 2026-12-02 (calculé depuis aujourd'hui, 2026-12-03).
65+
66+> $report_generator
67+Écrit report_acme.md.
68+```
69+
70+Le YAML derrière suit la skill `note_taking` :
71+
72+```yaml
73+meeting:
74+ client: Acme
75+ subject: Offre sandbox
76+ questions_asked:
77+ - author: Bruno
78+ subject: Mode air-gap
79+ notes: La sandbox fonctionne-t-elle en air-gap complet ? (pas encore de réponse)
80+ remarks:
81+ - Licences Office 365, prix fixe : pas de souci de tokens pour le moment
82+ next_steps:
83+ - RFP lancé en janvier, réponse en Q1, décision en environ 3 semaines (kickoff 2026-12-02)
84+```
85+
86+Vous pouvez aussi corriger Bob avec des mots simples (« non, c'était Alice, pas Bruno ») : il remplace la ligne au lieu d'en ajouter une seconde.
87+
88+## Ce que fait le prompt système
89+
90+Le prompt fait environ 400 mots, court volontairement : la fenêtre native du modèle est de 4096 tokens, et les descriptions d'outils et les skills s'y ajoutent. Il a été réécrit après lecture de trois sessions réelles où un prompt générique d'agent de code servait à prendre des notes. Chaque règle répond à quelque chose qui a été vu :
91+
92+| Vu dans les sessions | Règle dans le prompt |
93+|---|---|
94+| Le prompt citait un outil de plan désactivé | Plus aucune mention d'un outil de plan |
95+| Une réponse est sortie en anglais pour un utilisateur français | Répondre dans la langue du dernier message |
96+| Après chaque note, la section entière était réaffichée, plus « prêt pour la suite » | Une seule ligne : ce qui est ajouté, sous quelle clé |
97+| « Le kickoff était hier » était écrit « hier » | Une date relative devient `AAAA-MM-JJ`, calculée depuis `{{date}}` |
98+| Une remarque sur des licences a fini dans la `description` d'une fonctionnalité | Chaque section a une définition d'une ligne ; un doute va dans `remarks`, dit à voix haute |
99+| L'utilisateur a dû expliquer les skills (un dossier par skill) | La convention est écrite dans le prompt |
100+| Risque de tout petit modèle : réécrire le fichier entier | Lire une fois, puis `edit_file` seulement |
101+
102+## Réglages notables (`.mm/agent.yaml`)
103+
104+| Réglage | Valeur | Pourquoi |
105+|---|---|---|
106+| `sampling.temperature` | `0.2` | Ranger un fait n'est pas un travail créatif |
107+| `sampling.chat_template_kwargs.enable_thinking` | `true` | Le modèle réfléchit avant de choisir une section |
108+| `sampling.parallel_tool_calls` | `false` | Un appel d'outil par réponse : une vérification ne doit pas passer avant le changement qu'elle vérifie |
109+| `context.enabled` / `threshold` | `true` / `75` | L'historique est compacté avant que la fenêtre soit pleine ; le fichier garde les faits de toute façon |
110+| `workspace.confine` / `repairPaths` | `true` | Bob reste dans le dossier de notes ; `/meeting_x.yaml` est réparé en `meeting_x.yaml` |
111+| `bashTimeout` | `60s` | Une commande bloquée ne fige pas une réunion en cours |
112+| `maxTurns` | `40` | Largement assez pour une note |
113+| `yolo` | `true` | Les outils s'exécutent sans demander : c'est un dossier de notes, et `confine` limite la portée |
114+| `planTool` | `false` | Une note, une action : rien à planifier |
115+
116+## L'adapter
117+
118+- **Changer les sections** : éditez `.mm/skills/note_taking/SKILL.md` (l'exemple YAML) et les définitions d'une ligne dans le prompt, pour que les deux disent la même chose. Ajoutez une section `decisions`, retirez `to_research`, renommez des clés.
119+- **Changer le rapport** : éditez le gabarit Markdown à la fin de `.mm/skills/report_generator/SKILL.md`.
120+- **Changer de modèle** : changez `model` et refaites `sampling` avec lui (relancer `mm init` est le moyen rapide). Un modèle plus gros suivra les règles plus sûrement ; le prompt reste valable.
121+- **Demander une nouvelle skill à Bob** : *« dans .mm/skills, crée une skill qui explique comment on fait X »*. Une skill est un dossier : `.mm/skills/<nom>/SKILL.md`.
122+
123+## Limites
124+
125+- **Non mesuré.** Contrairement à d'autres démos de ce dépôt, cet agent n'a pas de série de lancements mesurée. Le prompt a été amélioré après lecture de trois sessions réelles ; il n'a pas été relancé avec le modèle depuis.
126+- **Les dates.** Calculer « vendredi prochain » est de l'arithmétique, et les petits modèles se trompent. Si le résultat est faux, vérifiez-le. Si cela se répète, retirez la règle 5 du prompt et écrivez les dates vous-même.
127+- **Ranger est un jugement.** Bob peut mettre un fait dans la mauvaise section. Comme chaque changement tient en une ligne visible, c'est vite repéré et corrigé.
128+- **Une réunion par fichier**, et le dossier est supposé contenir un seul fichier actif ; avec plusieurs, Bob demande lequel.
129+- **Des notes existantes avec d'autres clés** (par exemple un ancien fichier aux clés françaises) ne sont pas migrées. Renommez les clés à la main, ou demandez à Bob de le faire avant la réunion.
130+- **Les rapports sont en anglais.** Le gabarit du rapport est en anglais ; le contenu suit la langue des notes.
new file mode 100644
@@ -0,0 +1,130 @@
1+# Bob, le preneur de notes : des comptes-rendus de réunion avec un modèle de 4B qui ne quitte pas votre portable
2+
3+*[English version](README.en.md)*
4+
5+Vous êtes en réunion. Quelqu'un annonce que le RFP sera lancé en janvier, un autre demande si le mode air-gap est possible, et vous avez promis de regarder les coûts en tokens. Vous tapez trois lignes courtes, sans même finir vos phrases, et à la fin de la réunion les notes sont déjà rangées, dans un fichier, prêtes à devenir un compte-rendu.
6+
7+C'est ce que fait cette démo. **Bob** est un agent `mm` qui prend des notes de réunion dans un fichier YAML et, à la demande, en tire un rapport Markdown. Il tourne sur un **petit modèle local** (Gemma 4 E4B, environ 4 milliards de paramètres) via llama.cpp : rien n'est envoyé dans un cloud, ce qui compte quand les notes parlent d'un client.
8+
9+| | |
10+|---|---|
11+| Modèle | `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M`, raisonnement activé |
12+| Serveur | llama.cpp, lancé par `mm` lui-même (`autoStart`) et arrêté quand `mm` se termine |
13+| Outils | `bash`, `read_file` / `write_file` / `edit_file`, `read_skill`, `ask_user` — pas d'outil de plan, pas de LSP |
14+| Skills | `note_taking` (la structure YAML), `report_generator` (le rapport Markdown) |
15+| Fichier de notes | un fichier YAML par réunion, `meeting_<client>.yaml`, dans le dossier de lancement |
16+
17+## Pourquoi c'est un bon travail pour un petit modèle
18+
19+Les petits modèles sont mauvais sur les longues chaînes : écrire cinq fichiers qui s'importent, garder un plan en tête, se remettre d'une erreur de compilation trois étapes plus tard. Prendre des notes est le travail inverse.
20+
21+- **Chaque message est une petite action.** *Lire un fragment, décider de sa section, ajouter une ligne.* Il n'y a pas de chaîne à perdre.
22+- **La structure n'est pas dans la tête du modèle.** La skill donne les sections une fois pour toutes (`key_points`, `questions_asked`, `remarks`, `to_research`, `next_steps`, `todo`) ; le modèle n'a qu'à choisir parmi six noms.
23+- **Le fichier est la mémoire.** Bob n'a pas à se souvenir de la réunion : le YAML s'en charge. Après une compaction du contexte, il relit le fichier et continue.
24+- **De petites modifications plutôt que des réécritures.** À qui demande de réécrire un fichier de 60 lignes, un petit modèle perd ou déforme des lignes. Bob utilise `edit_file` quelques lignes à la fois, et l'outil montre les lignes modifiées pour qu'il les vérifie.
25+- **Le rapport ne peut rien inventer.** Il est généré à partir du YAML seul : une phrase fausse dans le rapport, c'est une ligne fausse dans les notes, que vous voyez et corrigez.
26+- **Des réponses courtes ménagent la fenêtre.** Une confirmation d'une ligne par note coûte quelques dizaines de tokens. Réafficher la section après chaque note, ce que Bob faisait au début, remplit vite une petite fenêtre.
27+- **Ça reste privé.** Des notes de réunion sont exactement le genre de texte qu'on ne veut pas coller dans un service hébergé.
28+
29+## Prérequis
30+
31+- `mm` et `llama-server` (llama.cpp) installés.
32+- Rien d'autre : avec `autoStart: true`, `mm` démarre `llama-server` et télécharge le modèle au premier lancement.
33+
34+## Lancer
35+
36+```bash
37+cd demos/notes-taker
38+mm # ou : mm tui
39+```
40+
41+`mm` trouve `.mm/agent.yaml` dans le dossier d'où il est lancé. Le fichier de notes et le rapport sont créés dans ce même dossier.
42+
43+## Une session
44+
45+Tapez comme vous prendriez des notes. Les réponses ci-dessous montrent ce que le prompt demande à Bob (illustration, pas un enregistrement) :
46+
47+```text
48+> Réunion avec Acme sur l'offre sandbox. Alice et Bruno sont là.
49+Créé meeting_acme.yaml (client: Acme, subject: offre sandbox).
50+
51+> le RFP sera lancé en janvier, réponse en Q1
52+Ajouté dans next_steps.
53+
54+> la durée de décision est de l'ordre de 3 semaines
55+Ajouté dans next_steps (élément RFP).
56+
57+> ils ont des licences Office 365, prix fixe, donc pas de souci de tokens pour le moment
58+Ajouté dans remarks.
59+
60+> Bruno demande si la sandbox marche en air-gap complet
61+Ajouté dans questions_asked (author: Bruno). La réponse n'est pas encore notée.
62+
63+> le kickoff était hier
64+Ajouté dans next_steps : kickoff 2026-12-02 (calculé depuis aujourd'hui, 2026-12-03).
65+
66+> $report_generator
67+Écrit report_acme.md.
68+```
69+
70+Le YAML derrière suit la skill `note_taking` :
71+
72+```yaml
73+meeting:
74+ client: Acme
75+ subject: Offre sandbox
76+ questions_asked:
77+ - author: Bruno
78+ subject: Mode air-gap
79+ notes: La sandbox fonctionne-t-elle en air-gap complet ? (pas encore de réponse)
80+ remarks:
81+ - Licences Office 365, prix fixe : pas de souci de tokens pour le moment
82+ next_steps:
83+ - RFP lancé en janvier, réponse en Q1, décision en environ 3 semaines (kickoff 2026-12-02)
84+```
85+
86+Vous pouvez aussi corriger Bob avec des mots simples (« non, c'était Alice, pas Bruno ») : il remplace la ligne au lieu d'en ajouter une seconde.
87+
88+## Ce que fait le prompt système
89+
90+Le prompt fait environ 400 mots, court volontairement : la fenêtre native du modèle est de 4096 tokens, et les descriptions d'outils et les skills s'y ajoutent. Il a été réécrit après lecture de trois sessions réelles où un prompt générique d'agent de code servait à prendre des notes. Chaque règle répond à quelque chose qui a été vu :
91+
92+| Vu dans les sessions | Règle dans le prompt |
93+|---|---|
94+| Le prompt citait un outil de plan désactivé | Plus aucune mention d'un outil de plan |
95+| Une réponse est sortie en anglais pour un utilisateur français | Répondre dans la langue du dernier message |
96+| Après chaque note, la section entière était réaffichée, plus « prêt pour la suite » | Une seule ligne : ce qui est ajouté, sous quelle clé |
97+| « Le kickoff était hier » était écrit « hier » | Une date relative devient `AAAA-MM-JJ`, calculée depuis `{{date}}` |
98+| Une remarque sur des licences a fini dans la `description` d'une fonctionnalité | Chaque section a une définition d'une ligne ; un doute va dans `remarks`, dit à voix haute |
99+| L'utilisateur a dû expliquer les skills (un dossier par skill) | La convention est écrite dans le prompt |
100+| Risque de tout petit modèle : réécrire le fichier entier | Lire une fois, puis `edit_file` seulement |
101+
102+## Réglages notables (`.mm/agent.yaml`)
103+
104+| Réglage | Valeur | Pourquoi |
105+|---|---|---|
106+| `sampling.temperature` | `0.2` | Ranger un fait n'est pas un travail créatif |
107+| `sampling.chat_template_kwargs.enable_thinking` | `true` | Le modèle réfléchit avant de choisir une section |
108+| `sampling.parallel_tool_calls` | `false` | Un appel d'outil par réponse : une vérification ne doit pas passer avant le changement qu'elle vérifie |
109+| `context.enabled` / `threshold` | `true` / `75` | L'historique est compacté avant que la fenêtre soit pleine ; le fichier garde les faits de toute façon |
110+| `workspace.confine` / `repairPaths` | `true` | Bob reste dans le dossier de notes ; `/meeting_x.yaml` est réparé en `meeting_x.yaml` |
111+| `bashTimeout` | `60s` | Une commande bloquée ne fige pas une réunion en cours |
112+| `maxTurns` | `40` | Largement assez pour une note |
113+| `yolo` | `true` | Les outils s'exécutent sans demander : c'est un dossier de notes, et `confine` limite la portée |
114+| `planTool` | `false` | Une note, une action : rien à planifier |
115+
116+## L'adapter
117+
118+- **Changer les sections** : éditez `.mm/skills/note_taking/SKILL.md` (l'exemple YAML) et les définitions d'une ligne dans le prompt, pour que les deux disent la même chose. Ajoutez une section `decisions`, retirez `to_research`, renommez des clés.
119+- **Changer le rapport** : éditez le gabarit Markdown à la fin de `.mm/skills/report_generator/SKILL.md`.
120+- **Changer de modèle** : changez `model` et refaites `sampling` avec lui (relancer `mm init` est le moyen rapide). Un modèle plus gros suivra les règles plus sûrement ; le prompt reste valable.
121+- **Demander une nouvelle skill à Bob** : *« dans .mm/skills, crée une skill qui explique comment on fait X »*. Une skill est un dossier : `.mm/skills/<nom>/SKILL.md`.
122+
123+## Limites
124+
125+- **Non mesuré.** Contrairement à d'autres démos de ce dépôt, cet agent n'a pas de série de lancements mesurée. Le prompt a été amélioré après lecture de trois sessions réelles ; il n'a pas été relancé avec le modèle depuis.
126+- **Les dates.** Calculer « vendredi prochain » est de l'arithmétique, et les petits modèles se trompent. Si le résultat est faux, vérifiez-le. Si cela se répète, retirez la règle 5 du prompt et écrivez les dates vous-même.
127+- **Ranger est un jugement.** Bob peut mettre un fait dans la mauvaise section. Comme chaque changement tient en une ligne visible, c'est vite repéré et corrigé.
128+- **Une réunion par fichier**, et le dossier est supposé contenir un seul fichier actif ; avec plusieurs, Bob demande lequel.
129+- **Des notes existantes avec d'autres clés** (par exemple un ancien fichier aux clés françaises) ne sont pas migrées. Renommez les clés à la main, ou demandez à Bob de le faire avant la réunion.
130+- **Les rapports sont en anglais.** Le gabarit du rapport est en anglais ; le contenu suit la langue des notes.
modified docs/en/explanation/lsp-tool.md +12 -0
@@ -18,6 +18,18 @@ The same idea governs the answers: every location comes back as `path:line:colum
1818
1919 An editor tells its server about every keystroke. `mm` has no keystrokes: the model edits with `edit_file`, and the file on disk is the truth. So before every request the client reads the file and sends its content — `didOpen` the first time, a whole-document `didChange` when it moved since — and the server always answers on what the model just wrote. Nothing else has to remember to notify anyone.
2020
21+## Why mm tells the server when go.mod changes
22+
23+Syncing the file is not enough when what changed is the project around it. A server reads its modules and dependencies from files such as `go.mod`, `go.sum` or `package.json`, and it only learns that they changed when the client tells it, with `workspace/didChangeWatchedFiles`. An editor watches the disk for that; `mm` did not, and the model changes those files with `bash`: `go get`, `go mod tidy`, `npm install`. On 2026-12-05 Mellum2.1 ran `go get gopkg.in/yaml.v3`, the build passed, and gopls kept answering `could not import gopkg.in/yaml.v3` after every edit. The model spent its calls on `go mod tidy`, `go list -m` and re-reads of `go.mod`, looking for an error that no longer existed.
24+
25+So before every sync, mm checks the workspace files of the file's directory and of every directory above it up to the project root (a Go module may sit in a subdirectory): `go.mod`, `go.sum`, `go.work`, `go.work.sum`, `package.json`, `package-lock.json`, `tsconfig.json`, `jsconfig.json`, `Cargo.toml`, `Cargo.lock`, `pyproject.toml`, `requirements.txt`. It compares their modification time and size with what it saw last, and sends one notification listing what was created, changed or deleted. Then it syncs the file. That costs a dozen `stat` calls per request. The diagnostics mm appends to `read_file` follow the same rule: a re-read recalls the last errors only while neither the file nor its workspace files changed, and otherwise asks the server again. Rejected: watching the whole tree (costly, and the code files are synced anyway), and restarting the server after a `bash` call (slow, and it loses the server's cache).
26+
27+## Why an empty list of diagnostics is not believed at once
28+
29+A server publishes diagnostics when it likes; mm waits for the publication that follows its sync. For a long time it took the first one. On 2026-12-02 that was wrong: Mellum2 created the workspace's first `go.mod`, then edited three files with wrong imports, and each edit was answered `clean` while `go build` reported every error. The inferred cause — not reproduced with a warm gopls — is a server reloading its workspace and publishing an empty list before its real answer. A false `clean` is worse than none: the model believes broken code builds.
30+
31+So the two kinds of answer are not treated alike. Errors are taken at once: they are never a false `clean`. An empty list is taken only once it has stood alone for a short while (400 ms) and the server says it is not loading anything — mm now declares `window.workDoneProgress`, so servers report their "Loading packages…" work through `$/progress`. If the wait runs out while the server is still busy, the answer says so instead of `clean`. A clean file costs those 400 ms; a broken one costs nothing more. Rejected: waiting a fixed second after every publication (slower on every edit, and still wrong for a long load), and building the project to check (that is the model's job, through `bash`).
32+
2133 ## Why `rename` writes the files itself, and asks first
2234
2335 A rename is a `WorkspaceEdit`: ranges to replace in several files. The client applies them to disk — from the end of each file backwards so earlier positions stay valid, with UTF-16 columns converted to bytes — then re-syncs the changed files so the next question is answered on the renamed code. In the terminal it runs like `edit_file` does; where a front end has a permission dialog (with `yolo: false`: the line mode, the window, an editor over ACP) it asks, because it writes, while the five navigation actions do not: a dialog on every read teaches people to click "allow" without reading.
@@ -18,6 +18,18 @@ The same idea governs the answers: every location comes back as `path:line:colum
18 18
19 An editor tells its server about every keystroke. `mm` has no keystrokes: the model edits with `edit_file`, and the file on disk is the truth. So before every request the client reads the file and sends its content — `didOpen` the first time, a whole-document `didChange` when it moved since — and the server always answers on what the model just wrote. Nothing else has to remember to notify anyone.19 An editor tells its server about every keystroke. `mm` has no keystrokes: the model edits with `edit_file`, and the file on disk is the truth. So before every request the client reads the file and sends its content — `didOpen` the first time, a whole-document `didChange` when it moved since — and the server always answers on what the model just wrote. Nothing else has to remember to notify anyone.
20 20
21+## Why mm tells the server when go.mod changes
22+
23+Syncing the file is not enough when what changed is the project around it. A server reads its modules and dependencies from files such as `go.mod`, `go.sum` or `package.json`, and it only learns that they changed when the client tells it, with `workspace/didChangeWatchedFiles`. An editor watches the disk for that; `mm` did not, and the model changes those files with `bash`: `go get`, `go mod tidy`, `npm install`. On 2026-12-05 Mellum2.1 ran `go get gopkg.in/yaml.v3`, the build passed, and gopls kept answering `could not import gopkg.in/yaml.v3` after every edit. The model spent its calls on `go mod tidy`, `go list -m` and re-reads of `go.mod`, looking for an error that no longer existed.
24+
25+So before every sync, mm checks the workspace files of the file's directory and of every directory above it up to the project root (a Go module may sit in a subdirectory): `go.mod`, `go.sum`, `go.work`, `go.work.sum`, `package.json`, `package-lock.json`, `tsconfig.json`, `jsconfig.json`, `Cargo.toml`, `Cargo.lock`, `pyproject.toml`, `requirements.txt`. It compares their modification time and size with what it saw last, and sends one notification listing what was created, changed or deleted. Then it syncs the file. That costs a dozen `stat` calls per request. The diagnostics mm appends to `read_file` follow the same rule: a re-read recalls the last errors only while neither the file nor its workspace files changed, and otherwise asks the server again. Rejected: watching the whole tree (costly, and the code files are synced anyway), and restarting the server after a `bash` call (slow, and it loses the server's cache).
26+
27+## Why an empty list of diagnostics is not believed at once
28+
29+A server publishes diagnostics when it likes; mm waits for the publication that follows its sync. For a long time it took the first one. On 2026-12-02 that was wrong: Mellum2 created the workspace's first `go.mod`, then edited three files with wrong imports, and each edit was answered `clean` while `go build` reported every error. The inferred cause — not reproduced with a warm gopls — is a server reloading its workspace and publishing an empty list before its real answer. A false `clean` is worse than none: the model believes broken code builds.
30+
31+So the two kinds of answer are not treated alike. Errors are taken at once: they are never a false `clean`. An empty list is taken only once it has stood alone for a short while (400 ms) and the server says it is not loading anything — mm now declares `window.workDoneProgress`, so servers report their "Loading packages…" work through `$/progress`. If the wait runs out while the server is still busy, the answer says so instead of `clean`. A clean file costs those 400 ms; a broken one costs nothing more. Rejected: waiting a fixed second after every publication (slower on every edit, and still wrong for a long load), and building the project to check (that is the model's job, through `bash`).
32+
21 ## Why `rename` writes the files itself, and asks first33 ## Why `rename` writes the files itself, and asks first
22 34
23 A rename is a `WorkspaceEdit`: ranges to replace in several files. The client applies them to disk — from the end of each file backwards so earlier positions stay valid, with UTF-16 columns converted to bytes — then re-syncs the changed files so the next question is answered on the renamed code. In the terminal it runs like `edit_file` does; where a front end has a permission dialog (with `yolo: false`: the line mode, the window, an editor over ACP) it asks, because it writes, while the five navigation actions do not: a dialog on every read teaches people to click "allow" without reading.35 A rename is a `WorkspaceEdit`: ranges to replace in several files. The client applies them to disk — from the end of each file backwards so earlier positions stay valid, with UTF-16 columns converted to bytes — then re-syncs the changed files so the next question is answered on the renamed code. In the terminal it runs like `edit_file` does; where a front end has a permission dialog (with `yolo: false`: the line mode, the window, an editor over ACP) it asks, because it writes, while the five navigation actions do not: a dialog on every read teaches people to click "allow" without reading.
modified docs/en/explanation/struggling-models.md +11 -1
@@ -24,6 +24,16 @@ Struggle signals (ticket 153) make the same detections visible to the **user**,
2424
2525 **Repairs before refusals.** Some mistakes can only mean one thing: `"true"` for `true`, `old_text` for `old`, a path with a directory missing. mm repairs them and says so in the tool output, rather than refusing and hoping the model fixes them — refusals that quote the right path were measured to make a small model loop. See [tools](../reference/tools.md#arguments-that-do-not-match-a-tools-schema) and [`workspace`](../reference/configuration.md#workspace-keys).
2626
27+**Tool feedback that must not mislead** (v2.2.2, tickets 294–300 and 307). The validation runs of 2026-12-02 with Mellum2, Mellum2.1 and Qwen3-Coder-Next failed less on their tasks than on what the tools told them. A diagnostics call said `clean` on files that did not build, so the model believed its wrong imports; an edit with `old` equal to `new`, sent twelve times between reads, was a success each time, so no rule saw a loop; a `line` of 1000000000000000 was accepted; a form feed written for `\f` was invisible in the diff. The fixes follow one rule: a tool answer must be true and visible, or say that it is not sure. An empty diagnostics list is only believed once it has settled, an edit that changes nothing counts as a failure for the loop detector, a line outside the file is refused, control characters are shown escaped, and errors are recalled when a broken file is read again. A recall can be true and still useless: on 2026-12-04 Mellum2.1 Thinking knew the extra `}` at line 142 had to go, but read the file eight times without editing it, because `}` is not unique as an edit's old text. So from the second recall, mm stops repeating the fact and says what to do: the line as the file has it, and the `edit_file` call, with `line`, that changes it.
28+
29+**Ending in an answer, not an error.** Three runs out of four that day ended on bookkeeping after the work was done: a `plan update` without its status, repeated until the loop detector stopped the turn — in error, with no answer. A repeated text was already handed back for an answer; a repeated tool call now is too: the stopped calls are answered "not run" and the model is asked once, without tools, for its final answer. A missing plan status now means `done`, the one thing a model that leaves it out can mean, and the tool's description asks for a single update per task.
30+
31+**Degenerate replies, recognised as loops.** A sentence followed by thousands of blank lines up to the token limit was reported as "raise max_tokens" — the wrong advice, since a larger limit only buys more blank lines. It is now a loop: cut while it streams, handed back once, and collapsed in the answer. A tool call written inside the reasoning, with nothing else in the reply, ended the turn silently; it is handed back once with the call quoted, and nothing from the reasoning is ever run — running it would give the reasoning, which the user may not see, the power to act.
32+
33+**Advice, never a stop, for a test run again.** A model re-running the same test with other sleeps and timeouts is going in circles, but one re-running it after a change is doing the right thing, and the two differ only by whether a file changed in between. So similar `bash` commands since the last file change get a note asking the model to read the code — and the turn is never stopped on similarity alone.
34+
35+**Repairing what the model asked to write.** The form-feed repair is the one place where mm changes the content a model asked to write, so it was studied before being written: every occurrence in the traces had the same shape (a form feed at the start of a line, before `unc`), legitimate form feeds have other shapes (a page break alone on its line), and the repair is limited to source files that hold no form feed yet, to new text only, and is always reported.
36+
2737 ## Rejected alternatives
2838
2939 - **The header.** Considered; the user chose the status bar, which keeps the header for who is answering and how full the context is.
@@ -31,4 +41,4 @@ Struggle signals (ticket 153) make the same detections visible to the **user**,
3141
3242 ## How it relates to the rest
3343
34-The detections themselves are unchanged: the loop detector still tells the model to change approach and still stops the turn after six identical calls; the watchdog, the runaway guard and the broken-call note behave as before. What the turn returns and what the history keeps do not change either — a struggle is shown, never stored. See also [context compression](context-compression.md), which a `context N% full` warning usually precedes, and [thinking models](thinking-models.md) for why the watchdog stays fed while a model reasons.
44+The detections themselves are unchanged: the loop detector still tells the model to change approach and still stops the tool calls after six identical calls — the model then gives its answer without tools; the watchdog, the runaway guard and the broken-call note behave as before. What the turn returns and what the history keeps do not change either — a struggle is shown, never stored. See also [context compression](context-compression.md), which a `context N% full` warning usually precedes, and [thinking models](thinking-models.md) for why the watchdog stays fed while a model reasons.
@@ -24,6 +24,16 @@ Struggle signals (ticket 153) make the same detections visible to the **user**,
24 24
25 **Repairs before refusals.** Some mistakes can only mean one thing: `"true"` for `true`, `old_text` for `old`, a path with a directory missing. mm repairs them and says so in the tool output, rather than refusing and hoping the model fixes them — refusals that quote the right path were measured to make a small model loop. See [tools](../reference/tools.md#arguments-that-do-not-match-a-tools-schema) and [`workspace`](../reference/configuration.md#workspace-keys).25 **Repairs before refusals.** Some mistakes can only mean one thing: `"true"` for `true`, `old_text` for `old`, a path with a directory missing. mm repairs them and says so in the tool output, rather than refusing and hoping the model fixes them — refusals that quote the right path were measured to make a small model loop. See [tools](../reference/tools.md#arguments-that-do-not-match-a-tools-schema) and [`workspace`](../reference/configuration.md#workspace-keys).
26 26
27+**Tool feedback that must not mislead** (v2.2.2, tickets 294–300 and 307). The validation runs of 2026-12-02 with Mellum2, Mellum2.1 and Qwen3-Coder-Next failed less on their tasks than on what the tools told them. A diagnostics call said `clean` on files that did not build, so the model believed its wrong imports; an edit with `old` equal to `new`, sent twelve times between reads, was a success each time, so no rule saw a loop; a `line` of 1000000000000000 was accepted; a form feed written for `\f` was invisible in the diff. The fixes follow one rule: a tool answer must be true and visible, or say that it is not sure. An empty diagnostics list is only believed once it has settled, an edit that changes nothing counts as a failure for the loop detector, a line outside the file is refused, control characters are shown escaped, and errors are recalled when a broken file is read again. A recall can be true and still useless: on 2026-12-04 Mellum2.1 Thinking knew the extra `}` at line 142 had to go, but read the file eight times without editing it, because `}` is not unique as an edit's old text. So from the second recall, mm stops repeating the fact and says what to do: the line as the file has it, and the `edit_file` call, with `line`, that changes it.
28+
29+**Ending in an answer, not an error.** Three runs out of four that day ended on bookkeeping after the work was done: a `plan update` without its status, repeated until the loop detector stopped the turn — in error, with no answer. A repeated text was already handed back for an answer; a repeated tool call now is too: the stopped calls are answered "not run" and the model is asked once, without tools, for its final answer. A missing plan status now means `done`, the one thing a model that leaves it out can mean, and the tool's description asks for a single update per task.
30+
31+**Degenerate replies, recognised as loops.** A sentence followed by thousands of blank lines up to the token limit was reported as "raise max_tokens" — the wrong advice, since a larger limit only buys more blank lines. It is now a loop: cut while it streams, handed back once, and collapsed in the answer. A tool call written inside the reasoning, with nothing else in the reply, ended the turn silently; it is handed back once with the call quoted, and nothing from the reasoning is ever run — running it would give the reasoning, which the user may not see, the power to act.
32+
33+**Advice, never a stop, for a test run again.** A model re-running the same test with other sleeps and timeouts is going in circles, but one re-running it after a change is doing the right thing, and the two differ only by whether a file changed in between. So similar `bash` commands since the last file change get a note asking the model to read the code — and the turn is never stopped on similarity alone.
34+
35+**Repairing what the model asked to write.** The form-feed repair is the one place where mm changes the content a model asked to write, so it was studied before being written: every occurrence in the traces had the same shape (a form feed at the start of a line, before `unc`), legitimate form feeds have other shapes (a page break alone on its line), and the repair is limited to source files that hold no form feed yet, to new text only, and is always reported.
36+
27 ## Rejected alternatives37 ## Rejected alternatives
28 38
29 - **The header.** Considered; the user chose the status bar, which keeps the header for who is answering and how full the context is.39 - **The header.** Considered; the user chose the status bar, which keeps the header for who is answering and how full the context is.
@@ -31,4 +41,4 @@ Struggle signals (ticket 153) make the same detections visible to the **user**,
31 41
32 ## How it relates to the rest42 ## How it relates to the rest
33 43
34-The detections themselves are unchanged: the loop detector still tells the model to change approach and still stops the turn after six identical calls; the watchdog, the runaway guard and the broken-call note behave as before. What the turn returns and what the history keeps do not change either — a struggle is shown, never stored. See also [context compression](context-compression.md), which a `context N% full` warning usually precedes, and [thinking models](thinking-models.md) for why the watchdog stays fed while a model reasons.44+The detections themselves are unchanged: the loop detector still tells the model to change approach and still stops the tool calls after six identical calls — the model then gives its answer without tools; the watchdog, the runaway guard and the broken-call note behave as before. What the turn returns and what the history keeps do not change either — a struggle is shown, never stored. See also [context compression](context-compression.md), which a `context N% full` warning usually precedes, and [thinking models](thinking-models.md) for why the watchdog stays fed while a model reasons.
modified docs/en/how-to/manage-plans-and-tasks.md +3 -3
@@ -10,7 +10,7 @@ Ask for several things at once, as a list:
1010 Do these 2 things: 1. create a file a.txt containing A, 2. create a file b.txt containing B.
1111 ```
1212
13-The model creates a plan from the list, works through it, and updates each task's status as it goes. Small models do it more reliably when you say so: "Use the plan tool. Do these…".
13+The model creates a plan from the list, works through it, and marks each task done as it finishes it — one `update` per task, which is all the tool's description asks for. Small models do it more reliably when you say so: "Use the plan tool. Do these…".
1414
1515 ## Follow the progress
1616
@@ -49,13 +49,13 @@ There is no slash command for plans: they are the model's tool.
4949
5050 - **Several conversations in an editor.** Each thread has its own plans: a plan made in one Zed thread is not visible in another.
5151 - **Starting over.** `/new` and `/resume` forget the plans in every front end; an editor's reload (`session/load`, `session/resume`) starts the thread with no plan. Plans are kept in memory only, never in the session file, and are lost when mm stops.
52-- **The `plan-manager` skill.** `skills/plan-manager` tells the model when to make a plan and how to move through it. Put it in the agent's `skillsDir` for a model that does not use the tool by itself. It also asks the model to repeat the status line in its answer; mm shows it anyway.
52+- **The `plan-manager` skill.** `skills/plan-manager` tells the model when to make a plan and how few calls it takes: one `create`, then one `update` with `status: done` per finished task — the same workflow as the tool's description. Put it in the agent's `skillsDir` for a model that does not use the tool by itself.
5353 - **An agent that does not need plans.** Set `planTool: false`: the tool is not declared. Do it for an agent whose job is a single answer (writing a document, answering questions), where a small model may otherwise loop on plan calls.
5454
5555 ## Troubleshooting
5656
5757 - **The agent does not create a plan.** Give a numbered list, and say "use the plan tool". With a small model, add the `plan-manager` skill.
58-- **The agent keeps calling `plan update`.** `update` changes the status of ONE task; it cannot change a plan's tasks. A call without a valid `status` gets an answer that quotes the call back, names the missing field and gives a valid call. If a small model still repeats it, set `planTool: false` for that agent.
58+- **The agent keeps calling `plan update`.** `update` changes the status of ONE task; it cannot change a plan's tasks. An `update` without `status` marks the task done; one with `tasks` and no `status`, or with an unknown status, gets an answer that quotes the call back and gives a valid call. If a small model still repeats the same call, the loop detector stops its tool calls after six and asks it for its final answer, so the work already done is still reported. To avoid the plan bookkeeping altogether, set `planTool: false` for that agent.
5959
6060 ## See also
6161
@@ -10,7 +10,7 @@ Ask for several things at once, as a list:
10 Do these 2 things: 1. create a file a.txt containing A, 2. create a file b.txt containing B.10 Do these 2 things: 1. create a file a.txt containing A, 2. create a file b.txt containing B.
11 ```11 ```
12 12
13-The model creates a plan from the list, works through it, and updates each task's status as it goes. Small models do it more reliably when you say so: "Use the plan tool. Do these…".13+The model creates a plan from the list, works through it, and marks each task done as it finishes it — one `update` per task, which is all the tool's description asks for. Small models do it more reliably when you say so: "Use the plan tool. Do these…".
14 14
15 ## Follow the progress15 ## Follow the progress
16 16
@@ -49,13 +49,13 @@ There is no slash command for plans: they are the model's tool.
49 49
50 - **Several conversations in an editor.** Each thread has its own plans: a plan made in one Zed thread is not visible in another.50 - **Several conversations in an editor.** Each thread has its own plans: a plan made in one Zed thread is not visible in another.
51 - **Starting over.** `/new` and `/resume` forget the plans in every front end; an editor's reload (`session/load`, `session/resume`) starts the thread with no plan. Plans are kept in memory only, never in the session file, and are lost when mm stops.51 - **Starting over.** `/new` and `/resume` forget the plans in every front end; an editor's reload (`session/load`, `session/resume`) starts the thread with no plan. Plans are kept in memory only, never in the session file, and are lost when mm stops.
52-- **The `plan-manager` skill.** `skills/plan-manager` tells the model when to make a plan and how to move through it. Put it in the agent's `skillsDir` for a model that does not use the tool by itself. It also asks the model to repeat the status line in its answer; mm shows it anyway.52+- **The `plan-manager` skill.** `skills/plan-manager` tells the model when to make a plan and how few calls it takes: one `create`, then one `update` with `status: done` per finished task — the same workflow as the tool's description. Put it in the agent's `skillsDir` for a model that does not use the tool by itself.
53 - **An agent that does not need plans.** Set `planTool: false`: the tool is not declared. Do it for an agent whose job is a single answer (writing a document, answering questions), where a small model may otherwise loop on plan calls.53 - **An agent that does not need plans.** Set `planTool: false`: the tool is not declared. Do it for an agent whose job is a single answer (writing a document, answering questions), where a small model may otherwise loop on plan calls.
54 54
55 ## Troubleshooting55 ## Troubleshooting
56 56
57 - **The agent does not create a plan.** Give a numbered list, and say "use the plan tool". With a small model, add the `plan-manager` skill.57 - **The agent does not create a plan.** Give a numbered list, and say "use the plan tool". With a small model, add the `plan-manager` skill.
58-- **The agent keeps calling `plan update`.** `update` changes the status of ONE task; it cannot change a plan's tasks. A call without a valid `status` gets an answer that quotes the call back, names the missing field and gives a valid call. If a small model still repeats it, set `planTool: false` for that agent.58+- **The agent keeps calling `plan update`.** `update` changes the status of ONE task; it cannot change a plan's tasks. An `update` without `status` marks the task done; one with `tasks` and no `status`, or with an unknown status, gets an answer that quotes the call back and gives a valid call. If a small model still repeats the same call, the loop detector stops its tool calls after six and asks it for its final answer, so the work already done is still reported. To avoid the plan bookkeeping altogether, set `planTool: false` for that agent.
59 59
60 ## See also60 ## See also
61 61
modified docs/en/how-to/navigate-code-with-lsp.md +2 -1
@@ -100,7 +100,7 @@ Small models rarely call `diagnostics` themselves. Two settings make mm append t
100100 ```yaml
101101 lsp:
102102 diagnosticsAfterEdit: true # after each successful write_file / edit_file
103- diagnosticsAfterRead: true # with each read_file, once per version of the file
103+ diagnosticsAfterRead: true # with each read_file: once per version, errors recalled on a re-read, then the fix pointed at
104104 servers:
105105 - name: gopls
106106 command: gopls
@@ -119,6 +119,7 @@ Nothing to configure: the same YAML applies. Navigation calls show up as tool ca
119119 - **A server with settings.** Pass them as `args` (many servers read a flag or a config file in the project root); `mm` answers "no settings" to a server that asks for configuration, so it runs with its defaults.
120120 - **Exact positions.** When the model has an exact position — from `read_file` with `numbered=true` — it may send `line` and `column` (1-based, inside the identifier) instead of `symbol`. `symbol` is the reliable road: small models rarely count columns right.
121121 - **No server on this machine.** The tool is not declared and the banner says `lsp: none of the configured servers is on the PATH — the lsp tool is not declared`. The configuration can stay; the agent works without it.
122+- **Dependencies added through `bash`.** After `go get`, `go mod tidy` or `npm install`, nothing to do: mm tells the server that `go.mod`, `go.sum`, `package.json`… changed before its next request, and the next diagnostics are computed on the new dependencies. See [why](../explanation/lsp-tool.md#why-mm-tells-the-server-when-gomod-changes).
122123 - **Slow first answer.** The first call for a language starts the server and lets it index the project; `diagnostics` may say `as last published` or `no diagnostics received … within 3s` — ask again once.
123124
124125 ## See also
@@ -100,7 +100,7 @@ Small models rarely call `diagnostics` themselves. Two settings make mm append t
100 ```yaml100 ```yaml
101 lsp:101 lsp:
102 diagnosticsAfterEdit: true # after each successful write_file / edit_file102 diagnosticsAfterEdit: true # after each successful write_file / edit_file
103- diagnosticsAfterRead: true # with each read_file, once per version of the file103+ diagnosticsAfterRead: true # with each read_file: once per version, errors recalled on a re-read, then the fix pointed at
104 servers:104 servers:
105 - name: gopls105 - name: gopls
106 command: gopls106 command: gopls
@@ -119,6 +119,7 @@ Nothing to configure: the same YAML applies. Navigation calls show up as tool ca
119 - **A server with settings.** Pass them as `args` (many servers read a flag or a config file in the project root); `mm` answers "no settings" to a server that asks for configuration, so it runs with its defaults.119 - **A server with settings.** Pass them as `args` (many servers read a flag or a config file in the project root); `mm` answers "no settings" to a server that asks for configuration, so it runs with its defaults.
120 - **Exact positions.** When the model has an exact position — from `read_file` with `numbered=true` — it may send `line` and `column` (1-based, inside the identifier) instead of `symbol`. `symbol` is the reliable road: small models rarely count columns right.120 - **Exact positions.** When the model has an exact position — from `read_file` with `numbered=true` — it may send `line` and `column` (1-based, inside the identifier) instead of `symbol`. `symbol` is the reliable road: small models rarely count columns right.
121 - **No server on this machine.** The tool is not declared and the banner says `lsp: none of the configured servers is on the PATH — the lsp tool is not declared`. The configuration can stay; the agent works without it.121 - **No server on this machine.** The tool is not declared and the banner says `lsp: none of the configured servers is on the PATH — the lsp tool is not declared`. The configuration can stay; the agent works without it.
122+- **Dependencies added through `bash`.** After `go get`, `go mod tidy` or `npm install`, nothing to do: mm tells the server that `go.mod`, `go.sum`, `package.json`… changed before its next request, and the next diagnostics are computed on the new dependencies. See [why](../explanation/lsp-tool.md#why-mm-tells-the-server-when-gomod-changes).
122 - **Slow first answer.** The first call for a language starts the server and lets it index the project; `diagnostics` may say `as last published` or `no diagnostics received … within 3s` — ask again once.123 - **Slow first answer.** The first call for a language starts the server and lets it index the project; `diagnostics` may say `as last published` or `no diagnostics received … within 3s` — ask again once.
123 124
124 ## See also125 ## See also
modified docs/en/reference/cli.md +6 -2
@@ -204,10 +204,13 @@ Signs that the model is struggling, shown to the user apart from the answer (tic
204204 | Signal | Level | When |
205205 |--------|-------|------|
206206 | `loop: <tool> ×N` | ⚠ | the loop detector flagged the same call with the same result N times in a row; the model is told to change approach |
207-| `stuck: <tool> ×N` | ✖ | the model ignored that advice: the loop detector stopped the turn |
208-| `looped — handed back 1/1` | ⚠ | the same sentence (12 characters or more) came 20 times in a row in the model's reasoning or answer while it streamed: that model call is cut and handed back once, with a note telling the model it was repeating itself |
207+| `stuck: <tool> ×N` | ✖ | the model ignored that advice: the loop detector stopped its tool calls |
208+| `loop detector stop — asked for the answer` | ⚠ | after that stop, the model is called once more without tools for its final answer (the turn ends in error only when none comes) |
209+| `same test again: <tool> ×N with the same result, no file changed` | ⚠ | a `bash` command run for the Nth time (N ≥ 3) with the same shape and the same result since the last file change; the model is told to read the code instead; never stops the turn |
210+| `looped — handed back 1/1` | ⚠ | the same sentence (12 characters or more) came 20 times in a row in the model's reasoning or answer while it streamed, or 100 blank lines did: that model call is cut and handed back once, with a note telling the model it was repeating itself (or writing blank lines) |
209211 | `looped — stopped` | ✖ | it looped again: the turn ends with `the model looped: "…" repeated N times in a row — stopped; ask again, or lower the temperature / reasoning effort` |
210212 | `reasoning cut at the limit 1/1` | ⚠ | a reply ended on the token limit with reasoning only — no text, no tool call; it is handed back once, asking the model to act now |
213+| `tool call in the reasoning — handed back 1/1` | ⚠ | a reply with no text and no tool call whose reasoning holds a complete `<tool_call>` block: it is handed back once, quoting the block — nothing written in the reasoning is run. Once per occurrence: after a reply with a real tool call, a new one is handed back again |
211214 | `answer after a failed <tool> — handed back 1/1` | ⚠ | the model gave its final answer while the turn's last `write_file` / `edit_file` had failed; the answer is handed back once with a note: the file was not changed, fix the call or say so |
212215 | `failing: N tool calls in a row` | ⚠ | the last N tool calls (N ≥ 3) all failed, with different inputs — a non-zero exit, a refused edit, a missing file, a rejected permission…; reported again at each new failure, reset by the first success; the model is not told |
213216 | `broken tool call (cut off\|invalid JSON) n/m` | ⚠ | a tool call's arguments did not parse; the call is handed back to the model (attempt n of m) |
@@ -219,6 +222,7 @@ Signs that the model is struggling, shown to the user apart from the answer (tic
219222 | `empty answer` | ⚠ | the turn ended without text and without a tool call |
220223 | `empty answer — the model reasoned until the limit (<key> N): raise sampling.<key>, or lower its reasoning effort` | ✖ | the reply handed back above was cut at the limit again |
221224 | `the model looped: the same line repeated N times — the answer is cut there` | ✖ | the final answer holds 20 identical lines or more in a row: they are collapsed to one line plus `[… the same line repeated N more times — removed by mm]`, in the answer and in the history; ` (it ran until the limit: <key>)` is added when it also hit the token limit |
225+| `the model looped: N blank lines in a row — removed from the answer` | ✖ | the final answer holds 40 blank lines in a row or more: they are replaced by `[… N blank lines — removed by mm]`, in the answer and in the history; ` (it ran until the limit: a larger <key> would not help)` is added when it also hit the token limit |
222226 | `answer cut at the limit (<key> N): raise sampling.<key>, or ask for a shorter answer` | ⚠ | the answer stopped mid-way at the token limit (`max_tokens` or `max_completion_tokens`) |
223227 | `the last <tool> failed (…) — that change was not made, whatever the answer says` | ✖ | the turn's last `write_file` / `edit_file` failed, with no successful one after it — still so after the hand-back above |
224228 | `context N% full` | ⚠ | the last model call read 80 % of the context window or more (window known only) |
@@ -204,10 +204,13 @@ Signs that the model is struggling, shown to the user apart from the answer (tic
204 | Signal | Level | When |204 | Signal | Level | When |
205 |--------|-------|------|205 |--------|-------|------|
206 | `loop: <tool> ×N` | ⚠ | the loop detector flagged the same call with the same result N times in a row; the model is told to change approach |206 | `loop: <tool> ×N` | ⚠ | the loop detector flagged the same call with the same result N times in a row; the model is told to change approach |
207-| `stuck: <tool> ×N` | ✖ | the model ignored that advice: the loop detector stopped the turn |207+| `stuck: <tool> ×N` | ✖ | the model ignored that advice: the loop detector stopped its tool calls |
208-| `looped — handed back 1/1` | ⚠ | the same sentence (12 characters or more) came 20 times in a row in the model's reasoning or answer while it streamed: that model call is cut and handed back once, with a note telling the model it was repeating itself |208+| `loop detector stop — asked for the answer` | ⚠ | after that stop, the model is called once more without tools for its final answer (the turn ends in error only when none comes) |
209+| `same test again: <tool> ×N with the same result, no file changed` | ⚠ | a `bash` command run for the Nth time (N ≥ 3) with the same shape and the same result since the last file change; the model is told to read the code instead; never stops the turn |
210+| `looped — handed back 1/1` | ⚠ | the same sentence (12 characters or more) came 20 times in a row in the model's reasoning or answer while it streamed, or 100 blank lines did: that model call is cut and handed back once, with a note telling the model it was repeating itself (or writing blank lines) |
209 | `looped — stopped` | ✖ | it looped again: the turn ends with `the model looped: "…" repeated N times in a row — stopped; ask again, or lower the temperature / reasoning effort` |211 | `looped — stopped` | ✖ | it looped again: the turn ends with `the model looped: "…" repeated N times in a row — stopped; ask again, or lower the temperature / reasoning effort` |
210 | `reasoning cut at the limit 1/1` | ⚠ | a reply ended on the token limit with reasoning only — no text, no tool call; it is handed back once, asking the model to act now |212 | `reasoning cut at the limit 1/1` | ⚠ | a reply ended on the token limit with reasoning only — no text, no tool call; it is handed back once, asking the model to act now |
213+| `tool call in the reasoning — handed back 1/1` | ⚠ | a reply with no text and no tool call whose reasoning holds a complete `<tool_call>` block: it is handed back once, quoting the block — nothing written in the reasoning is run. Once per occurrence: after a reply with a real tool call, a new one is handed back again |
211 | `answer after a failed <tool> — handed back 1/1` | ⚠ | the model gave its final answer while the turn's last `write_file` / `edit_file` had failed; the answer is handed back once with a note: the file was not changed, fix the call or say so |214 | `answer after a failed <tool> — handed back 1/1` | ⚠ | the model gave its final answer while the turn's last `write_file` / `edit_file` had failed; the answer is handed back once with a note: the file was not changed, fix the call or say so |
212 | `failing: N tool calls in a row` | ⚠ | the last N tool calls (N ≥ 3) all failed, with different inputs — a non-zero exit, a refused edit, a missing file, a rejected permission…; reported again at each new failure, reset by the first success; the model is not told |215 | `failing: N tool calls in a row` | ⚠ | the last N tool calls (N ≥ 3) all failed, with different inputs — a non-zero exit, a refused edit, a missing file, a rejected permission…; reported again at each new failure, reset by the first success; the model is not told |
213 | `broken tool call (cut off\|invalid JSON) n/m` | ⚠ | a tool call's arguments did not parse; the call is handed back to the model (attempt n of m) |216 | `broken tool call (cut off\|invalid JSON) n/m` | ⚠ | a tool call's arguments did not parse; the call is handed back to the model (attempt n of m) |
@@ -219,6 +222,7 @@ Signs that the model is struggling, shown to the user apart from the answer (tic
219 | `empty answer` | ⚠ | the turn ended without text and without a tool call |222 | `empty answer` | ⚠ | the turn ended without text and without a tool call |
220 | `empty answer — the model reasoned until the limit (<key> N): raise sampling.<key>, or lower its reasoning effort` | ✖ | the reply handed back above was cut at the limit again |223 | `empty answer — the model reasoned until the limit (<key> N): raise sampling.<key>, or lower its reasoning effort` | ✖ | the reply handed back above was cut at the limit again |
221 | `the model looped: the same line repeated N times — the answer is cut there` | ✖ | the final answer holds 20 identical lines or more in a row: they are collapsed to one line plus `[… the same line repeated N more times — removed by mm]`, in the answer and in the history; ` (it ran until the limit: <key>)` is added when it also hit the token limit |224 | `the model looped: the same line repeated N times — the answer is cut there` | ✖ | the final answer holds 20 identical lines or more in a row: they are collapsed to one line plus `[… the same line repeated N more times — removed by mm]`, in the answer and in the history; ` (it ran until the limit: <key>)` is added when it also hit the token limit |
225+| `the model looped: N blank lines in a row — removed from the answer` | ✖ | the final answer holds 40 blank lines in a row or more: they are replaced by `[… N blank lines — removed by mm]`, in the answer and in the history; ` (it ran until the limit: a larger <key> would not help)` is added when it also hit the token limit |
222 | `answer cut at the limit (<key> N): raise sampling.<key>, or ask for a shorter answer` | ⚠ | the answer stopped mid-way at the token limit (`max_tokens` or `max_completion_tokens`) |226 | `answer cut at the limit (<key> N): raise sampling.<key>, or ask for a shorter answer` | ⚠ | the answer stopped mid-way at the token limit (`max_tokens` or `max_completion_tokens`) |
223 | `the last <tool> failed (…) — that change was not made, whatever the answer says` | ✖ | the turn's last `write_file` / `edit_file` failed, with no successful one after it — still so after the hand-back above |227 | `the last <tool> failed (…) — that change was not made, whatever the answer says` | ✖ | the turn's last `write_file` / `edit_file` failed, with no successful one after it — still so after the hand-back above |
224 | `context N% full` | ⚠ | the last model call read 80 % of the context window or more (window known only) |228 | `context N% full` | ⚠ | the last model call read 80 % of the context window or more (window known only) |
modified docs/en/reference/configuration.md +1 -1
@@ -196,7 +196,7 @@ a2a:
196196 | `lsp.servers[].args` | list of strings | `[]` | Its arguments (many servers need `--stdio`). |
197197 | `lsp.servers[].extensions` | list of strings | — | File extensions it serves, with the dot (`.go`, `.ts`). Required, at least one; matched case-insensitively; an extension may be served by one server only. |
198198 | `lsp.diagnosticsAfterEdit` | bool | `false` | After a successful `write_file` or `edit_file` on a file a server handles, ask that server for the file's diagnostics and append them to the tool output under `[lsp diagnostics after this change]`. The server is started if needed; it has 8 s to answer, else the note says `not available — <reason>` (the edit itself succeeded). Small models rarely ask for diagnostics themselves: 0 times in 54 runs in `demos/gemma-coder`. |
199-| `lsp.diagnosticsAfterRead` | bool | `false` | After a successful `read_file` of a file a server handles, append that server's diagnostics for the whole file under `[lsp diagnostics for this file, added by mm — not part of its content]`. Once per version of the file (modification time and size): reading it again unchanged, or right after an edit that already brought its diagnostics, asks nothing. Same 8 s budget as `diagnosticsAfterEdit`. |
199+| `lsp.diagnosticsAfterRead` | bool | `false` | After a successful `read_file` of a file a server handles, append that server's diagnostics for the whole file under `[lsp diagnostics for this file, added by mm — not part of its content]`. Once per version of the file (modification time and size): reading it again unchanged, or right after an edit that already brought its diagnostics, asks nothing — and appends nothing for a clean file, but a short recall when that version had errors: `[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still N error(s)]` followed by the first 3 `error …` lines and `… and M more`. From the second such recall of the same version, a note follows: `[mm: you have read <path> N times since it last changed, and the error has not moved …]`, with the text of the first error's line and an `edit_file` call that uses `line` (its `new` is the old text, for the model to correct — never a ready deletion) (🔁 on screen); the count starts again when the file changes. Same 8 s budget as `diagnosticsAfterEdit`. |
200200
201201 ```yaml
202202 lsp:
@@ -196,7 +196,7 @@ a2a:
196 | `lsp.servers[].args` | list of strings | `[]` | Its arguments (many servers need `--stdio`). |196 | `lsp.servers[].args` | list of strings | `[]` | Its arguments (many servers need `--stdio`). |
197 | `lsp.servers[].extensions` | list of strings | — | File extensions it serves, with the dot (`.go`, `.ts`). Required, at least one; matched case-insensitively; an extension may be served by one server only. |197 | `lsp.servers[].extensions` | list of strings | — | File extensions it serves, with the dot (`.go`, `.ts`). Required, at least one; matched case-insensitively; an extension may be served by one server only. |
198 | `lsp.diagnosticsAfterEdit` | bool | `false` | After a successful `write_file` or `edit_file` on a file a server handles, ask that server for the file's diagnostics and append them to the tool output under `[lsp diagnostics after this change]`. The server is started if needed; it has 8 s to answer, else the note says `not available — <reason>` (the edit itself succeeded). Small models rarely ask for diagnostics themselves: 0 times in 54 runs in `demos/gemma-coder`. |198 | `lsp.diagnosticsAfterEdit` | bool | `false` | After a successful `write_file` or `edit_file` on a file a server handles, ask that server for the file's diagnostics and append them to the tool output under `[lsp diagnostics after this change]`. The server is started if needed; it has 8 s to answer, else the note says `not available — <reason>` (the edit itself succeeded). Small models rarely ask for diagnostics themselves: 0 times in 54 runs in `demos/gemma-coder`. |
199-| `lsp.diagnosticsAfterRead` | bool | `false` | After a successful `read_file` of a file a server handles, append that server's diagnostics for the whole file under `[lsp diagnostics for this file, added by mm — not part of its content]`. Once per version of the file (modification time and size): reading it again unchanged, or right after an edit that already brought its diagnostics, asks nothing. Same 8 s budget as `diagnosticsAfterEdit`. |199+| `lsp.diagnosticsAfterRead` | bool | `false` | After a successful `read_file` of a file a server handles, append that server's diagnostics for the whole file under `[lsp diagnostics for this file, added by mm — not part of its content]`. Once per version of the file (modification time and size): reading it again unchanged, or right after an edit that already brought its diagnostics, asks nothing — and appends nothing for a clean file, but a short recall when that version had errors: `[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still N error(s)]` followed by the first 3 `error …` lines and `… and M more`. From the second such recall of the same version, a note follows: `[mm: you have read <path> N times since it last changed, and the error has not moved …]`, with the text of the first error's line and an `edit_file` call that uses `line` (its `new` is the old text, for the model to correct — never a ready deletion) (🔁 on screen); the count starts again when the file changes. Same 8 s budget as `diagnosticsAfterEdit`. |
200 200
201 ```yaml201 ```yaml
202 lsp:202 lsp:
modified docs/en/reference/tools.md +17 -9
@@ -74,8 +74,10 @@ Declared when `editTools: true`.
7474 | Aspect | Behaviour |
7575 |--------|-----------|
7676 | Existing file | Entirely replaced. |
77-| Identical content | Nothing is written; the result says so. |
77+| Identical content | Nothing is written; the result says so. For the loop detector it is a failed call (see [Loop detection](#loop-detection)). |
7878 | Output | A one-line headline and the diff against the previous content. |
79+| Control characters in the diff | Shown escaped (`\f`, `\v`, `\b`, `\a`, `\r`, otherwise `\xNN`); a tab, and a carriage return ending a CRLF line, stay as they are. When an added line holds one, the diff ends with `note: the new text holds control characters, shown escaped above (\f is U+000C, a form feed). In JSON, "\f" IS a form feed: …`. The file itself is written as sent. |
80+| Form feeds (U+000C) | In a source file (`.go`, `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.py`, `.rs`, `.java`, `.kt`, `.swift`, `.c`, `.h`, `.cc`, `.cpp`, `.hpp`, `.cs`, `.rb`, `.php`, `.lua`, `.zig`, `.scala`, `.dart`, `.sh`) that holds no form feed yet, a form feed that starts a line before a lowercase letter — `"\n\func"` in the JSON arguments, which JSON reads as a new line, a form feed and `unc` — is written as a new line and `f` (a blank line, then `func`), or as `f` alone after an indentation or at the very start. The output then ends with `[mm: repaired N form feed(s) (U+000C) at the start of a line, in …]` and the user sees a `🩹` notice. Never changed: a form feed alone on its line (a page break), one inside a line, one before anything but a lowercase letter, any form feed in another kind of file or in a file that already holds one. |
7981 | ACP | Kind `edit`; permission requested; the change travels as a diff (new-file diff when created). |
8082
8183 ## `edit_file`
@@ -88,13 +90,13 @@ Declared when `editTools: true`.
8890 | `edits` | array of `{old, new, line}` | — | Replacements, all resolved against the original file. |
8991 | `edits[].old` | string | — | Exact text to find, present exactly once. Whitespace is forgiven — see *How `old` is matched*. |
9092 | `edits[].new` | string | — | Replacement; empty deletes the matched text. |
91-| `edits[].line` | integer | — | Only when `old` appears several times: the 1-based line where the occurrence to change starts, as `read_file` with `numbered: true` shows it. Ignored when `old` is unique. A line where no occurrence starts is refused: `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. |
93+| `edits[].line` | integer | — | Only when `old` appears several times: the 1-based line where the occurrence to change starts, as `read_file` with `numbered: true` shows it. Ignored when `old` is unique, as long as it is inside the file. A line where no occurrence starts is refused: `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. A line outside the file — past its last line, or below 1 — is refused whether `old` is unique or not: `edit #1: "line": 1000000000000000 is outside the file, which has 42 line(s) — "line" is only needed when old appears several times; leave it out, or give the line where old starts, as read_file numbered=true shows it`. |
9294 | `dry_run` | bool | `false` | Report what would change, write nothing. |
9395
9496 | Rule | Consequence when broken |
9597 |------|-------------------------|
9698 | `old` appears exactly once, or `line` picks one | Refused: not found, or ambiguous — `old text appears N times (lines 11, 20) — to change ONE of them, add "line": the number of the line where it starts (one of 11, 20); or include its surrounding lines in old until the text is unique; to change several, send one edit per place…`. |
97-| `old` and `new` identical | Not an error when the file holds `old`: that edit is reported as already done (` · N already as asked (identical old and new)`; `<path>: unchanged — already as asked: …` when it is the only one) and the other edits apply. When the file does not hold it: not found. |
99+| `old` and `new` identical | Not an error when the file holds `old`: that edit is reported as already done (` · N already as asked (identical old and new)`; `<path>: unchanged — already as asked: …` when it is the only one) and the other edits apply. When the file does not hold it: not found. A call that changes nothing at all is a failed call for the loop detector (see [Loop detection](#loop-detection)). |
98100 | Two edits must not overlap, nest or repeat | Refused. |
99101 | Edits are resolved against the original text, never in cascade | — |
100102 | Any refused edit | Nothing is written. |
@@ -102,6 +104,8 @@ Declared when `editTools: true`.
102104 | Aspect | Behaviour |
103105 |--------|-----------|
104106 | Output | A one-line headline (edits applied, lines added and deleted, first changed line, and ` · N matched ignoring whitespace` when any edit needed a relaxed match) and the diff with line numbers. |
107+| Control characters in the diff | As for `write_file`. |
108+| Form feeds (U+000C) | Repaired as for `write_file`, in each edit's `new` text only — never in `old`, which must match the file as it is; the note names the edit (`edit #2 new text, line(s) 4`). |
105109 | ACP | Kind `edit`; permission requested; the change travels as a diff with old and new text. |
106110
107111 ### How `old` is matched
@@ -147,14 +151,14 @@ Declared when `planTool: true` (the default). Turns a list of tasks into a plan
147151 | `name` | string | The plan. For `create`, optional: a plan without a name is called `user-request-N` (N counts the conversation's plans). For the other actions, optional too: without it, the action works on the conversation's most recently created plan (`list` ignores it). |
148152 | `tasks` | list of `{description, id?}` | For `create`: the tasks, in order. A task without an `id` gets its position (1, 2, …). Ignored by the other actions. |
149153 | `taskId` | integer | For `update`: the task, from 1. |
150-| `status` | string | For `update`: `open`, `in_progress`, `done` or `failed`. |
154+| `status` | string | For `update`: `done`, `failed`, `in_progress` or `open`. Absent means `done`. |
151155 | `message` | string | For `update`: a note kept on the task. |
152156
153157 | Action | Does | Result (JSON text) |
154158 |--------|------|--------------------|
155159 | `create` | Creates the plan, every task `open`. Refused when the name is taken. | `result` (`Plan '<name>' created with N tasks. Current: Task 1`), `planName`, `status`, `current`, `total`; in the line mode, also the whole `plan`. |
156160 | `get` | Reads one plan. | `result`, `plan` (name, tasks with id, description, status, start and end times, note). |
157-| `update` | Sets one task's status; `in_progress` records its start time (once) and makes it the current task, `done` and `failed` record its end time. | `result`, `status` (the status line, below). |
161+| `update` | Sets one task's status; `in_progress` records its start time (once) and makes it the current task, `done` and `failed` record its end time. Without `status` and without `tasks`, the task is marked `done`. | `result` — ending with ` (no status given: taken as done)` when `status` was absent —, `status` (the status line, below). |
158162 | `next` | Marks the current task `done` and starts the next one that is neither done nor failed (`in_progress`); a task already finished with `update` is skipped. | `result` (`Task N done. Next: Task M - <description>`, or `Plan '<name>' is complete! All N tasks done.`), `status`, `nextTask` when there is one. |
159163 | `list` | Lists the plans held. | `result`, `plans` (names, oldest first). |
160164 | `delete` | Removes a plan. | `result`. |
@@ -163,7 +167,8 @@ Declared when `planTool: true` (the default). Turns a list of tasks into a plan
163167 | Aspect | Behaviour |
164168 |--------|-----------|
165169 | Status line | `[C/N] <icon> Task C: <description> (<status>)` for the task being worked on — the first one in progress, else the first one still open —, `[N/N] Plan finished: D done, F failed` when every task is over and some failed, `[N/N] All tasks complete!` when all are done. Icons: ⏳ open, 🔄 in progress, ✅ done, ❌ failed. |
166-| Errors | Returned as text, never as a failed generation: `[error: no plans found for this session]`, `[error: no plan named '<name>' found]`, `[error: plan '<name>' already exists]`, `[error: no task with id N in plan '<name>']`, `[error: unknown action '<action>'. Valid actions: …]`. An `update` without a valid `status` quotes the call back, says that `tasks` is ignored by `update` when it was sent, and gives a call that works. |
170+| Errors | Returned as text, never as a failed generation: `[error: no plans found for this session]`, `[error: no plan named '<name>' found]`, `[error: plan '<name>' already exists]`, `[error: no task with id N in plan '<name>']`, `[error: unknown action '<action>'. Valid actions: …]`. An `update` with a `status` that is not one of the four, or with `tasks` and no `status`, quotes the call back, says that `tasks` is ignored by `update` when it was sent, and gives a call that works. |
171+| Description | Asks for one `update` with `status: "done"` per finished task, no plan call between the steps of a task, and none once every task is done. `next` and `status` are still accepted. |
167172 | Storage | In memory, per conversation: the line mode and the window hold one; over ACP each session has its own, and one thread never sees another's plans. Plans are not written to the session file and are lost when mm stops. A conversation that changes starts with no plan: `/new` and `/resume` in every front end, `session/load` and `session/resume` over ACP. |
168173 | Permission | `create`, `update`, `next` and `delete` are requested when `yolo: false`; a refusal returns `[plan: command rejected by the user]`. `get`, `list` and `status` never ask. |
169174 | Display | Line mode: `📋 plan: <action> <name>` before the call, then `📋 <status line>` after every action that has one (`create`, `update`, `next`, `status`). Window: the call as a tool call, and `📋 <status line>` as a notice. Editor (ACP): the call as a tool call, the status inside its result. The progress is shown by mm, whether or not the model repeats it. |
@@ -188,7 +193,7 @@ Declared when `lsp.servers` lists at least one server whose command is on the `P
188193 | `definition`, `references` | One `path:line:column <source line>` per location, sorted by path then position, duplicates removed; paths inside the project are relative, others absolute. `references` is prefixed with `N reference(s):` and includes the declaration. |
189194 | `hover` | The server's text as it sent it (signature, type, documentation; Markdown for most servers). |
190195 | `symbols` | One `<kind> <name> [<detail>] line N` per symbol, children indented two spaces. |
191-| `diagnostics` | The file is synced, then the call waits up to 3 s for the server's publication. `N diagnostic(s) in <path>:` then one `<severity> path:line:column <message> [<source>]` per finding; `no diagnostics: <path> is clean`; ` (as last published)` when the file did not change since the server last spoke; `no diagnostics received for <path> within 3s (…)` when it never did. |
196+| `diagnostics` | The file is synced, then the call waits up to 3 s for the server's publication. A publication with findings is taken at once. An empty one is taken once no other publication for the file came for 400 ms and the server reports no work in progress (`$/progress`; mm declares `window.workDoneProgress` at start-up): a server reloading its workspace may first publish an empty list. When the 3 s run out during such work, the answer is `no diagnostics yet for <path>, but the server is still loading the workspace — this does NOT mean the file is clean: ask again in a moment, or build it`. A server that answers `textDocument/diagnostic` is asked instead, and its answer is taken as it is. `N diagnostic(s) in <path>:` then one `<severity> path:line:column <message> [<source>]` per finding; `no diagnostics: <path> is clean`; ` (as last published)` when the file did not change since the server last spoke; `no diagnostics received for <path> within 3s (…)` when it never did. |
192197 | `rename` | Applies the server's edits to the files on disk (UTF-16 positions converted), tells the server the new contents, and answers `renamed to <new>: N edit(s) in M file(s)` followed by one `path: N edit(s)` line per file. Without `new_name`: `[lsp: rename needs new_name — call lsp again with {"action": "rename", "path": …, "symbol": …, "new_name": "<the new identifier>"}; do not use edit_file for a rename]`. |
193198 | Positions | 1-based lines and columns at the tool's boundary, 0-based UTF-16 on the wire. A position past the end of a line or of the file is refused with the count. |
194199 | File sync | Before every request the file is read from disk and sent as `didOpen` (first time) or a whole-document `didChange` (when its content moved): edits made with `edit_file` are seen without any extra step. |
@@ -473,12 +478,15 @@ Every tool records `(tool, input, output)` in the loop detector after each call.
473478 | Situation | Behaviour |
474479 |-----------|-----------|
475480 | The same triple 3 times in a row | The tool's output gets `[LOOP_DETECTED: You have attempted the same action multiple times with the same result. Please try a different approach or provide more information.]` appended. Nothing stops. |
476-| 3 more identical calls after that (6 in a row) | The tool returns an error instead of text and the turn ends: `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. The history keeps everything that ran; the error is recorded in the session file's `errors` array (`where: generation`). |
481+| 3 more identical calls after that (6 in a row) | The tool calls stop. The calls of that reply are answered `[mm: not run — the loop detector stopped the tool calls]`, and the model is called once more, **without tools**, after `[mm: mm stopped your tool calls: <the detector's sentence>. No more tools in this turn. Give your final answer now: …]`; its answer ends the turn. When that call fails, calls a tool or brings no text, the turn ends with the error `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. The history keeps everything that ran; that error is recorded in the session file's `errors` array (`where: generation`). |
482+| A `write_file` or `edit_file` that changes nothing | Recorded as a **failed** call (identical content; every edit with `old` equal to `new`): the rule for failed calls below flags it once it was recorded 3 times among the last 10 calls, reads in between included. A dry run is not a failure. |
477483 | A different call | The count starts again. `/new` resets the detector; `/compact` does not. |
478484 | The same call failing again with other calls in between | A **failed** call (same tool, input and output) already recorded 3 times among the last 10 calls is flagged, whatever came in between, and the turn stops at its third flag. Successful calls keep the consecutive rule: reading a file again is not a loop. |
479485 | A tool call whose streamed arguments repeat a pattern (the last 256 characters are one 4–64-character pattern repeated) or exceed 256 KB | The generation is stopped at once: `[error: the model's tool call ran away: its arguments repeat the same pattern (N characters so far: …) — generation stopped; rephrase the request, or try another model]`. Without it a derailed model composes garbage for minutes while the screen shows "Thinking" (the watchdog is fed by every delta). While a tool call streams, the spinner says `Composing a tool call`. |
480486
481-The thresholds (3, then 3 more) are set in `main.go`; `maxTurns` remains the outer bound of a turn.
487+| The same `bash` test run again | A `bash` call whose command and output have the same shape as 2 earlier calls since the last `write_file` / `edit_file` that changed a file gets `[mm: this is the same test, with the same result, for the 3rd time since the last file change — sleeps, timeouts and kills aside. …]` at the end of its output, and the user sees `same test again: bash ×N with the same result, no file changed`; from the 3rd, at every new one. Shape of the command: `pkill`, `kill`, `killall`, `sleep`, `wait`, `true` and `:` commands dropped, a `timeout …` prefix, redirections and a trailing `&` removed, every number written `N`. Shape of the output: numbers of 4 digits or more and decimals written `N`, spacing evened out — `000` and `200` stay different. Never stops the turn. |
488+
489+The thresholds (3, then 3 more; 3 for similar `bash` calls) are set in `main.go`; `maxTurns` remains the outer bound of a turn.
482490
483491 ## Counters shown after a turn
484492
@@ -74,8 +74,10 @@ Declared when `editTools: true`.
74 | Aspect | Behaviour |74 | Aspect | Behaviour |
75 |--------|-----------|75 |--------|-----------|
76 | Existing file | Entirely replaced. |76 | Existing file | Entirely replaced. |
77-| Identical content | Nothing is written; the result says so. |77+| Identical content | Nothing is written; the result says so. For the loop detector it is a failed call (see [Loop detection](#loop-detection)). |
78 | Output | A one-line headline and the diff against the previous content. |78 | Output | A one-line headline and the diff against the previous content. |
79+| Control characters in the diff | Shown escaped (`\f`, `\v`, `\b`, `\a`, `\r`, otherwise `\xNN`); a tab, and a carriage return ending a CRLF line, stay as they are. When an added line holds one, the diff ends with `note: the new text holds control characters, shown escaped above (\f is U+000C, a form feed). In JSON, "\f" IS a form feed: …`. The file itself is written as sent. |
80+| Form feeds (U+000C) | In a source file (`.go`, `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.py`, `.rs`, `.java`, `.kt`, `.swift`, `.c`, `.h`, `.cc`, `.cpp`, `.hpp`, `.cs`, `.rb`, `.php`, `.lua`, `.zig`, `.scala`, `.dart`, `.sh`) that holds no form feed yet, a form feed that starts a line before a lowercase letter — `"\n\func"` in the JSON arguments, which JSON reads as a new line, a form feed and `unc` — is written as a new line and `f` (a blank line, then `func`), or as `f` alone after an indentation or at the very start. The output then ends with `[mm: repaired N form feed(s) (U+000C) at the start of a line, in …]` and the user sees a `🩹` notice. Never changed: a form feed alone on its line (a page break), one inside a line, one before anything but a lowercase letter, any form feed in another kind of file or in a file that already holds one. |
79 | ACP | Kind `edit`; permission requested; the change travels as a diff (new-file diff when created). |81 | ACP | Kind `edit`; permission requested; the change travels as a diff (new-file diff when created). |
80 82
81 ## `edit_file`83 ## `edit_file`
@@ -88,13 +90,13 @@ Declared when `editTools: true`.
88 | `edits` | array of `{old, new, line}` | — | Replacements, all resolved against the original file. |90 | `edits` | array of `{old, new, line}` | — | Replacements, all resolved against the original file. |
89 | `edits[].old` | string | — | Exact text to find, present exactly once. Whitespace is forgiven — see *How `old` is matched*. |91 | `edits[].old` | string | — | Exact text to find, present exactly once. Whitespace is forgiven — see *How `old` is matched*. |
90 | `edits[].new` | string | — | Replacement; empty deletes the matched text. |92 | `edits[].new` | string | — | Replacement; empty deletes the matched text. |
91-| `edits[].line` | integer | — | Only when `old` appears several times: the 1-based line where the occurrence to change starts, as `read_file` with `numbered: true` shows it. Ignored when `old` is unique. A line where no occurrence starts is refused: `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. |93+| `edits[].line` | integer | — | Only when `old` appears several times: the 1-based line where the occurrence to change starts, as `read_file` with `numbered: true` shows it. Ignored when `old` is unique, as long as it is inside the file. A line where no occurrence starts is refused: `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. A line outside the file — past its last line, or below 1 — is refused whether `old` is unique or not: `edit #1: "line": 1000000000000000 is outside the file, which has 42 line(s) — "line" is only needed when old appears several times; leave it out, or give the line where old starts, as read_file numbered=true shows it`. |
92 | `dry_run` | bool | `false` | Report what would change, write nothing. |94 | `dry_run` | bool | `false` | Report what would change, write nothing. |
93 95
94 | Rule | Consequence when broken |96 | Rule | Consequence when broken |
95 |------|-------------------------|97 |------|-------------------------|
96 | `old` appears exactly once, or `line` picks one | Refused: not found, or ambiguous — `old text appears N times (lines 11, 20) — to change ONE of them, add "line": the number of the line where it starts (one of 11, 20); or include its surrounding lines in old until the text is unique; to change several, send one edit per place…`. |98 | `old` appears exactly once, or `line` picks one | Refused: not found, or ambiguous — `old text appears N times (lines 11, 20) — to change ONE of them, add "line": the number of the line where it starts (one of 11, 20); or include its surrounding lines in old until the text is unique; to change several, send one edit per place…`. |
97-| `old` and `new` identical | Not an error when the file holds `old`: that edit is reported as already done (` · N already as asked (identical old and new)`; `<path>: unchanged — already as asked: …` when it is the only one) and the other edits apply. When the file does not hold it: not found. |99+| `old` and `new` identical | Not an error when the file holds `old`: that edit is reported as already done (` · N already as asked (identical old and new)`; `<path>: unchanged — already as asked: …` when it is the only one) and the other edits apply. When the file does not hold it: not found. A call that changes nothing at all is a failed call for the loop detector (see [Loop detection](#loop-detection)). |
98 | Two edits must not overlap, nest or repeat | Refused. |100 | Two edits must not overlap, nest or repeat | Refused. |
99 | Edits are resolved against the original text, never in cascade | — |101 | Edits are resolved against the original text, never in cascade | — |
100 | Any refused edit | Nothing is written. |102 | Any refused edit | Nothing is written. |
@@ -102,6 +104,8 @@ Declared when `editTools: true`.
102 | Aspect | Behaviour |104 | Aspect | Behaviour |
103 |--------|-----------|105 |--------|-----------|
104 | Output | A one-line headline (edits applied, lines added and deleted, first changed line, and ` · N matched ignoring whitespace` when any edit needed a relaxed match) and the diff with line numbers. |106 | Output | A one-line headline (edits applied, lines added and deleted, first changed line, and ` · N matched ignoring whitespace` when any edit needed a relaxed match) and the diff with line numbers. |
107+| Control characters in the diff | As for `write_file`. |
108+| Form feeds (U+000C) | Repaired as for `write_file`, in each edit's `new` text only — never in `old`, which must match the file as it is; the note names the edit (`edit #2 new text, line(s) 4`). |
105 | ACP | Kind `edit`; permission requested; the change travels as a diff with old and new text. |109 | ACP | Kind `edit`; permission requested; the change travels as a diff with old and new text. |
106 110
107 ### How `old` is matched111 ### How `old` is matched
@@ -147,14 +151,14 @@ Declared when `planTool: true` (the default). Turns a list of tasks into a plan
147 | `name` | string | The plan. For `create`, optional: a plan without a name is called `user-request-N` (N counts the conversation's plans). For the other actions, optional too: without it, the action works on the conversation's most recently created plan (`list` ignores it). |151 | `name` | string | The plan. For `create`, optional: a plan without a name is called `user-request-N` (N counts the conversation's plans). For the other actions, optional too: without it, the action works on the conversation's most recently created plan (`list` ignores it). |
148 | `tasks` | list of `{description, id?}` | For `create`: the tasks, in order. A task without an `id` gets its position (1, 2, …). Ignored by the other actions. |152 | `tasks` | list of `{description, id?}` | For `create`: the tasks, in order. A task without an `id` gets its position (1, 2, …). Ignored by the other actions. |
149 | `taskId` | integer | For `update`: the task, from 1. |153 | `taskId` | integer | For `update`: the task, from 1. |
150-| `status` | string | For `update`: `open`, `in_progress`, `done` or `failed`. |154+| `status` | string | For `update`: `done`, `failed`, `in_progress` or `open`. Absent means `done`. |
151 | `message` | string | For `update`: a note kept on the task. |155 | `message` | string | For `update`: a note kept on the task. |
152 156
153 | Action | Does | Result (JSON text) |157 | Action | Does | Result (JSON text) |
154 |--------|------|--------------------|158 |--------|------|--------------------|
155 | `create` | Creates the plan, every task `open`. Refused when the name is taken. | `result` (`Plan '<name>' created with N tasks. Current: Task 1`), `planName`, `status`, `current`, `total`; in the line mode, also the whole `plan`. |159 | `create` | Creates the plan, every task `open`. Refused when the name is taken. | `result` (`Plan '<name>' created with N tasks. Current: Task 1`), `planName`, `status`, `current`, `total`; in the line mode, also the whole `plan`. |
156 | `get` | Reads one plan. | `result`, `plan` (name, tasks with id, description, status, start and end times, note). |160 | `get` | Reads one plan. | `result`, `plan` (name, tasks with id, description, status, start and end times, note). |
157-| `update` | Sets one task's status; `in_progress` records its start time (once) and makes it the current task, `done` and `failed` record its end time. | `result`, `status` (the status line, below). |161+| `update` | Sets one task's status; `in_progress` records its start time (once) and makes it the current task, `done` and `failed` record its end time. Without `status` and without `tasks`, the task is marked `done`. | `result` — ending with ` (no status given: taken as done)` when `status` was absent —, `status` (the status line, below). |
158 | `next` | Marks the current task `done` and starts the next one that is neither done nor failed (`in_progress`); a task already finished with `update` is skipped. | `result` (`Task N done. Next: Task M - <description>`, or `Plan '<name>' is complete! All N tasks done.`), `status`, `nextTask` when there is one. |162 | `next` | Marks the current task `done` and starts the next one that is neither done nor failed (`in_progress`); a task already finished with `update` is skipped. | `result` (`Task N done. Next: Task M - <description>`, or `Plan '<name>' is complete! All N tasks done.`), `status`, `nextTask` when there is one. |
159 | `list` | Lists the plans held. | `result`, `plans` (names, oldest first). |163 | `list` | Lists the plans held. | `result`, `plans` (names, oldest first). |
160 | `delete` | Removes a plan. | `result`. |164 | `delete` | Removes a plan. | `result`. |
@@ -163,7 +167,8 @@ Declared when `planTool: true` (the default). Turns a list of tasks into a plan
163 | Aspect | Behaviour |167 | Aspect | Behaviour |
164 |--------|-----------|168 |--------|-----------|
165 | Status line | `[C/N] <icon> Task C: <description> (<status>)` for the task being worked on — the first one in progress, else the first one still open —, `[N/N] Plan finished: D done, F failed` when every task is over and some failed, `[N/N] All tasks complete!` when all are done. Icons: ⏳ open, 🔄 in progress, ✅ done, ❌ failed. |169 | Status line | `[C/N] <icon> Task C: <description> (<status>)` for the task being worked on — the first one in progress, else the first one still open —, `[N/N] Plan finished: D done, F failed` when every task is over and some failed, `[N/N] All tasks complete!` when all are done. Icons: ⏳ open, 🔄 in progress, ✅ done, ❌ failed. |
166-| Errors | Returned as text, never as a failed generation: `[error: no plans found for this session]`, `[error: no plan named '<name>' found]`, `[error: plan '<name>' already exists]`, `[error: no task with id N in plan '<name>']`, `[error: unknown action '<action>'. Valid actions: …]`. An `update` without a valid `status` quotes the call back, says that `tasks` is ignored by `update` when it was sent, and gives a call that works. |170+| Errors | Returned as text, never as a failed generation: `[error: no plans found for this session]`, `[error: no plan named '<name>' found]`, `[error: plan '<name>' already exists]`, `[error: no task with id N in plan '<name>']`, `[error: unknown action '<action>'. Valid actions: …]`. An `update` with a `status` that is not one of the four, or with `tasks` and no `status`, quotes the call back, says that `tasks` is ignored by `update` when it was sent, and gives a call that works. |
171+| Description | Asks for one `update` with `status: "done"` per finished task, no plan call between the steps of a task, and none once every task is done. `next` and `status` are still accepted. |
167 | Storage | In memory, per conversation: the line mode and the window hold one; over ACP each session has its own, and one thread never sees another's plans. Plans are not written to the session file and are lost when mm stops. A conversation that changes starts with no plan: `/new` and `/resume` in every front end, `session/load` and `session/resume` over ACP. |172 | Storage | In memory, per conversation: the line mode and the window hold one; over ACP each session has its own, and one thread never sees another's plans. Plans are not written to the session file and are lost when mm stops. A conversation that changes starts with no plan: `/new` and `/resume` in every front end, `session/load` and `session/resume` over ACP. |
168 | Permission | `create`, `update`, `next` and `delete` are requested when `yolo: false`; a refusal returns `[plan: command rejected by the user]`. `get`, `list` and `status` never ask. |173 | Permission | `create`, `update`, `next` and `delete` are requested when `yolo: false`; a refusal returns `[plan: command rejected by the user]`. `get`, `list` and `status` never ask. |
169 | Display | Line mode: `📋 plan: <action> <name>` before the call, then `📋 <status line>` after every action that has one (`create`, `update`, `next`, `status`). Window: the call as a tool call, and `📋 <status line>` as a notice. Editor (ACP): the call as a tool call, the status inside its result. The progress is shown by mm, whether or not the model repeats it. |174 | Display | Line mode: `📋 plan: <action> <name>` before the call, then `📋 <status line>` after every action that has one (`create`, `update`, `next`, `status`). Window: the call as a tool call, and `📋 <status line>` as a notice. Editor (ACP): the call as a tool call, the status inside its result. The progress is shown by mm, whether or not the model repeats it. |
@@ -188,7 +193,7 @@ Declared when `lsp.servers` lists at least one server whose command is on the `P
188 | `definition`, `references` | One `path:line:column <source line>` per location, sorted by path then position, duplicates removed; paths inside the project are relative, others absolute. `references` is prefixed with `N reference(s):` and includes the declaration. |193 | `definition`, `references` | One `path:line:column <source line>` per location, sorted by path then position, duplicates removed; paths inside the project are relative, others absolute. `references` is prefixed with `N reference(s):` and includes the declaration. |
189 | `hover` | The server's text as it sent it (signature, type, documentation; Markdown for most servers). |194 | `hover` | The server's text as it sent it (signature, type, documentation; Markdown for most servers). |
190 | `symbols` | One `<kind> <name> [<detail>] line N` per symbol, children indented two spaces. |195 | `symbols` | One `<kind> <name> [<detail>] line N` per symbol, children indented two spaces. |
191-| `diagnostics` | The file is synced, then the call waits up to 3 s for the server's publication. `N diagnostic(s) in <path>:` then one `<severity> path:line:column <message> [<source>]` per finding; `no diagnostics: <path> is clean`; ` (as last published)` when the file did not change since the server last spoke; `no diagnostics received for <path> within 3s (…)` when it never did. |196+| `diagnostics` | The file is synced, then the call waits up to 3 s for the server's publication. A publication with findings is taken at once. An empty one is taken once no other publication for the file came for 400 ms and the server reports no work in progress (`$/progress`; mm declares `window.workDoneProgress` at start-up): a server reloading its workspace may first publish an empty list. When the 3 s run out during such work, the answer is `no diagnostics yet for <path>, but the server is still loading the workspace — this does NOT mean the file is clean: ask again in a moment, or build it`. A server that answers `textDocument/diagnostic` is asked instead, and its answer is taken as it is. `N diagnostic(s) in <path>:` then one `<severity> path:line:column <message> [<source>]` per finding; `no diagnostics: <path> is clean`; ` (as last published)` when the file did not change since the server last spoke; `no diagnostics received for <path> within 3s (…)` when it never did. |
192 | `rename` | Applies the server's edits to the files on disk (UTF-16 positions converted), tells the server the new contents, and answers `renamed to <new>: N edit(s) in M file(s)` followed by one `path: N edit(s)` line per file. Without `new_name`: `[lsp: rename needs new_name — call lsp again with {"action": "rename", "path": …, "symbol": …, "new_name": "<the new identifier>"}; do not use edit_file for a rename]`. |197 | `rename` | Applies the server's edits to the files on disk (UTF-16 positions converted), tells the server the new contents, and answers `renamed to <new>: N edit(s) in M file(s)` followed by one `path: N edit(s)` line per file. Without `new_name`: `[lsp: rename needs new_name — call lsp again with {"action": "rename", "path": …, "symbol": …, "new_name": "<the new identifier>"}; do not use edit_file for a rename]`. |
193 | Positions | 1-based lines and columns at the tool's boundary, 0-based UTF-16 on the wire. A position past the end of a line or of the file is refused with the count. |198 | Positions | 1-based lines and columns at the tool's boundary, 0-based UTF-16 on the wire. A position past the end of a line or of the file is refused with the count. |
194 | File sync | Before every request the file is read from disk and sent as `didOpen` (first time) or a whole-document `didChange` (when its content moved): edits made with `edit_file` are seen without any extra step. |199 | File sync | Before every request the file is read from disk and sent as `didOpen` (first time) or a whole-document `didChange` (when its content moved): edits made with `edit_file` are seen without any extra step. |
@@ -473,12 +478,15 @@ Every tool records `(tool, input, output)` in the loop detector after each call.
473 | Situation | Behaviour |478 | Situation | Behaviour |
474 |-----------|-----------|479 |-----------|-----------|
475 | The same triple 3 times in a row | The tool's output gets `[LOOP_DETECTED: You have attempted the same action multiple times with the same result. Please try a different approach or provide more information.]` appended. Nothing stops. |480 | The same triple 3 times in a row | The tool's output gets `[LOOP_DETECTED: You have attempted the same action multiple times with the same result. Please try a different approach or provide more information.]` appended. Nothing stops. |
476-| 3 more identical calls after that (6 in a row) | The tool returns an error instead of text and the turn ends: `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. The history keeps everything that ran; the error is recorded in the session file's `errors` array (`where: generation`). |481+| 3 more identical calls after that (6 in a row) | The tool calls stop. The calls of that reply are answered `[mm: not run — the loop detector stopped the tool calls]`, and the model is called once more, **without tools**, after `[mm: mm stopped your tool calls: <the detector's sentence>. No more tools in this turn. Give your final answer now: …]`; its answer ends the turn. When that call fails, calls a tool or brings no text, the turn ends with the error `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. The history keeps everything that ran; that error is recorded in the session file's `errors` array (`where: generation`). |
482+| A `write_file` or `edit_file` that changes nothing | Recorded as a **failed** call (identical content; every edit with `old` equal to `new`): the rule for failed calls below flags it once it was recorded 3 times among the last 10 calls, reads in between included. A dry run is not a failure. |
477 | A different call | The count starts again. `/new` resets the detector; `/compact` does not. |483 | A different call | The count starts again. `/new` resets the detector; `/compact` does not. |
478 | The same call failing again with other calls in between | A **failed** call (same tool, input and output) already recorded 3 times among the last 10 calls is flagged, whatever came in between, and the turn stops at its third flag. Successful calls keep the consecutive rule: reading a file again is not a loop. |484 | The same call failing again with other calls in between | A **failed** call (same tool, input and output) already recorded 3 times among the last 10 calls is flagged, whatever came in between, and the turn stops at its third flag. Successful calls keep the consecutive rule: reading a file again is not a loop. |
479 | A tool call whose streamed arguments repeat a pattern (the last 256 characters are one 4–64-character pattern repeated) or exceed 256 KB | The generation is stopped at once: `[error: the model's tool call ran away: its arguments repeat the same pattern (N characters so far: …) — generation stopped; rephrase the request, or try another model]`. Without it a derailed model composes garbage for minutes while the screen shows "Thinking" (the watchdog is fed by every delta). While a tool call streams, the spinner says `Composing a tool call`. |485 | A tool call whose streamed arguments repeat a pattern (the last 256 characters are one 4–64-character pattern repeated) or exceed 256 KB | The generation is stopped at once: `[error: the model's tool call ran away: its arguments repeat the same pattern (N characters so far: …) — generation stopped; rephrase the request, or try another model]`. Without it a derailed model composes garbage for minutes while the screen shows "Thinking" (the watchdog is fed by every delta). While a tool call streams, the spinner says `Composing a tool call`. |
480 486
481-The thresholds (3, then 3 more) are set in `main.go`; `maxTurns` remains the outer bound of a turn.487+| The same `bash` test run again | A `bash` call whose command and output have the same shape as 2 earlier calls since the last `write_file` / `edit_file` that changed a file gets `[mm: this is the same test, with the same result, for the 3rd time since the last file change — sleeps, timeouts and kills aside. …]` at the end of its output, and the user sees `same test again: bash ×N with the same result, no file changed`; from the 3rd, at every new one. Shape of the command: `pkill`, `kill`, `killall`, `sleep`, `wait`, `true` and `:` commands dropped, a `timeout …` prefix, redirections and a trailing `&` removed, every number written `N`. Shape of the output: numbers of 4 digits or more and decimals written `N`, spacing evened out — `000` and `200` stay different. Never stops the turn. |
488+
489+The thresholds (3, then 3 more; 3 for similar `bash` calls) are set in `main.go`; `maxTurns` remains the outer bound of a turn.
482 490
483 ## Counters shown after a turn491 ## Counters shown after a turn
484 492
modified docs/fr/explanation/lsp-tool.md +12 -0
@@ -18,6 +18,18 @@ La même idée gouverne les réponses : chaque emplacement revient sous la forme
1818
1919 Un éditeur informe son serveur de chaque frappe. `mm` n'a pas de frappes : le modèle édite avec `edit_file`, et le fichier sur disque est la vérité. Avant chaque requête, le client relit donc le fichier et envoie son contenu — `didOpen` la première fois, un `didChange` du document entier quand il a bougé depuis — et le serveur répond toujours sur ce que le modèle vient d'écrire. Rien d'autre n'a à penser à prévenir qui que ce soit.
2020
21+## Pourquoi mm prévient le serveur quand go.mod change
22+
23+Synchroniser le fichier ne suffit pas quand ce qui a changé est le projet autour. Un serveur lit ses modules et ses dépendances dans des fichiers comme `go.mod`, `go.sum` ou `package.json`, et il n'apprend qu'ils ont changé que si le client le lui dit, avec `workspace/didChangeWatchedFiles`. Un éditeur surveille le disque pour ça ; `mm` ne le faisait pas, et le modèle modifie ces fichiers avec `bash` : `go get`, `go mod tidy`, `npm install`. Le 2026-12-05, Mellum2.1 a lancé `go get gopkg.in/yaml.v3`, la compilation passait, et gopls a continué de répondre `could not import gopkg.in/yaml.v3` après chaque édition. Le modèle a dépensé ses appels en `go mod tidy`, `go list -m` et relectures de `go.mod`, à chercher une erreur qui n'existait plus.
24+
25+Avant chaque synchronisation, mm regarde donc les fichiers de workspace du dossier du fichier et de chaque dossier au-dessus jusqu'à la racine du projet (un module Go peut être dans un sous-dossier) : `go.mod`, `go.sum`, `go.work`, `go.work.sum`, `package.json`, `package-lock.json`, `tsconfig.json`, `jsconfig.json`, `Cargo.toml`, `Cargo.lock`, `pyproject.toml`, `requirements.txt`. Il compare leur date de modification et leur taille avec ce qu'il a vu la dernière fois, et envoie une seule notification avec ce qui a été créé, modifié ou supprimé. Puis il synchronise le fichier. Ça coûte une douzaine de `stat` par requête. Les diagnostics que mm ajoute à `read_file` suivent la même règle : une relecture ne rappelle les dernières erreurs que tant que ni le fichier ni ses fichiers de workspace n'ont changé ; sinon mm redemande au serveur. Rejeté : surveiller toute l'arborescence (coûteux, et les fichiers de code sont synchronisés de toute façon), et redémarrer le serveur après un appel `bash` (lent, et il perd son cache).
26+
27+## Pourquoi une liste de diagnostics vide n'est pas crue tout de suite
28+
29+Un serveur publie ses diagnostics quand il le veut ; mm attend la publication qui suit sa synchronisation. Longtemps, il a pris la première. Le 2026-12-02, c'était faux : Mellum2 a créé le premier `go.mod` du workspace, puis édité trois fichiers avec des imports faux, et chaque édition a reçu `clean` alors que `go build` signalait toutes les erreurs. La cause déduite — non reproduite avec un gopls au cache chaud — est un serveur qui recharge son workspace et publie une liste vide avant sa vraie réponse. Un faux `clean` est pire que rien : le modèle croit que du code cassé compile.
30+
31+Les deux sortes de réponse ne sont donc pas traitées pareil. Des erreurs sont prises tout de suite : elles ne sont jamais un faux `clean`. Une liste vide n'est prise qu'une fois restée seule un court moment (400 ms) et quand le serveur dit qu'il ne charge rien — mm déclare désormais `window.workDoneProgress`, si bien que les serveurs signalent leur travail « Loading packages… » par `$/progress`. Si l'attente s'épuise alors que le serveur est encore occupé, la réponse le dit au lieu de `clean`. Un fichier propre coûte ces 400 ms ; un fichier cassé ne coûte rien de plus. Rejeté : attendre une seconde fixe après chaque publication (plus lent à chaque édition, et toujours faux pour un long chargement), et compiler le projet pour vérifier (c'est le travail du modèle, par `bash`).
32+
2133 ## Pourquoi `rename` écrit lui-même les fichiers, et demande d'abord
2234
2335 Un renommage est un `WorkspaceEdit` : des plages à remplacer dans plusieurs fichiers. Le client les applique sur disque — de la fin de chaque fichier vers le début pour que les positions antérieures restent valides, les colonnes UTF-16 converties en octets — puis resynchronise les fichiers changés pour que la question suivante porte sur le code renommé. Dans le terminal il s'exécute comme `edit_file` ; là où une façade a une boîte de permission (avec `yolo: false` : le mode ligne, la fenêtre, un éditeur en ACP) il demande, parce qu'il écrit, alors que les cinq actions de navigation ne demandent pas : une boîte à chaque lecture apprend aux gens à cliquer « autoriser » sans lire.
@@ -18,6 +18,18 @@ La même idée gouverne les réponses : chaque emplacement revient sous la forme
18 18
19 Un éditeur informe son serveur de chaque frappe. `mm` n'a pas de frappes : le modèle édite avec `edit_file`, et le fichier sur disque est la vérité. Avant chaque requête, le client relit donc le fichier et envoie son contenu — `didOpen` la première fois, un `didChange` du document entier quand il a bougé depuis — et le serveur répond toujours sur ce que le modèle vient d'écrire. Rien d'autre n'a à penser à prévenir qui que ce soit.19 Un éditeur informe son serveur de chaque frappe. `mm` n'a pas de frappes : le modèle édite avec `edit_file`, et le fichier sur disque est la vérité. Avant chaque requête, le client relit donc le fichier et envoie son contenu — `didOpen` la première fois, un `didChange` du document entier quand il a bougé depuis — et le serveur répond toujours sur ce que le modèle vient d'écrire. Rien d'autre n'a à penser à prévenir qui que ce soit.
20 20
21+## Pourquoi mm prévient le serveur quand go.mod change
22+
23+Synchroniser le fichier ne suffit pas quand ce qui a changé est le projet autour. Un serveur lit ses modules et ses dépendances dans des fichiers comme `go.mod`, `go.sum` ou `package.json`, et il n'apprend qu'ils ont changé que si le client le lui dit, avec `workspace/didChangeWatchedFiles`. Un éditeur surveille le disque pour ça ; `mm` ne le faisait pas, et le modèle modifie ces fichiers avec `bash` : `go get`, `go mod tidy`, `npm install`. Le 2026-12-05, Mellum2.1 a lancé `go get gopkg.in/yaml.v3`, la compilation passait, et gopls a continué de répondre `could not import gopkg.in/yaml.v3` après chaque édition. Le modèle a dépensé ses appels en `go mod tidy`, `go list -m` et relectures de `go.mod`, à chercher une erreur qui n'existait plus.
24+
25+Avant chaque synchronisation, mm regarde donc les fichiers de workspace du dossier du fichier et de chaque dossier au-dessus jusqu'à la racine du projet (un module Go peut être dans un sous-dossier) : `go.mod`, `go.sum`, `go.work`, `go.work.sum`, `package.json`, `package-lock.json`, `tsconfig.json`, `jsconfig.json`, `Cargo.toml`, `Cargo.lock`, `pyproject.toml`, `requirements.txt`. Il compare leur date de modification et leur taille avec ce qu'il a vu la dernière fois, et envoie une seule notification avec ce qui a été créé, modifié ou supprimé. Puis il synchronise le fichier. Ça coûte une douzaine de `stat` par requête. Les diagnostics que mm ajoute à `read_file` suivent la même règle : une relecture ne rappelle les dernières erreurs que tant que ni le fichier ni ses fichiers de workspace n'ont changé ; sinon mm redemande au serveur. Rejeté : surveiller toute l'arborescence (coûteux, et les fichiers de code sont synchronisés de toute façon), et redémarrer le serveur après un appel `bash` (lent, et il perd son cache).
26+
27+## Pourquoi une liste de diagnostics vide n'est pas crue tout de suite
28+
29+Un serveur publie ses diagnostics quand il le veut ; mm attend la publication qui suit sa synchronisation. Longtemps, il a pris la première. Le 2026-12-02, c'était faux : Mellum2 a créé le premier `go.mod` du workspace, puis édité trois fichiers avec des imports faux, et chaque édition a reçu `clean` alors que `go build` signalait toutes les erreurs. La cause déduite — non reproduite avec un gopls au cache chaud — est un serveur qui recharge son workspace et publie une liste vide avant sa vraie réponse. Un faux `clean` est pire que rien : le modèle croit que du code cassé compile.
30+
31+Les deux sortes de réponse ne sont donc pas traitées pareil. Des erreurs sont prises tout de suite : elles ne sont jamais un faux `clean`. Une liste vide n'est prise qu'une fois restée seule un court moment (400 ms) et quand le serveur dit qu'il ne charge rien — mm déclare désormais `window.workDoneProgress`, si bien que les serveurs signalent leur travail « Loading packages… » par `$/progress`. Si l'attente s'épuise alors que le serveur est encore occupé, la réponse le dit au lieu de `clean`. Un fichier propre coûte ces 400 ms ; un fichier cassé ne coûte rien de plus. Rejeté : attendre une seconde fixe après chaque publication (plus lent à chaque édition, et toujours faux pour un long chargement), et compiler le projet pour vérifier (c'est le travail du modèle, par `bash`).
32+
21 ## Pourquoi `rename` écrit lui-même les fichiers, et demande d'abord33 ## Pourquoi `rename` écrit lui-même les fichiers, et demande d'abord
22 34
23 Un renommage est un `WorkspaceEdit` : des plages à remplacer dans plusieurs fichiers. Le client les applique sur disque — de la fin de chaque fichier vers le début pour que les positions antérieures restent valides, les colonnes UTF-16 converties en octets — puis resynchronise les fichiers changés pour que la question suivante porte sur le code renommé. Dans le terminal il s'exécute comme `edit_file` ; là où une façade a une boîte de permission (avec `yolo: false` : le mode ligne, la fenêtre, un éditeur en ACP) il demande, parce qu'il écrit, alors que les cinq actions de navigation ne demandent pas : une boîte à chaque lecture apprend aux gens à cliquer « autoriser » sans lire.35 Un renommage est un `WorkspaceEdit` : des plages à remplacer dans plusieurs fichiers. Le client les applique sur disque — de la fin de chaque fichier vers le début pour que les positions antérieures restent valides, les colonnes UTF-16 converties en octets — puis resynchronise les fichiers changés pour que la question suivante porte sur le code renommé. Dans le terminal il s'exécute comme `edit_file` ; là où une façade a une boîte de permission (avec `yolo: false` : le mode ligne, la fenêtre, un éditeur en ACP) il demande, parce qu'il écrit, alors que les cinq actions de navigation ne demandent pas : une boîte à chaque lecture apprend aux gens à cliquer « autoriser » sans lire.
modified docs/fr/explanation/struggling-models.md +11 -1
@@ -24,6 +24,16 @@ Les signaux de difficulté (ticket 153) rendent ces mêmes détections visibles
2424
2525 **Réparer plutôt que refuser.** Certaines erreurs ne peuvent vouloir dire qu'une chose : `"true"` pour `true`, `old_text` pour `old`, un chemin auquel il manque un répertoire. mm les répare et le dit dans la sortie de l'outil, plutôt que de refuser en espérant que le modèle corrige — des refus qui citaient le bon chemin ont, mesuré, fait boucler un petit modèle. Voir les [outils](../reference/tools.md#arguments-qui-ne-respectent-pas-le-schéma-dun-outil) et [`workspace`](../reference/configuration.md#clés-de-workspace).
2626
27+**Des retours d'outils qui ne doivent pas tromper** (v2.2.2, tickets 294–300 et 307). Les runs de validation du 2026-12-02 avec Mellum2, Mellum2.1 et Qwen3-Coder-Next ont moins échoué sur leur tâche que sur ce que les outils leur disaient. Un appel de diagnostics répondait `clean` sur des fichiers qui ne compilaient pas, si bien que le modèle croyait ses imports faux ; une édition avec `old` égal à `new`, envoyée douze fois entre des lectures, était un succès à chaque fois, si bien qu'aucune règle ne voyait de boucle ; une `line` de 1000000000000000 était acceptée ; un saut de page écrit pour `\f` était invisible dans le diff. Les corrections suivent une règle : la réponse d'un outil doit être vraie et visible, ou dire qu'elle n'est pas sûre. Une liste de diagnostics vide n'est crue qu'une fois stabilisée, une édition qui ne change rien compte comme un échec pour le détecteur de boucles, une ligne hors du fichier est refusée, les caractères de contrôle sont affichés échappés, et les erreurs sont rappelées quand un fichier cassé est relu. Un rappel peut être vrai et pourtant inutile : le 2026-12-04, Mellum2.1 Thinking savait qu'il fallait retirer le `}` en trop de la ligne 142, mais a relu le fichier huit fois sans le modifier, parce que `}` n'est pas unique comme ancien texte d'une édition. Alors, à partir du deuxième rappel, mm cesse de répéter le constat et dit quoi faire : la ligne telle que le fichier la contient, et l'appel `edit_file`, avec `line`, qui la change.
28+
29+**Finir sur une réponse, pas sur une erreur.** Trois runs sur quatre ce jour-là se sont terminés sur de la comptabilité, le travail fait : un `plan update` sans son statut, répété jusqu'à ce que le détecteur de boucles arrête le tour — en erreur, sans réponse. Un texte répété était déjà rendu pour obtenir une réponse ; un appel d'outil répété l'est désormais aussi : les appels arrêtés reçoivent « not run » et on demande une fois au modèle, sans outils, sa réponse finale. Un statut de plan absent vaut maintenant `done`, la seule chose que puisse vouloir dire un modèle qui l'omet, et la description de l'outil demande un seul update par tâche.
30+
31+**Des réponses dégénérées, reconnues comme des boucles.** Une phrase suivie de milliers de lignes vides jusqu'à la limite de tokens était signalée comme « raise max_tokens » — le mauvais conseil, puisqu'une limite plus grande n'achète que davantage de lignes vides. C'est désormais une boucle : coupée pendant le flux, rendue une fois, et réduite dans la réponse. Un appel d'outil écrit dans le raisonnement, sans rien d'autre dans la réponse, terminait le tour en silence ; il est rendu une fois avec l'appel cité, et rien du raisonnement n'est jamais exécuté — l'exécuter donnerait au raisonnement, que l'utilisateur peut ne pas voir, le pouvoir d'agir.
32+
33+**Un conseil, jamais un arrêt, pour un test relancé.** Un modèle qui relance le même test avec d'autres sleeps et timeouts tourne en rond, mais un modèle qui le relance après une modification fait ce qu'il faut, et les deux ne diffèrent que par un fichier modifié entre-temps. Les commandes `bash` semblables depuis la dernière modification de fichier reçoivent donc une note qui demande au modèle de lire le code — et le tour n'est jamais arrêté sur la seule ressemblance.
34+
35+**Réparer ce que le modèle a demandé d'écrire.** La réparation des sauts de page est le seul endroit où mm modifie le contenu qu'un modèle a demandé d'écrire ; elle a donc été étudiée avant d'être écrite : toutes les occurrences des traces avaient la même forme (un saut de page en début de ligne, devant `unc`), les sauts de page légitimes ont d'autres formes (un saut de page seul sur sa ligne), et la réparation se limite aux fichiers source qui n'en contiennent pas encore, au nouveau texte seulement, et elle est toujours signalée.
36+
2737 ## Alternatives écartées
2838
2939 - **L'en-tête.** Envisagé ; l'utilisateur a choisi la barre d'état, ce qui garde l'en-tête pour qui répond et le remplissage du contexte.
@@ -31,4 +41,4 @@ Les signaux de difficulté (ticket 153) rendent ces mêmes détections visibles
3141
3242 ## Liens avec le reste
3343
34-Les détections elles-mêmes ne changent pas : le détecteur de boucles dit toujours au modèle de changer d'approche et arrête toujours le tour après six appels identiques ; le watchdog, le garde-fou contre l'emballement et la note après un appel cassé se comportent comme avant. Ce que renvoie le tour et ce que garde l'historique ne changent pas non plus — une difficulté est montrée, jamais enregistrée. Voir aussi la [compression du contexte](context-compression.md), qu'un avertissement `context N% full` précède souvent, et les [modèles à raisonnement](thinking-models.md) pour savoir pourquoi le watchdog reste nourri pendant qu'un modèle réfléchit.
44+Les détections elles-mêmes ne changent pas : le détecteur de boucles dit toujours au modèle de changer d'approche et arrête toujours les appels d'outils après six appels identiques — le modèle donne alors sa réponse sans outils ; le watchdog, le garde-fou contre l'emballement et la note après un appel cassé se comportent comme avant. Ce que renvoie le tour et ce que garde l'historique ne changent pas non plus — une difficulté est montrée, jamais enregistrée. Voir aussi la [compression du contexte](context-compression.md), qu'un avertissement `context N% full` précède souvent, et les [modèles à raisonnement](thinking-models.md) pour savoir pourquoi le watchdog reste nourri pendant qu'un modèle réfléchit.
@@ -24,6 +24,16 @@ Les signaux de difficulté (ticket 153) rendent ces mêmes détections visibles
24 24
25 **Réparer plutôt que refuser.** Certaines erreurs ne peuvent vouloir dire qu'une chose : `"true"` pour `true`, `old_text` pour `old`, un chemin auquel il manque un répertoire. mm les répare et le dit dans la sortie de l'outil, plutôt que de refuser en espérant que le modèle corrige — des refus qui citaient le bon chemin ont, mesuré, fait boucler un petit modèle. Voir les [outils](../reference/tools.md#arguments-qui-ne-respectent-pas-le-schéma-dun-outil) et [`workspace`](../reference/configuration.md#clés-de-workspace).25 **Réparer plutôt que refuser.** Certaines erreurs ne peuvent vouloir dire qu'une chose : `"true"` pour `true`, `old_text` pour `old`, un chemin auquel il manque un répertoire. mm les répare et le dit dans la sortie de l'outil, plutôt que de refuser en espérant que le modèle corrige — des refus qui citaient le bon chemin ont, mesuré, fait boucler un petit modèle. Voir les [outils](../reference/tools.md#arguments-qui-ne-respectent-pas-le-schéma-dun-outil) et [`workspace`](../reference/configuration.md#clés-de-workspace).
26 26
27+**Des retours d'outils qui ne doivent pas tromper** (v2.2.2, tickets 294–300 et 307). Les runs de validation du 2026-12-02 avec Mellum2, Mellum2.1 et Qwen3-Coder-Next ont moins échoué sur leur tâche que sur ce que les outils leur disaient. Un appel de diagnostics répondait `clean` sur des fichiers qui ne compilaient pas, si bien que le modèle croyait ses imports faux ; une édition avec `old` égal à `new`, envoyée douze fois entre des lectures, était un succès à chaque fois, si bien qu'aucune règle ne voyait de boucle ; une `line` de 1000000000000000 était acceptée ; un saut de page écrit pour `\f` était invisible dans le diff. Les corrections suivent une règle : la réponse d'un outil doit être vraie et visible, ou dire qu'elle n'est pas sûre. Une liste de diagnostics vide n'est crue qu'une fois stabilisée, une édition qui ne change rien compte comme un échec pour le détecteur de boucles, une ligne hors du fichier est refusée, les caractères de contrôle sont affichés échappés, et les erreurs sont rappelées quand un fichier cassé est relu. Un rappel peut être vrai et pourtant inutile : le 2026-12-04, Mellum2.1 Thinking savait qu'il fallait retirer le `}` en trop de la ligne 142, mais a relu le fichier huit fois sans le modifier, parce que `}` n'est pas unique comme ancien texte d'une édition. Alors, à partir du deuxième rappel, mm cesse de répéter le constat et dit quoi faire : la ligne telle que le fichier la contient, et l'appel `edit_file`, avec `line`, qui la change.
28+
29+**Finir sur une réponse, pas sur une erreur.** Trois runs sur quatre ce jour-là se sont terminés sur de la comptabilité, le travail fait : un `plan update` sans son statut, répété jusqu'à ce que le détecteur de boucles arrête le tour — en erreur, sans réponse. Un texte répété était déjà rendu pour obtenir une réponse ; un appel d'outil répété l'est désormais aussi : les appels arrêtés reçoivent « not run » et on demande une fois au modèle, sans outils, sa réponse finale. Un statut de plan absent vaut maintenant `done`, la seule chose que puisse vouloir dire un modèle qui l'omet, et la description de l'outil demande un seul update par tâche.
30+
31+**Des réponses dégénérées, reconnues comme des boucles.** Une phrase suivie de milliers de lignes vides jusqu'à la limite de tokens était signalée comme « raise max_tokens » — le mauvais conseil, puisqu'une limite plus grande n'achète que davantage de lignes vides. C'est désormais une boucle : coupée pendant le flux, rendue une fois, et réduite dans la réponse. Un appel d'outil écrit dans le raisonnement, sans rien d'autre dans la réponse, terminait le tour en silence ; il est rendu une fois avec l'appel cité, et rien du raisonnement n'est jamais exécuté — l'exécuter donnerait au raisonnement, que l'utilisateur peut ne pas voir, le pouvoir d'agir.
32+
33+**Un conseil, jamais un arrêt, pour un test relancé.** Un modèle qui relance le même test avec d'autres sleeps et timeouts tourne en rond, mais un modèle qui le relance après une modification fait ce qu'il faut, et les deux ne diffèrent que par un fichier modifié entre-temps. Les commandes `bash` semblables depuis la dernière modification de fichier reçoivent donc une note qui demande au modèle de lire le code — et le tour n'est jamais arrêté sur la seule ressemblance.
34+
35+**Réparer ce que le modèle a demandé d'écrire.** La réparation des sauts de page est le seul endroit où mm modifie le contenu qu'un modèle a demandé d'écrire ; elle a donc été étudiée avant d'être écrite : toutes les occurrences des traces avaient la même forme (un saut de page en début de ligne, devant `unc`), les sauts de page légitimes ont d'autres formes (un saut de page seul sur sa ligne), et la réparation se limite aux fichiers source qui n'en contiennent pas encore, au nouveau texte seulement, et elle est toujours signalée.
36+
27 ## Alternatives écartées37 ## Alternatives écartées
28 38
29 - **L'en-tête.** Envisagé ; l'utilisateur a choisi la barre d'état, ce qui garde l'en-tête pour qui répond et le remplissage du contexte.39 - **L'en-tête.** Envisagé ; l'utilisateur a choisi la barre d'état, ce qui garde l'en-tête pour qui répond et le remplissage du contexte.
@@ -31,4 +41,4 @@ Les signaux de difficulté (ticket 153) rendent ces mêmes détections visibles
31 41
32 ## Liens avec le reste42 ## Liens avec le reste
33 43
34-Les détections elles-mêmes ne changent pas : le détecteur de boucles dit toujours au modèle de changer d'approche et arrête toujours le tour après six appels identiques ; le watchdog, le garde-fou contre l'emballement et la note après un appel cassé se comportent comme avant. Ce que renvoie le tour et ce que garde l'historique ne changent pas non plus — une difficulté est montrée, jamais enregistrée. Voir aussi la [compression du contexte](context-compression.md), qu'un avertissement `context N% full` précède souvent, et les [modèles à raisonnement](thinking-models.md) pour savoir pourquoi le watchdog reste nourri pendant qu'un modèle réfléchit.44+Les détections elles-mêmes ne changent pas : le détecteur de boucles dit toujours au modèle de changer d'approche et arrête toujours les appels d'outils après six appels identiques — le modèle donne alors sa réponse sans outils ; le watchdog, le garde-fou contre l'emballement et la note après un appel cassé se comportent comme avant. Ce que renvoie le tour et ce que garde l'historique ne changent pas non plus — une difficulté est montrée, jamais enregistrée. Voir aussi la [compression du contexte](context-compression.md), qu'un avertissement `context N% full` précède souvent, et les [modèles à raisonnement](thinking-models.md) pour savoir pourquoi le watchdog reste nourri pendant qu'un modèle réfléchit.
modified docs/fr/how-to/manage-plans-and-tasks.md +3 -3
@@ -10,7 +10,7 @@ Demandez plusieurs choses à la fois, sous forme de liste :
1010 Do these 2 things: 1. create a file a.txt containing A, 2. create a file b.txt containing B.
1111 ```
1212
13-Le modèle crée un plan à partir de la liste, le suit, et met à jour le statut de chaque tâche au fur et à mesure. Les petits modèles le font plus sûrement quand on le leur dit : « Use the plan tool. Do these… ».
13+Le modèle crée un plan à partir de la liste, le suit, et marque chaque tâche faite quand il la termine — un seul `update` par tâche, c'est tout ce que demande la description de l'outil. Les petits modèles le font plus sûrement quand on le leur dit : « Use the plan tool. Do these… ».
1414
1515 ## Suivre la progression
1616
@@ -49,13 +49,13 @@ Il n'y a pas de commande slash pour les plans : c'est l'outil du modèle.
4949
5050 - **Plusieurs conversations dans un éditeur.** Chaque fil a ses propres plans : un plan créé dans un fil de Zed n'est pas visible dans un autre.
5151 - **Repartir de zéro.** `/new` et `/resume` oublient les plans dans toutes les façades ; un rechargement depuis l'éditeur (`session/load`, `session/resume`) démarre le fil sans plan. Les plans ne sont gardés qu'en mémoire, jamais dans le fichier de session, et sont perdus à l'arrêt de mm.
52-- **Le skill `plan-manager`.** `skills/plan-manager` dit au modèle quand faire un plan et comment le parcourir. Mettez-le dans le `skillsDir` de l'agent pour un modèle qui n'utilise pas l'outil de lui-même. Il demande aussi au modèle de reprendre la ligne de statut dans sa réponse ; mm l'affiche de toute façon.
52+- **Le skill `plan-manager`.** `skills/plan-manager` dit au modèle quand faire un plan et avec combien peu d'appels : un `create`, puis un `update` avec `status: done` par tâche terminée — le même déroulé que la description de l'outil. Mettez-le dans le `skillsDir` de l'agent pour un modèle qui n'utilise pas l'outil de lui-même.
5353 - **Un agent qui n'a pas besoin de plans.** Mettez `planTool: false` : l'outil n'est pas déclaré. Faites-le pour un agent dont le travail est une réponse unique (écrire un document, répondre à des questions), où un petit modèle pourrait sinon boucler sur des appels au plan.
5454
5555 ## Dépannage
5656
5757 - **L'agent ne crée pas de plan.** Donnez une liste numérotée, et dites « use the plan tool ». Avec un petit modèle, ajoutez le skill `plan-manager`.
58-- **L'agent appelle `plan update` en boucle.** `update` change le statut d'UNE tâche ; il ne peut pas changer les tâches d'un plan. Un appel sans `status` valide reçoit une réponse qui reprend l'appel, nomme le champ manquant et donne un appel valide. Si un petit modèle le répète quand même, mettez `planTool: false` pour cet agent.
58+- **L'agent appelle `plan update` en boucle.** `update` change le statut d'UNE tâche ; il ne peut pas changer les tâches d'un plan. Un `update` sans `status` marque la tâche faite ; un `update` avec `tasks` et sans `status`, ou avec un statut inconnu, reçoit une réponse qui reprend l'appel et donne un appel valide. Si un petit modèle répète quand même le même appel, le détecteur de boucles arrête ses appels d'outils au sixième et lui demande sa réponse finale : le travail déjà fait est donc quand même rapporté. Pour éviter toute cette comptabilité, mettez `planTool: false` pour cet agent.
5959
6060 ## Voir aussi
6161
@@ -10,7 +10,7 @@ Demandez plusieurs choses à la fois, sous forme de liste :
10 Do these 2 things: 1. create a file a.txt containing A, 2. create a file b.txt containing B.10 Do these 2 things: 1. create a file a.txt containing A, 2. create a file b.txt containing B.
11 ```11 ```
12 12
13-Le modèle crée un plan à partir de la liste, le suit, et met à jour le statut de chaque tâche au fur et à mesure. Les petits modèles le font plus sûrement quand on le leur dit : « Use the plan tool. Do these… ».13+Le modèle crée un plan à partir de la liste, le suit, et marque chaque tâche faite quand il la termine — un seul `update` par tâche, c'est tout ce que demande la description de l'outil. Les petits modèles le font plus sûrement quand on le leur dit : « Use the plan tool. Do these… ».
14 14
15 ## Suivre la progression15 ## Suivre la progression
16 16
@@ -49,13 +49,13 @@ Il n'y a pas de commande slash pour les plans : c'est l'outil du modèle.
49 49
50 - **Plusieurs conversations dans un éditeur.** Chaque fil a ses propres plans : un plan créé dans un fil de Zed n'est pas visible dans un autre.50 - **Plusieurs conversations dans un éditeur.** Chaque fil a ses propres plans : un plan créé dans un fil de Zed n'est pas visible dans un autre.
51 - **Repartir de zéro.** `/new` et `/resume` oublient les plans dans toutes les façades ; un rechargement depuis l'éditeur (`session/load`, `session/resume`) démarre le fil sans plan. Les plans ne sont gardés qu'en mémoire, jamais dans le fichier de session, et sont perdus à l'arrêt de mm.51 - **Repartir de zéro.** `/new` et `/resume` oublient les plans dans toutes les façades ; un rechargement depuis l'éditeur (`session/load`, `session/resume`) démarre le fil sans plan. Les plans ne sont gardés qu'en mémoire, jamais dans le fichier de session, et sont perdus à l'arrêt de mm.
52-- **Le skill `plan-manager`.** `skills/plan-manager` dit au modèle quand faire un plan et comment le parcourir. Mettez-le dans le `skillsDir` de l'agent pour un modèle qui n'utilise pas l'outil de lui-même. Il demande aussi au modèle de reprendre la ligne de statut dans sa réponse ; mm l'affiche de toute façon.52+- **Le skill `plan-manager`.** `skills/plan-manager` dit au modèle quand faire un plan et avec combien peu d'appels : un `create`, puis un `update` avec `status: done` par tâche terminée — le même déroulé que la description de l'outil. Mettez-le dans le `skillsDir` de l'agent pour un modèle qui n'utilise pas l'outil de lui-même.
53 - **Un agent qui n'a pas besoin de plans.** Mettez `planTool: false` : l'outil n'est pas déclaré. Faites-le pour un agent dont le travail est une réponse unique (écrire un document, répondre à des questions), où un petit modèle pourrait sinon boucler sur des appels au plan.53 - **Un agent qui n'a pas besoin de plans.** Mettez `planTool: false` : l'outil n'est pas déclaré. Faites-le pour un agent dont le travail est une réponse unique (écrire un document, répondre à des questions), où un petit modèle pourrait sinon boucler sur des appels au plan.
54 54
55 ## Dépannage55 ## Dépannage
56 56
57 - **L'agent ne crée pas de plan.** Donnez une liste numérotée, et dites « use the plan tool ». Avec un petit modèle, ajoutez le skill `plan-manager`.57 - **L'agent ne crée pas de plan.** Donnez une liste numérotée, et dites « use the plan tool ». Avec un petit modèle, ajoutez le skill `plan-manager`.
58-- **L'agent appelle `plan update` en boucle.** `update` change le statut d'UNE tâche ; il ne peut pas changer les tâches d'un plan. Un appel sans `status` valide reçoit une réponse qui reprend l'appel, nomme le champ manquant et donne un appel valide. Si un petit modèle le répète quand même, mettez `planTool: false` pour cet agent.58+- **L'agent appelle `plan update` en boucle.** `update` change le statut d'UNE tâche ; il ne peut pas changer les tâches d'un plan. Un `update` sans `status` marque la tâche faite ; un `update` avec `tasks` et sans `status`, ou avec un statut inconnu, reçoit une réponse qui reprend l'appel et donne un appel valide. Si un petit modèle répète quand même le même appel, le détecteur de boucles arrête ses appels d'outils au sixième et lui demande sa réponse finale : le travail déjà fait est donc quand même rapporté. Pour éviter toute cette comptabilité, mettez `planTool: false` pour cet agent.
59 59
60 ## Voir aussi60 ## Voir aussi
61 61
modified docs/fr/how-to/navigate-code-with-lsp.md +2 -1
@@ -100,7 +100,7 @@ Les petits modèles appellent rarement `diagnostics` d'eux-mêmes. Deux réglage
100100 ```yaml
101101 lsp:
102102 diagnosticsAfterEdit: true # après chaque write_file / edit_file réussi
103- diagnosticsAfterRead: true # avec chaque read_file, une fois par version du fichier
103+ diagnosticsAfterRead: true # avec chaque read_file : une fois par version, erreurs rappelées à la relecture, puis la correction indiquée
104104 servers:
105105 - name: gopls
106106 command: gopls
@@ -119,6 +119,7 @@ Rien à configurer : le même YAML s'applique. Les appels de navigation apparais
119119 - **Un serveur avec des réglages.** Passez-les en `args` (beaucoup de serveurs lisent un drapeau ou un fichier de configuration à la racine du projet) ; `mm` répond « pas de réglages » à un serveur qui demande sa configuration, qui tourne alors avec ses valeurs par défaut.
120120 - **Positions exactes.** Quand le modèle a une position exacte — via `read_file` avec `numbered=true` — il peut envoyer `line` et `column` (base 1, dans l'identifiant) au lieu de `symbol`. `symbol` est la voie fiable : les petits modèles comptent rarement les colonnes juste.
121121 - **Aucun serveur sur cette machine.** L'outil n'est pas déclaré et la bannière dit `lsp: none of the configured servers is on the PATH — the lsp tool is not declared`. La configuration peut rester ; l'agent fonctionne sans.
122+- **Dépendances ajoutées par `bash`.** Après `go get`, `go mod tidy` ou `npm install`, rien à faire : mm prévient le serveur que `go.mod`, `go.sum`, `package.json`… ont changé avant sa requête suivante, et les diagnostics suivants sont calculés avec les nouvelles dépendances. Voir [pourquoi](../explanation/lsp-tool.md#pourquoi-mm-prévient-le-serveur-quand-gomod-change).
122123 - **Première réponse lente.** Le premier appel pour un langage démarre le serveur et le laisse indexer le projet ; `diagnostics` peut dire `as last published` ou `no diagnostics received … within 3s` — redemandez une fois.
123124
124125 ## Voir aussi
@@ -100,7 +100,7 @@ Les petits modèles appellent rarement `diagnostics` d'eux-mêmes. Deux réglage
100 ```yaml100 ```yaml
101 lsp:101 lsp:
102 diagnosticsAfterEdit: true # après chaque write_file / edit_file réussi102 diagnosticsAfterEdit: true # après chaque write_file / edit_file réussi
103- diagnosticsAfterRead: true # avec chaque read_file, une fois par version du fichier103+ diagnosticsAfterRead: true # avec chaque read_file : une fois par version, erreurs rappelées à la relecture, puis la correction indiquée
104 servers:104 servers:
105 - name: gopls105 - name: gopls
106 command: gopls106 command: gopls
@@ -119,6 +119,7 @@ Rien à configurer : le même YAML s'applique. Les appels de navigation apparais
119 - **Un serveur avec des réglages.** Passez-les en `args` (beaucoup de serveurs lisent un drapeau ou un fichier de configuration à la racine du projet) ; `mm` répond « pas de réglages » à un serveur qui demande sa configuration, qui tourne alors avec ses valeurs par défaut.119 - **Un serveur avec des réglages.** Passez-les en `args` (beaucoup de serveurs lisent un drapeau ou un fichier de configuration à la racine du projet) ; `mm` répond « pas de réglages » à un serveur qui demande sa configuration, qui tourne alors avec ses valeurs par défaut.
120 - **Positions exactes.** Quand le modèle a une position exacte — via `read_file` avec `numbered=true` — il peut envoyer `line` et `column` (base 1, dans l'identifiant) au lieu de `symbol`. `symbol` est la voie fiable : les petits modèles comptent rarement les colonnes juste.120 - **Positions exactes.** Quand le modèle a une position exacte — via `read_file` avec `numbered=true` — il peut envoyer `line` et `column` (base 1, dans l'identifiant) au lieu de `symbol`. `symbol` est la voie fiable : les petits modèles comptent rarement les colonnes juste.
121 - **Aucun serveur sur cette machine.** L'outil n'est pas déclaré et la bannière dit `lsp: none of the configured servers is on the PATH — the lsp tool is not declared`. La configuration peut rester ; l'agent fonctionne sans.121 - **Aucun serveur sur cette machine.** L'outil n'est pas déclaré et la bannière dit `lsp: none of the configured servers is on the PATH — the lsp tool is not declared`. La configuration peut rester ; l'agent fonctionne sans.
122+- **Dépendances ajoutées par `bash`.** Après `go get`, `go mod tidy` ou `npm install`, rien à faire : mm prévient le serveur que `go.mod`, `go.sum`, `package.json`… ont changé avant sa requête suivante, et les diagnostics suivants sont calculés avec les nouvelles dépendances. Voir [pourquoi](../explanation/lsp-tool.md#pourquoi-mm-prévient-le-serveur-quand-gomod-change).
122 - **Première réponse lente.** Le premier appel pour un langage démarre le serveur et le laisse indexer le projet ; `diagnostics` peut dire `as last published` ou `no diagnostics received … within 3s` — redemandez une fois.123 - **Première réponse lente.** Le premier appel pour un langage démarre le serveur et le laisse indexer le projet ; `diagnostics` peut dire `as last published` ou `no diagnostics received … within 3s` — redemandez une fois.
123 124
124 ## Voir aussi125 ## Voir aussi
modified docs/fr/reference/cli.md +6 -2
@@ -204,10 +204,13 @@ Les signes que le modèle peine, montrés à l'utilisateur à part de la répons
204204 | Signal | Niveau | Quand |
205205 |--------|--------|-------|
206206 | `loop: <outil> ×N` | ⚠ | le détecteur de boucles a repéré le même appel avec le même résultat N fois de suite ; le modèle est invité à changer d'approche |
207-| `stuck: <outil> ×N` | ✖ | le modèle a ignoré ce conseil : le détecteur de boucles a arrêté le tour |
208-| `looped — handed back 1/1` | ⚠ | la même phrase (12 caractères ou plus) est revenue 20 fois de suite dans le raisonnement ou la réponse du modèle pendant le flux : cet appel au modèle est coupé et rendu une fois, avec une note qui dit au modèle qu'il se répétait |
207+| `stuck: <outil> ×N` | ✖ | le modèle a ignoré ce conseil : le détecteur de boucles a arrêté ses appels d'outils |
208+| `loop detector stop — asked for the answer` | ⚠ | après cet arrêt, le modèle est appelé une fois de plus sans outils pour sa réponse finale (le tour ne finit en erreur que si elle ne vient pas) |
209+| `same test again: <outil> ×N with the same result, no file changed` | ⚠ | une commande `bash` lancée pour la Ne fois (N ≥ 3) avec la même forme et le même résultat depuis la dernière modification de fichier ; on dit au modèle de lire le code plutôt ; n'arrête jamais le tour |
210+| `looped — handed back 1/1` | ⚠ | la même phrase (12 caractères ou plus) est revenue 20 fois de suite dans le raisonnement ou la réponse du modèle pendant le flux, ou 100 lignes vides de suite : cet appel au modèle est coupé et rendu une fois, avec une note qui dit au modèle qu'il se répétait (ou écrivait des lignes vides) |
209211 | `looped — stopped` | ✖ | il a bouclé de nouveau : le tour se termine par `the model looped: "…" repeated N times in a row — stopped; ask again, or lower the temperature / reasoning effort` |
210212 | `reasoning cut at the limit 1/1` | ⚠ | une réponse s'est arrêtée à la limite de tokens avec seulement du raisonnement — ni texte ni appel d'outil ; elle est rendue une fois, en demandant au modèle d'agir tout de suite |
213+| `tool call in the reasoning — handed back 1/1` | ⚠ | une réponse sans texte ni appel d'outil dont le raisonnement contient un bloc `<tool_call>` complet : elle est rendue une fois, en citant le bloc — rien de ce qui est écrit dans le raisonnement n'est exécuté. Une fois par occurrence : après une réponse avec un vrai appel d'outil, une nouvelle occurrence est rendue à nouveau |
211214 | `answer after a failed <outil> — handed back 1/1` | ⚠ | le modèle a donné sa réponse finale alors que le dernier `write_file` / `edit_file` du tour avait échoué ; la réponse est rendue une fois avec une note : le fichier n'a pas été modifié, corrige l'appel ou dis-le |
212215 | `failing: N tool calls in a row` | ⚠ | les N derniers appels d'outil (N ≥ 3) ont tous échoué, avec des entrées différentes — code de sortie non nul, modification refusée, fichier absent, permission rejetée… ; signalé de nouveau à chaque nouvel échec, remis à zéro au premier succès ; le modèle n'en est pas informé |
213216 | `broken tool call (cut off\|invalid JSON) n/m` | ⚠ | les arguments d'un appel d'outil ne se lisent pas ; l'appel est rendu au modèle (essai n sur m) |
@@ -219,6 +222,7 @@ Les signes que le modèle peine, montrés à l'utilisateur à part de la répons
219222 | `empty answer` | ⚠ | le tour s'est terminé sans texte ni appel d'outil |
220223 | `empty answer — the model reasoned until the limit (<clé> N): raise sampling.<clé>, or lower its reasoning effort` | ✖ | la réponse rendue ci-dessus a de nouveau été coupée à la limite |
221224 | `the model looped: the same line repeated N times — the answer is cut there` | ✖ | la réponse finale contient 20 lignes identiques ou plus à la suite : elles sont réduites à une ligne suivie de `[… the same line repeated N more times — removed by mm]`, dans la réponse et dans l'historique ; ` (it ran until the limit: <clé>)` est ajouté quand elle a aussi atteint la limite de tokens |
225+| `the model looped: N blank lines in a row — removed from the answer` | ✖ | la réponse finale contient 40 lignes vides de suite ou plus : elles sont remplacées par `[… N blank lines — removed by mm]`, dans la réponse et dans l'historique ; ` (it ran until the limit: a larger <clé> would not help)` s'ajoute quand elle a aussi atteint la limite de tokens |
222226 | `answer cut at the limit (<clé> N): raise sampling.<clé>, or ask for a shorter answer` | ⚠ | la réponse s'est arrêtée en cours de route à la limite de tokens (`max_tokens` ou `max_completion_tokens`) |
223227 | `the last <outil> failed (…) — that change was not made, whatever the answer says` | ✖ | le dernier `write_file` / `edit_file` du tour a échoué, sans réussite après lui — toujours le cas après la note ci-dessus |
224228 | `context N% full` | ⚠ | le dernier appel au modèle a lu 80 % de la fenêtre de contexte ou plus (fenêtre connue uniquement) |
@@ -204,10 +204,13 @@ Les signes que le modèle peine, montrés à l'utilisateur à part de la répons
204 | Signal | Niveau | Quand |204 | Signal | Niveau | Quand |
205 |--------|--------|-------|205 |--------|--------|-------|
206 | `loop: <outil> ×N` | ⚠ | le détecteur de boucles a repéré le même appel avec le même résultat N fois de suite ; le modèle est invité à changer d'approche |206 | `loop: <outil> ×N` | ⚠ | le détecteur de boucles a repéré le même appel avec le même résultat N fois de suite ; le modèle est invité à changer d'approche |
207-| `stuck: <outil> ×N` | ✖ | le modèle a ignoré ce conseil : le détecteur de boucles a arrêté le tour |207+| `stuck: <outil> ×N` | ✖ | le modèle a ignoré ce conseil : le détecteur de boucles a arrêté ses appels d'outils |
208-| `looped — handed back 1/1` | ⚠ | la même phrase (12 caractères ou plus) est revenue 20 fois de suite dans le raisonnement ou la réponse du modèle pendant le flux : cet appel au modèle est coupé et rendu une fois, avec une note qui dit au modèle qu'il se répétait |208+| `loop detector stop — asked for the answer` | ⚠ | après cet arrêt, le modèle est appelé une fois de plus sans outils pour sa réponse finale (le tour ne finit en erreur que si elle ne vient pas) |
209+| `same test again: <outil> ×N with the same result, no file changed` | ⚠ | une commande `bash` lancée pour la Ne fois (N ≥ 3) avec la même forme et le même résultat depuis la dernière modification de fichier ; on dit au modèle de lire le code plutôt ; n'arrête jamais le tour |
210+| `looped — handed back 1/1` | ⚠ | la même phrase (12 caractères ou plus) est revenue 20 fois de suite dans le raisonnement ou la réponse du modèle pendant le flux, ou 100 lignes vides de suite : cet appel au modèle est coupé et rendu une fois, avec une note qui dit au modèle qu'il se répétait (ou écrivait des lignes vides) |
209 | `looped — stopped` | ✖ | il a bouclé de nouveau : le tour se termine par `the model looped: "…" repeated N times in a row — stopped; ask again, or lower the temperature / reasoning effort` |211 | `looped — stopped` | ✖ | il a bouclé de nouveau : le tour se termine par `the model looped: "…" repeated N times in a row — stopped; ask again, or lower the temperature / reasoning effort` |
210 | `reasoning cut at the limit 1/1` | ⚠ | une réponse s'est arrêtée à la limite de tokens avec seulement du raisonnement — ni texte ni appel d'outil ; elle est rendue une fois, en demandant au modèle d'agir tout de suite |212 | `reasoning cut at the limit 1/1` | ⚠ | une réponse s'est arrêtée à la limite de tokens avec seulement du raisonnement — ni texte ni appel d'outil ; elle est rendue une fois, en demandant au modèle d'agir tout de suite |
213+| `tool call in the reasoning — handed back 1/1` | ⚠ | une réponse sans texte ni appel d'outil dont le raisonnement contient un bloc `<tool_call>` complet : elle est rendue une fois, en citant le bloc — rien de ce qui est écrit dans le raisonnement n'est exécuté. Une fois par occurrence : après une réponse avec un vrai appel d'outil, une nouvelle occurrence est rendue à nouveau |
211 | `answer after a failed <outil> — handed back 1/1` | ⚠ | le modèle a donné sa réponse finale alors que le dernier `write_file` / `edit_file` du tour avait échoué ; la réponse est rendue une fois avec une note : le fichier n'a pas été modifié, corrige l'appel ou dis-le |214 | `answer after a failed <outil> — handed back 1/1` | ⚠ | le modèle a donné sa réponse finale alors que le dernier `write_file` / `edit_file` du tour avait échoué ; la réponse est rendue une fois avec une note : le fichier n'a pas été modifié, corrige l'appel ou dis-le |
212 | `failing: N tool calls in a row` | ⚠ | les N derniers appels d'outil (N ≥ 3) ont tous échoué, avec des entrées différentes — code de sortie non nul, modification refusée, fichier absent, permission rejetée… ; signalé de nouveau à chaque nouvel échec, remis à zéro au premier succès ; le modèle n'en est pas informé |215 | `failing: N tool calls in a row` | ⚠ | les N derniers appels d'outil (N ≥ 3) ont tous échoué, avec des entrées différentes — code de sortie non nul, modification refusée, fichier absent, permission rejetée… ; signalé de nouveau à chaque nouvel échec, remis à zéro au premier succès ; le modèle n'en est pas informé |
213 | `broken tool call (cut off\|invalid JSON) n/m` | ⚠ | les arguments d'un appel d'outil ne se lisent pas ; l'appel est rendu au modèle (essai n sur m) |216 | `broken tool call (cut off\|invalid JSON) n/m` | ⚠ | les arguments d'un appel d'outil ne se lisent pas ; l'appel est rendu au modèle (essai n sur m) |
@@ -219,6 +222,7 @@ Les signes que le modèle peine, montrés à l'utilisateur à part de la répons
219 | `empty answer` | ⚠ | le tour s'est terminé sans texte ni appel d'outil |222 | `empty answer` | ⚠ | le tour s'est terminé sans texte ni appel d'outil |
220 | `empty answer — the model reasoned until the limit (<clé> N): raise sampling.<clé>, or lower its reasoning effort` | ✖ | la réponse rendue ci-dessus a de nouveau été coupée à la limite |223 | `empty answer — the model reasoned until the limit (<clé> N): raise sampling.<clé>, or lower its reasoning effort` | ✖ | la réponse rendue ci-dessus a de nouveau été coupée à la limite |
221 | `the model looped: the same line repeated N times — the answer is cut there` | ✖ | la réponse finale contient 20 lignes identiques ou plus à la suite : elles sont réduites à une ligne suivie de `[… the same line repeated N more times — removed by mm]`, dans la réponse et dans l'historique ; ` (it ran until the limit: <clé>)` est ajouté quand elle a aussi atteint la limite de tokens |224 | `the model looped: the same line repeated N times — the answer is cut there` | ✖ | la réponse finale contient 20 lignes identiques ou plus à la suite : elles sont réduites à une ligne suivie de `[… the same line repeated N more times — removed by mm]`, dans la réponse et dans l'historique ; ` (it ran until the limit: <clé>)` est ajouté quand elle a aussi atteint la limite de tokens |
225+| `the model looped: N blank lines in a row — removed from the answer` | ✖ | la réponse finale contient 40 lignes vides de suite ou plus : elles sont remplacées par `[… N blank lines — removed by mm]`, dans la réponse et dans l'historique ; ` (it ran until the limit: a larger <clé> would not help)` s'ajoute quand elle a aussi atteint la limite de tokens |
222 | `answer cut at the limit (<clé> N): raise sampling.<clé>, or ask for a shorter answer` | ⚠ | la réponse s'est arrêtée en cours de route à la limite de tokens (`max_tokens` ou `max_completion_tokens`) |226 | `answer cut at the limit (<clé> N): raise sampling.<clé>, or ask for a shorter answer` | ⚠ | la réponse s'est arrêtée en cours de route à la limite de tokens (`max_tokens` ou `max_completion_tokens`) |
223 | `the last <outil> failed (…) — that change was not made, whatever the answer says` | ✖ | le dernier `write_file` / `edit_file` du tour a échoué, sans réussite après lui — toujours le cas après la note ci-dessus |227 | `the last <outil> failed (…) — that change was not made, whatever the answer says` | ✖ | le dernier `write_file` / `edit_file` du tour a échoué, sans réussite après lui — toujours le cas après la note ci-dessus |
224 | `context N% full` | ⚠ | le dernier appel au modèle a lu 80 % de la fenêtre de contexte ou plus (fenêtre connue uniquement) |228 | `context N% full` | ⚠ | le dernier appel au modèle a lu 80 % de la fenêtre de contexte ou plus (fenêtre connue uniquement) |
modified docs/fr/reference/configuration.md +1 -1
@@ -196,7 +196,7 @@ a2a:
196196 | `lsp.servers[].args` | liste de chaînes | `[]` | Ses arguments (beaucoup de serveurs veulent `--stdio`). |
197197 | `lsp.servers[].extensions` | liste de chaînes | — | Les extensions de fichier qu'il sert, avec le point (`.go`, `.ts`). Obligatoire, au moins une ; comparaison insensible à la casse ; une extension ne peut être servie que par un serveur. |
198198 | `lsp.diagnosticsAfterEdit` | booléen | `false` | Après un `write_file` ou un `edit_file` réussi sur un fichier qu'un serveur gère, demande à ce serveur les diagnostics du fichier et les ajoute à la sortie de l'outil sous `[lsp diagnostics after this change]`. Le serveur est démarré si besoin ; il a 8 s pour répondre, sinon la note dit `not available — <raison>` (la modification elle-même a réussi). Les petits modèles demandent rarement les diagnostics d'eux-mêmes : 0 fois en 54 exécutions dans `demos/gemma-coder`. |
199-| `lsp.diagnosticsAfterRead` | booléen | `false` | Après un `read_file` réussi d'un fichier qu'un serveur gère, ajoute les diagnostics de ce serveur pour tout le fichier sous `[lsp diagnostics for this file, added by mm — not part of its content]`. Une fois par version du fichier (date de modification et taille) : le relire inchangé, ou juste après une modification qui a déjà apporté ses diagnostics, ne demande rien. Même délai de 8 s que `diagnosticsAfterEdit`. |
199+| `lsp.diagnosticsAfterRead` | booléen | `false` | Après un `read_file` réussi d'un fichier qu'un serveur gère, ajoute les diagnostics de ce serveur pour tout le fichier sous `[lsp diagnostics for this file, added by mm — not part of its content]`. Une fois par version du fichier (date de modification et taille) : le relire inchangé, ou juste après une modification qui a déjà apporté ses diagnostics, ne demande rien — et n'ajoute rien pour un fichier propre, mais un court rappel quand cette version avait des erreurs : `[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still N error(s)]` suivi des 3 premières lignes `error …` et de `… and M more`. À partir du deuxième rappel de la même version, une note suit : `[mm: you have read <chemin> N times since it last changed, and the error has not moved …]`, avec le texte de la ligne de la première erreur et un appel `edit_file` qui utilise `line` (son `new` reprend l'ancien texte, à corriger par le modèle — jamais une suppression toute prête) (🔁 à l'écran) ; le compte repart de zéro quand le fichier change. Même délai de 8 s que `diagnosticsAfterEdit`. |
200200
201201 ```yaml
202202 lsp:
@@ -196,7 +196,7 @@ a2a:
196 | `lsp.servers[].args` | liste de chaînes | `[]` | Ses arguments (beaucoup de serveurs veulent `--stdio`). |196 | `lsp.servers[].args` | liste de chaînes | `[]` | Ses arguments (beaucoup de serveurs veulent `--stdio`). |
197 | `lsp.servers[].extensions` | liste de chaînes | — | Les extensions de fichier qu'il sert, avec le point (`.go`, `.ts`). Obligatoire, au moins une ; comparaison insensible à la casse ; une extension ne peut être servie que par un serveur. |197 | `lsp.servers[].extensions` | liste de chaînes | — | Les extensions de fichier qu'il sert, avec le point (`.go`, `.ts`). Obligatoire, au moins une ; comparaison insensible à la casse ; une extension ne peut être servie que par un serveur. |
198 | `lsp.diagnosticsAfterEdit` | booléen | `false` | Après un `write_file` ou un `edit_file` réussi sur un fichier qu'un serveur gère, demande à ce serveur les diagnostics du fichier et les ajoute à la sortie de l'outil sous `[lsp diagnostics after this change]`. Le serveur est démarré si besoin ; il a 8 s pour répondre, sinon la note dit `not available — <raison>` (la modification elle-même a réussi). Les petits modèles demandent rarement les diagnostics d'eux-mêmes : 0 fois en 54 exécutions dans `demos/gemma-coder`. |198 | `lsp.diagnosticsAfterEdit` | booléen | `false` | Après un `write_file` ou un `edit_file` réussi sur un fichier qu'un serveur gère, demande à ce serveur les diagnostics du fichier et les ajoute à la sortie de l'outil sous `[lsp diagnostics after this change]`. Le serveur est démarré si besoin ; il a 8 s pour répondre, sinon la note dit `not available — <raison>` (la modification elle-même a réussi). Les petits modèles demandent rarement les diagnostics d'eux-mêmes : 0 fois en 54 exécutions dans `demos/gemma-coder`. |
199-| `lsp.diagnosticsAfterRead` | booléen | `false` | Après un `read_file` réussi d'un fichier qu'un serveur gère, ajoute les diagnostics de ce serveur pour tout le fichier sous `[lsp diagnostics for this file, added by mm — not part of its content]`. Une fois par version du fichier (date de modification et taille) : le relire inchangé, ou juste après une modification qui a déjà apporté ses diagnostics, ne demande rien. Même délai de 8 s que `diagnosticsAfterEdit`. |199+| `lsp.diagnosticsAfterRead` | booléen | `false` | Après un `read_file` réussi d'un fichier qu'un serveur gère, ajoute les diagnostics de ce serveur pour tout le fichier sous `[lsp diagnostics for this file, added by mm — not part of its content]`. Une fois par version du fichier (date de modification et taille) : le relire inchangé, ou juste après une modification qui a déjà apporté ses diagnostics, ne demande rien — et n'ajoute rien pour un fichier propre, mais un court rappel quand cette version avait des erreurs : `[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still N error(s)]` suivi des 3 premières lignes `error …` et de `… and M more`. À partir du deuxième rappel de la même version, une note suit : `[mm: you have read <chemin> N times since it last changed, and the error has not moved …]`, avec le texte de la ligne de la première erreur et un appel `edit_file` qui utilise `line` (son `new` reprend l'ancien texte, à corriger par le modèle — jamais une suppression toute prête) (🔁 à l'écran) ; le compte repart de zéro quand le fichier change. Même délai de 8 s que `diagnosticsAfterEdit`. |
200 200
201 ```yaml201 ```yaml
202 lsp:202 lsp:
modified docs/fr/reference/tools.md +17 -9
@@ -74,8 +74,10 @@ Déclaré quand `editTools: true`.
7474 | Aspect | Comportement |
7575 |--------|--------------|
7676 | Fichier existant | Entièrement remplacé. |
77-| Contenu identique | Rien n'est écrit ; le résultat le dit. |
77+| Contenu identique | Rien n'est écrit ; le résultat le dit. Pour le détecteur de boucles, c'est un appel en échec (voir [Détection des boucles](#détection-de-boucle)). |
7878 | Sortie | Un en-tête d'une ligne et le diff par rapport au contenu précédent. |
79+| Caractères de contrôle dans le diff | Affichés échappés (`\f`, `\v`, `\b`, `\a`, `\r`, sinon `\xNN`) ; une tabulation, et un retour chariot qui termine une ligne CRLF, restent tels quels. Quand une ligne ajoutée en contient un, le diff se termine par `note: the new text holds control characters, shown escaped above (\f is U+000C, a form feed). In JSON, "\f" IS a form feed: …`. Le fichier lui-même est écrit tel qu'envoyé. |
80+| Sauts de page (U+000C) | Dans un fichier source (`.go`, `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.py`, `.rs`, `.java`, `.kt`, `.swift`, `.c`, `.h`, `.cc`, `.cpp`, `.hpp`, `.cs`, `.rb`, `.php`, `.lua`, `.zig`, `.scala`, `.dart`, `.sh`) qui ne contient pas encore de saut de page, un saut de page en début de ligne devant une lettre minuscule — `"\n\func"` dans les arguments JSON, que JSON lit comme un retour à la ligne, un saut de page et `unc` — est écrit comme un retour à la ligne et `f` (une ligne vide, puis `func`), ou comme `f` seul après une indentation ou tout au début. La sortie se termine alors par `[mm: repaired N form feed(s) (U+000C) at the start of a line, in …]` et l'utilisateur voit un avis `🩹`. Jamais modifié : un saut de page seul sur sa ligne (un saut de page de mise en forme), un saut de page au milieu d'une ligne, devant autre chose qu'une minuscule, dans un autre genre de fichier ou dans un fichier qui en contient déjà un. |
7981 | ACP | Genre `edit` ; permission demandée ; le changement voyage comme un diff (diff de nouveau fichier à la création). |
8082
8183 ## `edit_file`
@@ -88,13 +90,13 @@ Déclaré quand `editTools: true`.
8890 | `edits` | tableau de `{old, new, line}` | — | Remplacements, tous résolus par rapport au fichier original. |
8991 | `edits[].old` | chaîne | — | Texte exact à trouver, présent exactement une fois. Les espaces sont pardonnés — voir *Comment `old` est mis en correspondance*. |
9092 | `edits[].new` | chaîne | — | Remplacement ; vide supprime le texte trouvé. |
91-| `edits[].line` | entier | — | Seulement quand `old` apparaît plusieurs fois : la ligne (à partir de 1) où commence l'occurrence à changer, telle que `read_file` avec `numbered: true` l'affiche. Ignoré quand `old` est unique. Une ligne où ne commence aucune occurrence est refusée : `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. |
93+| `edits[].line` | entier | — | Seulement quand `old` apparaît plusieurs fois : la ligne (à partir de 1) où commence l'occurrence à changer, telle que `read_file` avec `numbered: true` l'affiche. Ignoré quand `old` est unique, tant qu'il est dans le fichier. Une ligne où ne commence aucune occurrence est refusée : `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. Une ligne hors du fichier — après sa dernière ligne, ou sous 1 — est refusée, que `old` soit unique ou non : `edit #1: "line": 1000000000000000 is outside the file, which has 42 line(s) — "line" is only needed when old appears several times; leave it out, or give the line where old starts, as read_file numbered=true shows it`. |
9294 | `dry_run` | booléen | `false` | Rapporte ce qui changerait, n'écrit rien. |
9395
9496 | Règle | Conséquence si violée |
9597 |-------|-----------------------|
9698 | `old` apparaît exactement une fois, ou `line` en désigne une | Refusé : introuvable, ou ambigu — `old text appears N times (lines 11, 20) — to change ONE of them, add "line": the number of the line where it starts (one of 11, 20); or include its surrounding lines in old until the text is unique; to change several, send one edit per place…`. |
97-| `old` et `new` identiques | Pas une erreur quand le fichier contient `old` : cette modification est signalée comme déjà faite (` · N already as asked (identical old and new)` ; `<chemin>: unchanged — already as asked: …` quand c'est la seule) et les autres s'appliquent. Quand le fichier ne le contient pas : introuvable. |
99+| `old` et `new` identiques | Pas une erreur quand le fichier contient `old` : cette modification est signalée comme déjà faite (` · N already as asked (identical old and new)` ; `<chemin>: unchanged — already as asked: …` quand c'est la seule) et les autres s'appliquent. Quand le fichier ne le contient pas : introuvable. Un appel qui ne change rien du tout est un appel en échec pour le détecteur de boucles (voir [Détection des boucles](#détection-de-boucle)). |
98100 | Deux éditions ne doivent ni se chevaucher, ni s'imbriquer, ni se répéter | Refus. |
99101 | Les éditions sont résolues sur le texte original, jamais en cascade | — |
100102 | Toute édition refusée | Rien n'est écrit. |
@@ -102,6 +104,8 @@ Déclaré quand `editTools: true`.
102104 | Aspect | Comportement |
103105 |--------|--------------|
104106 | Sortie | Un en-tête d'une ligne (éditions appliquées, lignes ajoutées et supprimées, première ligne modifiée, et ` · N matched ignoring whitespace` quand une édition a eu besoin d'une correspondance tolérante) et le diff avec numéros de ligne. |
107+| Caractères de contrôle dans le diff | Comme pour `write_file`. |
108+| Sauts de page (U+000C) | Réparés comme pour `write_file`, dans le texte `new` de chaque édition seulement — jamais dans `old`, qui doit correspondre au fichier tel qu'il est ; la note nomme l'édition (`edit #2 new text, line(s) 4`). |
105109 | ACP | Genre `edit` ; permission demandée ; le changement voyage comme un diff avec ancien et nouveau texte. |
106110
107111 ### Comment `old` est mis en correspondance
@@ -147,14 +151,14 @@ Déclaré quand `planTool: true` (le défaut). Transforme une liste de tâches e
147151 | `name` | chaîne | Le plan. Pour `create`, facultatif : un plan sans nom s'appelle `user-request-N` (N compte les plans de la conversation). Pour les autres actions, facultatif aussi : sans lui, l'action porte sur le dernier plan créé dans la conversation (`list` l'ignore). |
148152 | `tasks` | liste de `{description, id?}` | Pour `create` : les tâches, dans l'ordre. Une tâche sans `id` reçoit sa position (1, 2, …). Ignoré par les autres actions. |
149153 | `taskId` | entier | Pour `update` : la tâche, à partir de 1. |
150-| `status` | chaîne | Pour `update` : `open`, `in_progress`, `done` ou `failed`. |
154+| `status` | chaîne | Pour `update` : `done`, `failed`, `in_progress` ou `open`. Absent vaut `done`. |
151155 | `message` | chaîne | Pour `update` : une note gardée sur la tâche. |
152156
153157 | Action | Effet | Résultat (texte JSON) |
154158 |--------|-------|-----------------------|
155159 | `create` | Crée le plan, chaque tâche `open`. Refusé si le nom est déjà pris. | `result` (`Plan '<nom>' created with N tasks. Current: Task 1`), `planName`, `status`, `current`, `total` ; en mode ligne, aussi le `plan` entier. |
156160 | `get` | Lit un plan. | `result`, `plan` (nom, tâches avec id, description, statut, heures de début et de fin, note). |
157-| `update` | Fixe le statut d'une tâche ; `in_progress` enregistre son heure de début (une fois) et en fait la tâche courante, `done` et `failed` enregistrent son heure de fin. | `result`, `status` (la ligne de statut, ci-dessous). |
161+| `update` | Fixe le statut d'une tâche ; `in_progress` enregistre son heure de début (une fois) et en fait la tâche courante, `done` et `failed` enregistrent son heure de fin. Sans `status` et sans `tasks`, la tâche est marquée `done`. | `result` — terminé par ` (no status given: taken as done)` quand `status` était absent —, `status` (la ligne de statut, ci-dessous). |
158162 | `next` | Marque la tâche courante `done` et démarre la suivante qui n'est ni faite ni en échec (`in_progress`) ; une tâche déjà terminée avec `update` est sautée. | `result` (`Task N done. Next: Task M - <description>`, ou `Plan '<nom>' is complete! All N tasks done.`), `status`, `nextTask` s'il y en a une. |
159163 | `list` | Liste les plans existants. | `result`, `plans` (noms, du plus ancien au plus récent). |
160164 | `delete` | Supprime un plan. | `result`. |
@@ -163,7 +167,8 @@ Déclaré quand `planTool: true` (le défaut). Transforme une liste de tâches e
163167 | Aspect | Comportement |
164168 |--------|--------------|
165169 | Ligne de statut | `[C/N] <icône> Task C: <description> (<statut>)` pour la tâche en cours de travail — la première en cours, sinon la première encore ouverte —, `[N/N] Plan finished: D done, F failed` quand toutes les tâches sont terminées et que certaines ont échoué, `[N/N] All tasks complete!` quand toutes sont faites. Icônes : ⏳ ouverte, 🔄 en cours, ✅ faite, ❌ en échec. |
166-| Erreurs | Renvoyées comme texte, jamais comme un échec de génération : `[error: no plans found for this session]`, `[error: no plan named '<nom>' found]`, `[error: plan '<nom>' already exists]`, `[error: no task with id N in plan '<nom>']`, `[error: unknown action '<action>'. Valid actions: …]`. Un `update` sans `status` valide renvoie l'appel reçu, précise que `tasks` est ignoré par `update` quand il a été envoyé, et donne un appel qui fonctionne. |
170+| Erreurs | Renvoyées comme texte, jamais comme un échec de génération : `[error: no plans found for this session]`, `[error: no plan named '<nom>' found]`, `[error: plan '<nom>' already exists]`, `[error: no task with id N in plan '<nom>']`, `[error: unknown action '<action>'. Valid actions: …]`. Un `update` avec un `status` qui n'est pas l'un des quatre, ou avec `tasks` et sans `status`, renvoie l'appel reçu, précise que `tasks` est ignoré par `update` quand il a été envoyé, et donne un appel qui fonctionne. |
171+| Description | Demande un seul `update` avec `status: "done"` par tâche terminée, aucun appel au plan entre les étapes d'une tâche, et aucun une fois toutes les tâches faites. `next` et `status` restent acceptés. |
167172 | Stockage | En mémoire, par conversation : le mode ligne et la fenêtre en tiennent une ; en ACP chaque session a la sienne, et un fil ne voit jamais les plans d'un autre. Les plans ne sont pas écrits dans le fichier de session et sont perdus à l'arrêt de mm. Une conversation qui change repart sans plan : `/new` et `/resume` dans toutes les façades, `session/load` et `session/resume` en ACP. |
168173 | Permission | `create`, `update`, `next` et `delete` sont demandés quand `yolo: false` ; un refus renvoie `[plan: command rejected by the user]`. `get`, `list` et `status` ne demandent jamais. |
169174 | Affichage | Mode ligne : `📋 plan: <action> <nom>` avant l'appel, puis `📋 <ligne de statut>` après chaque action qui en a une (`create`, `update`, `next`, `status`). Fenêtre : l'appel comme appel d'outil, et `📋 <ligne de statut>` en notice. Éditeur (ACP) : l'appel comme appel d'outil, le statut dans son résultat. La progression est affichée par mm, que le modèle la reprenne ou non. |
@@ -188,7 +193,7 @@ Déclaré quand `lsp.servers` liste au moins un serveur dont la commande est sur
188193 | `definition`, `references` | Une ligne `chemin:ligne:colonne <ligne source>` par emplacement, triée par chemin puis position, doublons retirés ; les chemins du projet sont relatifs, les autres absolus. `references` est préfixé de `N reference(s):` et inclut la déclaration. |
189194 | `hover` | Le texte du serveur tel qu'envoyé (signature, type, documentation ; Markdown pour la plupart des serveurs). |
190195 | `symbols` | Une ligne `<sorte> <nom> [<détail>] line N` par symbole, enfants indentés de deux espaces. |
191-| `diagnostics` | Le fichier est synchronisé, puis l'appel attend jusqu'à 3 s la publication du serveur. `N diagnostic(s) in <chemin>:` puis une ligne `<sévérité> chemin:ligne:colonne <message> [<source>]` par constat ; `no diagnostics: <chemin> is clean` ; ` (as last published)` quand le fichier n'a pas changé depuis la dernière publication ; `no diagnostics received for <chemin> within 3s (…)` quand le serveur n'a jamais publié. |
196+| `diagnostics` | Le fichier est synchronisé, puis l'appel attend jusqu'à 3 s la publication du serveur. Une publication avec des constats est prise tout de suite. Une publication vide est prise une fois qu'aucune autre publication pour le fichier n'est venue pendant 400 ms et que le serveur ne signale aucun travail en cours (`$/progress` ; mm déclare `window.workDoneProgress` au démarrage) : un serveur qui recharge son workspace peut d'abord publier une liste vide. Quand les 3 s s'épuisent pendant un tel travail, la réponse est `no diagnostics yet for <chemin>, but the server is still loading the workspace — this does NOT mean the file is clean: ask again in a moment, or build it`. Un serveur qui répond à `textDocument/diagnostic` est interrogé à la place, et sa réponse est prise telle quelle. `N diagnostic(s) in <chemin>:` puis une ligne `<sévérité> chemin:ligne:colonne <message> [<source>]` par constat ; `no diagnostics: <chemin> is clean` ; ` (as last published)` quand le fichier n'a pas changé depuis la dernière publication ; `no diagnostics received for <chemin> within 3s (…)` quand le serveur n'a jamais publié. |
192197 | `rename` | Applique les modifications du serveur aux fichiers sur disque (positions UTF-16 converties), informe le serveur du nouveau contenu, et répond `renamed to <nouveau>: N edit(s) in M file(s)` suivi d'une ligne `chemin: N edit(s)` par fichier. Sans `new_name` : `[lsp: rename needs new_name — call lsp again with {"action": "rename", "path": …, "symbol": …, "new_name": "<the new identifier>"}; do not use edit_file for a rename]`. |
193198 | Positions | Lignes et colonnes en base 1 à la frontière de l'outil, UTF-16 en base 0 sur le fil. Une position au-delà de la fin d'une ligne ou du fichier est refusée, avec le compte. |
194199 | Synchronisation | Avant chaque requête, le fichier est relu sur disque et envoyé en `didOpen` (première fois) ou en `didChange` complet (quand son contenu a bougé) : les modifications faites avec `edit_file` sont vues sans étape supplémentaire. |
@@ -473,12 +478,15 @@ Chaque outil enregistre `(outil, entrée, sortie)` dans le détecteur de boucle
473478 | Situation | Comportement |
474479 |-----------|--------------|
475480 | Le même triplet 3 fois de suite | La sortie de l'outil reçoit `[LOOP_DETECTED: You have attempted the same action multiple times with the same result. Please try a different approach or provide more information.]` en annexe. Rien ne s'arrête. |
476-| 3 appels identiques de plus (6 de suite) | L'outil renvoie une erreur au lieu de texte et le tour se termine : `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. L'historique garde tout ce qui a tourné ; l'erreur est enregistrée dans le tableau `errors` du fichier de session (`where: generation`). |
481+| 3 appels identiques de plus (6 de suite) | Les appels d'outils s'arrêtent. Les appels de cette réponse reçoivent `[mm: not run — the loop detector stopped the tool calls]`, et le modèle est appelé une fois de plus, **sans outils**, après `[mm: mm stopped your tool calls: <la phrase du détecteur>. No more tools in this turn. Give your final answer now: …]` ; sa réponse termine le tour. Quand cet appel échoue, appelle un outil ou n'apporte aucun texte, le tour se termine sur l'erreur `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. L'historique garde tout ce qui a tourné ; cette erreur est enregistrée dans le tableau `errors` du fichier de session (`where: generation`). |
482+| Un `write_file` ou `edit_file` qui ne change rien | Enregistré comme un appel **en échec** (contenu identique ; chaque édition avec `old` égal à `new`) : la règle des appels en échec ci-dessous le signale dès qu'il a été enregistré 3 fois parmi les 10 derniers appels, lectures intercalées comprises. Une simulation (`dry_run`) n'est pas un échec. |
477483 | Un appel différent | Le compte repart. `/new` réinitialise le détecteur ; `/compact` non. |
478484 | Le même appel qui échoue encore, avec d'autres appels entre-temps | Un appel **en échec** (même outil, même entrée, même sortie) déjà enregistré 3 fois parmi les 10 derniers appels est signalé, quoi qu'il y ait eu entre-temps, et le tour s'arrête à son troisième signalement. Les appels réussis gardent la règle « à la suite » : relire un fichier n'est pas une boucle. |
479485 | Un appel d'outil dont les arguments diffusés répètent un motif (les 256 derniers caractères sont un motif de 4 à 64 caractères répété) ou dépassent 256 Ko | La génération est arrêtée aussitôt : `[error: the model's tool call ran away: its arguments repeat the same pattern (N characters so far: …) — generation stopped; rephrase the request, or try another model]`. Sans cela, un modèle qui déraille compose du charabia pendant des minutes pendant que l'écran affiche « Thinking » (le chien de garde est nourri par chaque fragment). Pendant qu'un appel d'outil est diffusé, le spinner dit `Composing a tool call`. |
480486
481-Les seuils (3, puis 3 de plus) sont fixés dans `main.go` ; `maxTurns` reste la borne extérieure d'un tour.
487+| Le même test `bash` relancé | Un appel `bash` dont la commande et la sortie ont la même forme que 2 appels précédents depuis le dernier `write_file` / `edit_file` qui a modifié un fichier reçoit `[mm: this is the same test, with the same result, for the 3rd time since the last file change — sleeps, timeouts and kills aside. …]` à la fin de sa sortie, et l'utilisateur voit `same test again: bash ×N with the same result, no file changed` ; à partir du 3e, à chaque nouveau. Forme de la commande : commandes `pkill`, `kill`, `killall`, `sleep`, `wait`, `true` et `:` retirées, préfixe `timeout …`, redirections et `&` final enlevés, chaque nombre écrit `N`. Forme de la sortie : nombres de 4 chiffres ou plus et décimaux écrits `N`, espacement uniformisé — `000` et `200` restent différents. N'arrête jamais le tour. |
488+
489+Les seuils (3, puis 3 de plus ; 3 pour les appels `bash` semblables) sont fixés dans `main.go` ; `maxTurns` reste la borne extérieure d'un tour.
482490
483491 ## Compteurs affichés après un tour
484492
@@ -74,8 +74,10 @@ Déclaré quand `editTools: true`.
74 | Aspect | Comportement |74 | Aspect | Comportement |
75 |--------|--------------|75 |--------|--------------|
76 | Fichier existant | Entièrement remplacé. |76 | Fichier existant | Entièrement remplacé. |
77-| Contenu identique | Rien n'est écrit ; le résultat le dit. |77+| Contenu identique | Rien n'est écrit ; le résultat le dit. Pour le détecteur de boucles, c'est un appel en échec (voir [Détection des boucles](#détection-de-boucle)). |
78 | Sortie | Un en-tête d'une ligne et le diff par rapport au contenu précédent. |78 | Sortie | Un en-tête d'une ligne et le diff par rapport au contenu précédent. |
79+| Caractères de contrôle dans le diff | Affichés échappés (`\f`, `\v`, `\b`, `\a`, `\r`, sinon `\xNN`) ; une tabulation, et un retour chariot qui termine une ligne CRLF, restent tels quels. Quand une ligne ajoutée en contient un, le diff se termine par `note: the new text holds control characters, shown escaped above (\f is U+000C, a form feed). In JSON, "\f" IS a form feed: …`. Le fichier lui-même est écrit tel qu'envoyé. |
80+| Sauts de page (U+000C) | Dans un fichier source (`.go`, `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.py`, `.rs`, `.java`, `.kt`, `.swift`, `.c`, `.h`, `.cc`, `.cpp`, `.hpp`, `.cs`, `.rb`, `.php`, `.lua`, `.zig`, `.scala`, `.dart`, `.sh`) qui ne contient pas encore de saut de page, un saut de page en début de ligne devant une lettre minuscule — `"\n\func"` dans les arguments JSON, que JSON lit comme un retour à la ligne, un saut de page et `unc` — est écrit comme un retour à la ligne et `f` (une ligne vide, puis `func`), ou comme `f` seul après une indentation ou tout au début. La sortie se termine alors par `[mm: repaired N form feed(s) (U+000C) at the start of a line, in …]` et l'utilisateur voit un avis `🩹`. Jamais modifié : un saut de page seul sur sa ligne (un saut de page de mise en forme), un saut de page au milieu d'une ligne, devant autre chose qu'une minuscule, dans un autre genre de fichier ou dans un fichier qui en contient déjà un. |
79 | ACP | Genre `edit` ; permission demandée ; le changement voyage comme un diff (diff de nouveau fichier à la création). |81 | ACP | Genre `edit` ; permission demandée ; le changement voyage comme un diff (diff de nouveau fichier à la création). |
80 82
81 ## `edit_file`83 ## `edit_file`
@@ -88,13 +90,13 @@ Déclaré quand `editTools: true`.
88 | `edits` | tableau de `{old, new, line}` | — | Remplacements, tous résolus par rapport au fichier original. |90 | `edits` | tableau de `{old, new, line}` | — | Remplacements, tous résolus par rapport au fichier original. |
89 | `edits[].old` | chaîne | — | Texte exact à trouver, présent exactement une fois. Les espaces sont pardonnés — voir *Comment `old` est mis en correspondance*. |91 | `edits[].old` | chaîne | — | Texte exact à trouver, présent exactement une fois. Les espaces sont pardonnés — voir *Comment `old` est mis en correspondance*. |
90 | `edits[].new` | chaîne | — | Remplacement ; vide supprime le texte trouvé. |92 | `edits[].new` | chaîne | — | Remplacement ; vide supprime le texte trouvé. |
91-| `edits[].line` | entier | — | Seulement quand `old` apparaît plusieurs fois : la ligne (à partir de 1) où commence l'occurrence à changer, telle que `read_file` avec `numbered: true` l'affiche. Ignoré quand `old` est unique. Une ligne où ne commence aucune occurrence est refusée : `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. |93+| `edits[].line` | entier | — | Seulement quand `old` apparaît plusieurs fois : la ligne (à partir de 1) où commence l'occurrence à changer, telle que `read_file` avec `numbered: true` l'affiche. Ignoré quand `old` est unique, tant qu'il est dans le fichier. Une ligne où ne commence aucune occurrence est refusée : `edit #1: old text appears 2 times, at lines 8, 9 — none starts at line 7: give one of these lines in "line"`. Une ligne hors du fichier — après sa dernière ligne, ou sous 1 — est refusée, que `old` soit unique ou non : `edit #1: "line": 1000000000000000 is outside the file, which has 42 line(s) — "line" is only needed when old appears several times; leave it out, or give the line where old starts, as read_file numbered=true shows it`. |
92 | `dry_run` | booléen | `false` | Rapporte ce qui changerait, n'écrit rien. |94 | `dry_run` | booléen | `false` | Rapporte ce qui changerait, n'écrit rien. |
93 95
94 | Règle | Conséquence si violée |96 | Règle | Conséquence si violée |
95 |-------|-----------------------|97 |-------|-----------------------|
96 | `old` apparaît exactement une fois, ou `line` en désigne une | Refusé : introuvable, ou ambigu — `old text appears N times (lines 11, 20) — to change ONE of them, add "line": the number of the line where it starts (one of 11, 20); or include its surrounding lines in old until the text is unique; to change several, send one edit per place…`. |98 | `old` apparaît exactement une fois, ou `line` en désigne une | Refusé : introuvable, ou ambigu — `old text appears N times (lines 11, 20) — to change ONE of them, add "line": the number of the line where it starts (one of 11, 20); or include its surrounding lines in old until the text is unique; to change several, send one edit per place…`. |
97-| `old` et `new` identiques | Pas une erreur quand le fichier contient `old` : cette modification est signalée comme déjà faite (` · N already as asked (identical old and new)` ; `<chemin>: unchanged — already as asked: …` quand c'est la seule) et les autres s'appliquent. Quand le fichier ne le contient pas : introuvable. |99+| `old` et `new` identiques | Pas une erreur quand le fichier contient `old` : cette modification est signalée comme déjà faite (` · N already as asked (identical old and new)` ; `<chemin>: unchanged — already as asked: …` quand c'est la seule) et les autres s'appliquent. Quand le fichier ne le contient pas : introuvable. Un appel qui ne change rien du tout est un appel en échec pour le détecteur de boucles (voir [Détection des boucles](#détection-de-boucle)). |
98 | Deux éditions ne doivent ni se chevaucher, ni s'imbriquer, ni se répéter | Refus. |100 | Deux éditions ne doivent ni se chevaucher, ni s'imbriquer, ni se répéter | Refus. |
99 | Les éditions sont résolues sur le texte original, jamais en cascade | — |101 | Les éditions sont résolues sur le texte original, jamais en cascade | — |
100 | Toute édition refusée | Rien n'est écrit. |102 | Toute édition refusée | Rien n'est écrit. |
@@ -102,6 +104,8 @@ Déclaré quand `editTools: true`.
102 | Aspect | Comportement |104 | Aspect | Comportement |
103 |--------|--------------|105 |--------|--------------|
104 | Sortie | Un en-tête d'une ligne (éditions appliquées, lignes ajoutées et supprimées, première ligne modifiée, et ` · N matched ignoring whitespace` quand une édition a eu besoin d'une correspondance tolérante) et le diff avec numéros de ligne. |106 | Sortie | Un en-tête d'une ligne (éditions appliquées, lignes ajoutées et supprimées, première ligne modifiée, et ` · N matched ignoring whitespace` quand une édition a eu besoin d'une correspondance tolérante) et le diff avec numéros de ligne. |
107+| Caractères de contrôle dans le diff | Comme pour `write_file`. |
108+| Sauts de page (U+000C) | Réparés comme pour `write_file`, dans le texte `new` de chaque édition seulement — jamais dans `old`, qui doit correspondre au fichier tel qu'il est ; la note nomme l'édition (`edit #2 new text, line(s) 4`). |
105 | ACP | Genre `edit` ; permission demandée ; le changement voyage comme un diff avec ancien et nouveau texte. |109 | ACP | Genre `edit` ; permission demandée ; le changement voyage comme un diff avec ancien et nouveau texte. |
106 110
107 ### Comment `old` est mis en correspondance111 ### Comment `old` est mis en correspondance
@@ -147,14 +151,14 @@ Déclaré quand `planTool: true` (le défaut). Transforme une liste de tâches e
147 | `name` | chaîne | Le plan. Pour `create`, facultatif : un plan sans nom s'appelle `user-request-N` (N compte les plans de la conversation). Pour les autres actions, facultatif aussi : sans lui, l'action porte sur le dernier plan créé dans la conversation (`list` l'ignore). |151 | `name` | chaîne | Le plan. Pour `create`, facultatif : un plan sans nom s'appelle `user-request-N` (N compte les plans de la conversation). Pour les autres actions, facultatif aussi : sans lui, l'action porte sur le dernier plan créé dans la conversation (`list` l'ignore). |
148 | `tasks` | liste de `{description, id?}` | Pour `create` : les tâches, dans l'ordre. Une tâche sans `id` reçoit sa position (1, 2, …). Ignoré par les autres actions. |152 | `tasks` | liste de `{description, id?}` | Pour `create` : les tâches, dans l'ordre. Une tâche sans `id` reçoit sa position (1, 2, …). Ignoré par les autres actions. |
149 | `taskId` | entier | Pour `update` : la tâche, à partir de 1. |153 | `taskId` | entier | Pour `update` : la tâche, à partir de 1. |
150-| `status` | chaîne | Pour `update` : `open`, `in_progress`, `done` ou `failed`. |154+| `status` | chaîne | Pour `update` : `done`, `failed`, `in_progress` ou `open`. Absent vaut `done`. |
151 | `message` | chaîne | Pour `update` : une note gardée sur la tâche. |155 | `message` | chaîne | Pour `update` : une note gardée sur la tâche. |
152 156
153 | Action | Effet | Résultat (texte JSON) |157 | Action | Effet | Résultat (texte JSON) |
154 |--------|-------|-----------------------|158 |--------|-------|-----------------------|
155 | `create` | Crée le plan, chaque tâche `open`. Refusé si le nom est déjà pris. | `result` (`Plan '<nom>' created with N tasks. Current: Task 1`), `planName`, `status`, `current`, `total` ; en mode ligne, aussi le `plan` entier. |159 | `create` | Crée le plan, chaque tâche `open`. Refusé si le nom est déjà pris. | `result` (`Plan '<nom>' created with N tasks. Current: Task 1`), `planName`, `status`, `current`, `total` ; en mode ligne, aussi le `plan` entier. |
156 | `get` | Lit un plan. | `result`, `plan` (nom, tâches avec id, description, statut, heures de début et de fin, note). |160 | `get` | Lit un plan. | `result`, `plan` (nom, tâches avec id, description, statut, heures de début et de fin, note). |
157-| `update` | Fixe le statut d'une tâche ; `in_progress` enregistre son heure de début (une fois) et en fait la tâche courante, `done` et `failed` enregistrent son heure de fin. | `result`, `status` (la ligne de statut, ci-dessous). |161+| `update` | Fixe le statut d'une tâche ; `in_progress` enregistre son heure de début (une fois) et en fait la tâche courante, `done` et `failed` enregistrent son heure de fin. Sans `status` et sans `tasks`, la tâche est marquée `done`. | `result` — terminé par ` (no status given: taken as done)` quand `status` était absent —, `status` (la ligne de statut, ci-dessous). |
158 | `next` | Marque la tâche courante `done` et démarre la suivante qui n'est ni faite ni en échec (`in_progress`) ; une tâche déjà terminée avec `update` est sautée. | `result` (`Task N done. Next: Task M - <description>`, ou `Plan '<nom>' is complete! All N tasks done.`), `status`, `nextTask` s'il y en a une. |162 | `next` | Marque la tâche courante `done` et démarre la suivante qui n'est ni faite ni en échec (`in_progress`) ; une tâche déjà terminée avec `update` est sautée. | `result` (`Task N done. Next: Task M - <description>`, ou `Plan '<nom>' is complete! All N tasks done.`), `status`, `nextTask` s'il y en a une. |
159 | `list` | Liste les plans existants. | `result`, `plans` (noms, du plus ancien au plus récent). |163 | `list` | Liste les plans existants. | `result`, `plans` (noms, du plus ancien au plus récent). |
160 | `delete` | Supprime un plan. | `result`. |164 | `delete` | Supprime un plan. | `result`. |
@@ -163,7 +167,8 @@ Déclaré quand `planTool: true` (le défaut). Transforme une liste de tâches e
163 | Aspect | Comportement |167 | Aspect | Comportement |
164 |--------|--------------|168 |--------|--------------|
165 | Ligne de statut | `[C/N] <icône> Task C: <description> (<statut>)` pour la tâche en cours de travail — la première en cours, sinon la première encore ouverte —, `[N/N] Plan finished: D done, F failed` quand toutes les tâches sont terminées et que certaines ont échoué, `[N/N] All tasks complete!` quand toutes sont faites. Icônes : ⏳ ouverte, 🔄 en cours, ✅ faite, ❌ en échec. |169 | Ligne de statut | `[C/N] <icône> Task C: <description> (<statut>)` pour la tâche en cours de travail — la première en cours, sinon la première encore ouverte —, `[N/N] Plan finished: D done, F failed` quand toutes les tâches sont terminées et que certaines ont échoué, `[N/N] All tasks complete!` quand toutes sont faites. Icônes : ⏳ ouverte, 🔄 en cours, ✅ faite, ❌ en échec. |
166-| Erreurs | Renvoyées comme texte, jamais comme un échec de génération : `[error: no plans found for this session]`, `[error: no plan named '<nom>' found]`, `[error: plan '<nom>' already exists]`, `[error: no task with id N in plan '<nom>']`, `[error: unknown action '<action>'. Valid actions: …]`. Un `update` sans `status` valide renvoie l'appel reçu, précise que `tasks` est ignoré par `update` quand il a été envoyé, et donne un appel qui fonctionne. |170+| Erreurs | Renvoyées comme texte, jamais comme un échec de génération : `[error: no plans found for this session]`, `[error: no plan named '<nom>' found]`, `[error: plan '<nom>' already exists]`, `[error: no task with id N in plan '<nom>']`, `[error: unknown action '<action>'. Valid actions: …]`. Un `update` avec un `status` qui n'est pas l'un des quatre, ou avec `tasks` et sans `status`, renvoie l'appel reçu, précise que `tasks` est ignoré par `update` quand il a été envoyé, et donne un appel qui fonctionne. |
171+| Description | Demande un seul `update` avec `status: "done"` par tâche terminée, aucun appel au plan entre les étapes d'une tâche, et aucun une fois toutes les tâches faites. `next` et `status` restent acceptés. |
167 | Stockage | En mémoire, par conversation : le mode ligne et la fenêtre en tiennent une ; en ACP chaque session a la sienne, et un fil ne voit jamais les plans d'un autre. Les plans ne sont pas écrits dans le fichier de session et sont perdus à l'arrêt de mm. Une conversation qui change repart sans plan : `/new` et `/resume` dans toutes les façades, `session/load` et `session/resume` en ACP. |172 | Stockage | En mémoire, par conversation : le mode ligne et la fenêtre en tiennent une ; en ACP chaque session a la sienne, et un fil ne voit jamais les plans d'un autre. Les plans ne sont pas écrits dans le fichier de session et sont perdus à l'arrêt de mm. Une conversation qui change repart sans plan : `/new` et `/resume` dans toutes les façades, `session/load` et `session/resume` en ACP. |
168 | Permission | `create`, `update`, `next` et `delete` sont demandés quand `yolo: false` ; un refus renvoie `[plan: command rejected by the user]`. `get`, `list` et `status` ne demandent jamais. |173 | Permission | `create`, `update`, `next` et `delete` sont demandés quand `yolo: false` ; un refus renvoie `[plan: command rejected by the user]`. `get`, `list` et `status` ne demandent jamais. |
169 | Affichage | Mode ligne : `📋 plan: <action> <nom>` avant l'appel, puis `📋 <ligne de statut>` après chaque action qui en a une (`create`, `update`, `next`, `status`). Fenêtre : l'appel comme appel d'outil, et `📋 <ligne de statut>` en notice. Éditeur (ACP) : l'appel comme appel d'outil, le statut dans son résultat. La progression est affichée par mm, que le modèle la reprenne ou non. |174 | Affichage | Mode ligne : `📋 plan: <action> <nom>` avant l'appel, puis `📋 <ligne de statut>` après chaque action qui en a une (`create`, `update`, `next`, `status`). Fenêtre : l'appel comme appel d'outil, et `📋 <ligne de statut>` en notice. Éditeur (ACP) : l'appel comme appel d'outil, le statut dans son résultat. La progression est affichée par mm, que le modèle la reprenne ou non. |
@@ -188,7 +193,7 @@ Déclaré quand `lsp.servers` liste au moins un serveur dont la commande est sur
188 | `definition`, `references` | Une ligne `chemin:ligne:colonne <ligne source>` par emplacement, triée par chemin puis position, doublons retirés ; les chemins du projet sont relatifs, les autres absolus. `references` est préfixé de `N reference(s):` et inclut la déclaration. |193 | `definition`, `references` | Une ligne `chemin:ligne:colonne <ligne source>` par emplacement, triée par chemin puis position, doublons retirés ; les chemins du projet sont relatifs, les autres absolus. `references` est préfixé de `N reference(s):` et inclut la déclaration. |
189 | `hover` | Le texte du serveur tel qu'envoyé (signature, type, documentation ; Markdown pour la plupart des serveurs). |194 | `hover` | Le texte du serveur tel qu'envoyé (signature, type, documentation ; Markdown pour la plupart des serveurs). |
190 | `symbols` | Une ligne `<sorte> <nom> [<détail>] line N` par symbole, enfants indentés de deux espaces. |195 | `symbols` | Une ligne `<sorte> <nom> [<détail>] line N` par symbole, enfants indentés de deux espaces. |
191-| `diagnostics` | Le fichier est synchronisé, puis l'appel attend jusqu'à 3 s la publication du serveur. `N diagnostic(s) in <chemin>:` puis une ligne `<sévérité> chemin:ligne:colonne <message> [<source>]` par constat ; `no diagnostics: <chemin> is clean` ; ` (as last published)` quand le fichier n'a pas changé depuis la dernière publication ; `no diagnostics received for <chemin> within 3s (…)` quand le serveur n'a jamais publié. |196+| `diagnostics` | Le fichier est synchronisé, puis l'appel attend jusqu'à 3 s la publication du serveur. Une publication avec des constats est prise tout de suite. Une publication vide est prise une fois qu'aucune autre publication pour le fichier n'est venue pendant 400 ms et que le serveur ne signale aucun travail en cours (`$/progress` ; mm déclare `window.workDoneProgress` au démarrage) : un serveur qui recharge son workspace peut d'abord publier une liste vide. Quand les 3 s s'épuisent pendant un tel travail, la réponse est `no diagnostics yet for <chemin>, but the server is still loading the workspace — this does NOT mean the file is clean: ask again in a moment, or build it`. Un serveur qui répond à `textDocument/diagnostic` est interrogé à la place, et sa réponse est prise telle quelle. `N diagnostic(s) in <chemin>:` puis une ligne `<sévérité> chemin:ligne:colonne <message> [<source>]` par constat ; `no diagnostics: <chemin> is clean` ; ` (as last published)` quand le fichier n'a pas changé depuis la dernière publication ; `no diagnostics received for <chemin> within 3s (…)` quand le serveur n'a jamais publié. |
192 | `rename` | Applique les modifications du serveur aux fichiers sur disque (positions UTF-16 converties), informe le serveur du nouveau contenu, et répond `renamed to <nouveau>: N edit(s) in M file(s)` suivi d'une ligne `chemin: N edit(s)` par fichier. Sans `new_name` : `[lsp: rename needs new_name — call lsp again with {"action": "rename", "path": …, "symbol": …, "new_name": "<the new identifier>"}; do not use edit_file for a rename]`. |197 | `rename` | Applique les modifications du serveur aux fichiers sur disque (positions UTF-16 converties), informe le serveur du nouveau contenu, et répond `renamed to <nouveau>: N edit(s) in M file(s)` suivi d'une ligne `chemin: N edit(s)` par fichier. Sans `new_name` : `[lsp: rename needs new_name — call lsp again with {"action": "rename", "path": …, "symbol": …, "new_name": "<the new identifier>"}; do not use edit_file for a rename]`. |
193 | Positions | Lignes et colonnes en base 1 à la frontière de l'outil, UTF-16 en base 0 sur le fil. Une position au-delà de la fin d'une ligne ou du fichier est refusée, avec le compte. |198 | Positions | Lignes et colonnes en base 1 à la frontière de l'outil, UTF-16 en base 0 sur le fil. Une position au-delà de la fin d'une ligne ou du fichier est refusée, avec le compte. |
194 | Synchronisation | Avant chaque requête, le fichier est relu sur disque et envoyé en `didOpen` (première fois) ou en `didChange` complet (quand son contenu a bougé) : les modifications faites avec `edit_file` sont vues sans étape supplémentaire. |199 | Synchronisation | Avant chaque requête, le fichier est relu sur disque et envoyé en `didOpen` (première fois) ou en `didChange` complet (quand son contenu a bougé) : les modifications faites avec `edit_file` sont vues sans étape supplémentaire. |
@@ -473,12 +478,15 @@ Chaque outil enregistre `(outil, entrée, sortie)` dans le détecteur de boucle
473 | Situation | Comportement |478 | Situation | Comportement |
474 |-----------|--------------|479 |-----------|--------------|
475 | Le même triplet 3 fois de suite | La sortie de l'outil reçoit `[LOOP_DETECTED: You have attempted the same action multiple times with the same result. Please try a different approach or provide more information.]` en annexe. Rien ne s'arrête. |480 | Le même triplet 3 fois de suite | La sortie de l'outil reçoit `[LOOP_DETECTED: You have attempted the same action multiple times with the same result. Please try a different approach or provide more information.]` en annexe. Rien ne s'arrête. |
476-| 3 appels identiques de plus (6 de suite) | L'outil renvoie une erreur au lieu de texte et le tour se termine : `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. L'historique garde tout ce qui a tourné ; l'erreur est enregistrée dans le tableau `errors` du fichier de session (`where: generation`). |481+| 3 appels identiques de plus (6 de suite) | Les appels d'outils s'arrêtent. Les appels de cette réponse reçoivent `[mm: not run — the loop detector stopped the tool calls]`, et le modèle est appelé une fois de plus, **sans outils**, après `[mm: mm stopped your tool calls: <la phrase du détecteur>. No more tools in this turn. Give your final answer now: …]` ; sa réponse termine le tour. Quand cet appel échoue, appelle un outil ou n'apporte aucun texte, le tour se termine sur l'erreur `[error: the model repeated the same edit_file call 6 times in a row with the same failing result — turn stopped by the loop detector; rephrase the request, or fix what the tool kept reporting]`. L'historique garde tout ce qui a tourné ; cette erreur est enregistrée dans le tableau `errors` du fichier de session (`where: generation`). |
482+| Un `write_file` ou `edit_file` qui ne change rien | Enregistré comme un appel **en échec** (contenu identique ; chaque édition avec `old` égal à `new`) : la règle des appels en échec ci-dessous le signale dès qu'il a été enregistré 3 fois parmi les 10 derniers appels, lectures intercalées comprises. Une simulation (`dry_run`) n'est pas un échec. |
477 | Un appel différent | Le compte repart. `/new` réinitialise le détecteur ; `/compact` non. |483 | Un appel différent | Le compte repart. `/new` réinitialise le détecteur ; `/compact` non. |
478 | Le même appel qui échoue encore, avec d'autres appels entre-temps | Un appel **en échec** (même outil, même entrée, même sortie) déjà enregistré 3 fois parmi les 10 derniers appels est signalé, quoi qu'il y ait eu entre-temps, et le tour s'arrête à son troisième signalement. Les appels réussis gardent la règle « à la suite » : relire un fichier n'est pas une boucle. |484 | Le même appel qui échoue encore, avec d'autres appels entre-temps | Un appel **en échec** (même outil, même entrée, même sortie) déjà enregistré 3 fois parmi les 10 derniers appels est signalé, quoi qu'il y ait eu entre-temps, et le tour s'arrête à son troisième signalement. Les appels réussis gardent la règle « à la suite » : relire un fichier n'est pas une boucle. |
479 | Un appel d'outil dont les arguments diffusés répètent un motif (les 256 derniers caractères sont un motif de 4 à 64 caractères répété) ou dépassent 256 Ko | La génération est arrêtée aussitôt : `[error: the model's tool call ran away: its arguments repeat the same pattern (N characters so far: …) — generation stopped; rephrase the request, or try another model]`. Sans cela, un modèle qui déraille compose du charabia pendant des minutes pendant que l'écran affiche « Thinking » (le chien de garde est nourri par chaque fragment). Pendant qu'un appel d'outil est diffusé, le spinner dit `Composing a tool call`. |485 | Un appel d'outil dont les arguments diffusés répètent un motif (les 256 derniers caractères sont un motif de 4 à 64 caractères répété) ou dépassent 256 Ko | La génération est arrêtée aussitôt : `[error: the model's tool call ran away: its arguments repeat the same pattern (N characters so far: …) — generation stopped; rephrase the request, or try another model]`. Sans cela, un modèle qui déraille compose du charabia pendant des minutes pendant que l'écran affiche « Thinking » (le chien de garde est nourri par chaque fragment). Pendant qu'un appel d'outil est diffusé, le spinner dit `Composing a tool call`. |
480 486
481-Les seuils (3, puis 3 de plus) sont fixés dans `main.go` ; `maxTurns` reste la borne extérieure d'un tour.487+| Le même test `bash` relancé | Un appel `bash` dont la commande et la sortie ont la même forme que 2 appels précédents depuis le dernier `write_file` / `edit_file` qui a modifié un fichier reçoit `[mm: this is the same test, with the same result, for the 3rd time since the last file change — sleeps, timeouts and kills aside. …]` à la fin de sa sortie, et l'utilisateur voit `same test again: bash ×N with the same result, no file changed` ; à partir du 3e, à chaque nouveau. Forme de la commande : commandes `pkill`, `kill`, `killall`, `sleep`, `wait`, `true` et `:` retirées, préfixe `timeout …`, redirections et `&` final enlevés, chaque nombre écrit `N`. Forme de la sortie : nombres de 4 chiffres ou plus et décimaux écrits `N`, espacement uniformisé — `000` et `200` restent différents. N'arrête jamais le tour. |
488+
489+Les seuils (3, puis 3 de plus ; 3 pour les appels `bash` semblables) sont fixés dans `main.go` ; `maxTurns` reste la borne extérieure d'un tour.
482 490
483 ## Compteurs affichés après un tour491 ## Compteurs affichés après un tour
484 492
modified internal/detector/detector.go +35 -2
@@ -31,6 +31,13 @@ type Action struct {
3131 // rejected permission… — whatever its input: the detector counts
3232 // consecutive failures apart from identical repeats (WithFailures).
3333 Failed bool
34+ // Shape is the call reduced to what makes it the same test run again —
35+ // for bash, the command without its sleeps, timeouts, kills and numbers,
36+ // and the shape of its output (ticket 297). "" is never compared.
37+ Shape string
38+ // Changed says the call changed a file (a write_file or edit_file that
39+ // wrote): calls of the same Shape before it do not count after it.
40+ Changed bool
3441 }
3542
3643 // LoopDetector tracks the history of actions to detect repetitive cycles.
@@ -53,6 +60,9 @@ type LoopDetector struct {
5360 // failedFlags counts, per identical FAILED action, how many times it was
5461 // flagged although other calls came in between (ticket 240).
5562 failedFlags map[string]int
63+ // similarAfter is how many calls of the same Shape, with no file changed
64+ // between them, make a cycle (WithSimilar); 0 never looks.
65+ similarAfter int
5666 }
5767
5868 // Loop is what WithReport hands over: a flagged repeat — the tool, how many
@@ -64,6 +74,9 @@ type Loop struct {
6474 Repeats int
6575 Stuck bool
6676 Failing bool
77+ // Similar: Repeats calls of the same Shape since the last file change
78+ // (WithSimilar, ticket 297) — reported and noted, never stopped.
79+ Similar bool
6780 }
6881
6982 // Stuck is the error a tool returns when the detector says the turn must
@@ -126,15 +139,30 @@ func (d *LoopDetector) WithFailures(n int) *LoopDetector {
126139
127140 // Record adds an action to the history and returns true if a loop is detected.
128141 func (d *LoopDetector) Record(action Action) bool {
142+ flagged, _ := d.Check(action)
143+ return flagged
144+}
145+
146+// Check is Record that also says whether the action closes a cycle of
147+// similar calls (WithSimilar): similar is then how many calls of its Shape
148+// there were since the last file change, this one included; 0 otherwise,
149+// and always 0 when flagged is true — the stronger finding wins.
150+//
151+// flagged, similar := d.Check(detector.Action{ToolName: "bash", Input: cmd, Output: out, Shape: shape})
152+func (d *LoopDetector) Check(action Action) (flagged bool, similar int) {
129153 flagged, loop, report := d.record(action)
130154 if loop != nil && report != nil {
131155 report(*loop)
132156 }
133- return flagged
157+ if loop != nil && loop.Similar {
158+ similar = loop.Repeats
159+ }
160+ return flagged, similar
134161 }
135162
136163 // record is Record under the lock; it also returns what to report, if
137-// anything: a flagged repeat wins over a run of failures — it says more.
164+// anything: a flagged repeat wins over a run of failures — it says more —
165+// and a run of failures over a cycle of similar calls.
138166 func (d *LoopDetector) record(action Action) (bool, *Loop, func(Loop)) {
139167 d.historyMu.Lock()
140168 defer d.historyMu.Unlock()
@@ -162,11 +190,15 @@ func (d *LoopDetector) record(action Action) (bool, *Loop, func(Loop)) {
162190 return true, &Loop{Tool: action.ToolName, Repeats: seen + 1, Stuck: d.stuck()}, d.report
163191 }
164192 d.flagged = 0
193+ similar := d.similar(action)
165194 d.remember(action)
166195
167196 if d.failAfter > 0 && d.failures >= d.failAfter {
168197 return false, &Loop{Tool: action.ToolName, Repeats: d.failures, Failing: true}, d.report
169198 }
199+ if d.similarAfter > 0 && similar >= d.similarAfter {
200+ return false, &Loop{Tool: action.ToolName, Repeats: similar, Similar: true}, d.report
201+ }
170202 return false, nil, nil
171203 }
172204
@@ -245,6 +277,7 @@ func (d *LoopDetector) Reset() {
245277 defer d.historyMu.Unlock()
246278 d.failedFlags = nil
247279 d.history = d.history[:0]
280+ // similarAfter is a setting: kept.
248281 d.flagged = 0
249282 d.failures = 0
250283 }
@@ -31,6 +31,13 @@ type Action struct {
31 // rejected permission… — whatever its input: the detector counts31 // rejected permission… — whatever its input: the detector counts
32 // consecutive failures apart from identical repeats (WithFailures).32 // consecutive failures apart from identical repeats (WithFailures).
33 Failed bool33 Failed bool
34+ // Shape is the call reduced to what makes it the same test run again —
35+ // for bash, the command without its sleeps, timeouts, kills and numbers,
36+ // and the shape of its output (ticket 297). "" is never compared.
37+ Shape string
38+ // Changed says the call changed a file (a write_file or edit_file that
39+ // wrote): calls of the same Shape before it do not count after it.
40+ Changed bool
34 }41 }
35 42
36 // LoopDetector tracks the history of actions to detect repetitive cycles.43 // LoopDetector tracks the history of actions to detect repetitive cycles.
@@ -53,6 +60,9 @@ type LoopDetector struct {
53 // failedFlags counts, per identical FAILED action, how many times it was60 // failedFlags counts, per identical FAILED action, how many times it was
54 // flagged although other calls came in between (ticket 240).61 // flagged although other calls came in between (ticket 240).
55 failedFlags map[string]int62 failedFlags map[string]int
63+ // similarAfter is how many calls of the same Shape, with no file changed
64+ // between them, make a cycle (WithSimilar); 0 never looks.
65+ similarAfter int
56 }66 }
57 67
58 // Loop is what WithReport hands over: a flagged repeat — the tool, how many68 // Loop is what WithReport hands over: a flagged repeat — the tool, how many
@@ -64,6 +74,9 @@ type Loop struct {
64 Repeats int74 Repeats int
65 Stuck bool75 Stuck bool
66 Failing bool76 Failing bool
77+ // Similar: Repeats calls of the same Shape since the last file change
78+ // (WithSimilar, ticket 297) — reported and noted, never stopped.
79+ Similar bool
67 }80 }
68 81
69 // Stuck is the error a tool returns when the detector says the turn must82 // Stuck is the error a tool returns when the detector says the turn must
@@ -126,15 +139,30 @@ func (d *LoopDetector) WithFailures(n int) *LoopDetector {
126 139
127 // Record adds an action to the history and returns true if a loop is detected.140 // Record adds an action to the history and returns true if a loop is detected.
128 func (d *LoopDetector) Record(action Action) bool {141 func (d *LoopDetector) Record(action Action) bool {
142+ flagged, _ := d.Check(action)
143+ return flagged
144+}
145+
146+// Check is Record that also says whether the action closes a cycle of
147+// similar calls (WithSimilar): similar is then how many calls of its Shape
148+// there were since the last file change, this one included; 0 otherwise,
149+// and always 0 when flagged is true — the stronger finding wins.
150+//
151+// flagged, similar := d.Check(detector.Action{ToolName: "bash", Input: cmd, Output: out, Shape: shape})
152+func (d *LoopDetector) Check(action Action) (flagged bool, similar int) {
129 flagged, loop, report := d.record(action)153 flagged, loop, report := d.record(action)
130 if loop != nil && report != nil {154 if loop != nil && report != nil {
131 report(*loop)155 report(*loop)
132 }156 }
133- return flagged157+ if loop != nil && loop.Similar {
158+ similar = loop.Repeats
159+ }
160+ return flagged, similar
134 }161 }
135 162
136 // record is Record under the lock; it also returns what to report, if163 // record is Record under the lock; it also returns what to report, if
137-// anything: a flagged repeat wins over a run of failures — it says more.164+// anything: a flagged repeat wins over a run of failures — it says more —
165+// and a run of failures over a cycle of similar calls.
138 func (d *LoopDetector) record(action Action) (bool, *Loop, func(Loop)) {166 func (d *LoopDetector) record(action Action) (bool, *Loop, func(Loop)) {
139 d.historyMu.Lock()167 d.historyMu.Lock()
140 defer d.historyMu.Unlock()168 defer d.historyMu.Unlock()
@@ -162,11 +190,15 @@ func (d *LoopDetector) record(action Action) (bool, *Loop, func(Loop)) {
162 return true, &Loop{Tool: action.ToolName, Repeats: seen + 1, Stuck: d.stuck()}, d.report190 return true, &Loop{Tool: action.ToolName, Repeats: seen + 1, Stuck: d.stuck()}, d.report
163 }191 }
164 d.flagged = 0192 d.flagged = 0
193+ similar := d.similar(action)
165 d.remember(action)194 d.remember(action)
166 195
167 if d.failAfter > 0 && d.failures >= d.failAfter {196 if d.failAfter > 0 && d.failures >= d.failAfter {
168 return false, &Loop{Tool: action.ToolName, Repeats: d.failures, Failing: true}, d.report197 return false, &Loop{Tool: action.ToolName, Repeats: d.failures, Failing: true}, d.report
169 }198 }
199+ if d.similarAfter > 0 && similar >= d.similarAfter {
200+ return false, &Loop{Tool: action.ToolName, Repeats: similar, Similar: true}, d.report
201+ }
170 return false, nil, nil202 return false, nil, nil
171 }203 }
172 204
@@ -245,6 +277,7 @@ func (d *LoopDetector) Reset() {
245 defer d.historyMu.Unlock()277 defer d.historyMu.Unlock()
246 d.failedFlags = nil278 d.failedFlags = nil
247 d.history = d.history[:0]279 d.history = d.history[:0]
280+ // similarAfter is a setting: kept.
248 d.flagged = 0281 d.flagged = 0
249 d.failures = 0282 d.failures = 0
250 }283 }
added internal/detector/similar.go +46 -0
new file mode 100644
@@ -0,0 +1,46 @@
1+package detector
2+
3+// Cycles of similar calls (ticket 297). Seen 2026-12-02 with
4+// Qwen3-Coder-Next: the server it wrote deadlocked on every write, its test
5+// hid curl's error, and for about twelve calls it alternated two bash
6+// commands — a GET ("the server works") and the full test ("the server
7+// exits") — changing only `pkill`, `timeout N`, `sleep N`, `2>&1`. No rule
8+// fired: each command differed a little and most exited 0.
9+//
10+// The caller reduces such a call to its Shape (for bash, tools/bashshape.go);
11+// WithSimilar counts the calls of the same Shape in the history window since
12+// the last file change. Re-running a test after a real change is the right
13+// thing to do, so this is only reported and noted in the tool result — the
14+// model is told to read the code instead — never a reason to stop the turn.
15+
16+// WithSimilar makes Check report, through WithReport and its own result,
17+// the n-th call of the same Shape since the last file change, and every
18+// one after it. 0 (the default) never looks.
19+//
20+// d := detector.NewLoopDetector(10, 3).WithSimilar(3).WithReport(show)
21+func (d *LoopDetector) WithSimilar(n int) *LoopDetector {
22+ d.historyMu.Lock()
23+ defer d.historyMu.Unlock()
24+ d.similarAfter = n
25+ return d
26+}
27+
28+// similar is how many calls of action's Shape the history holds since its
29+// last file change, action included; 0 when the action has no Shape or
30+// changes a file itself. Called under the lock, before action is remembered.
31+func (d *LoopDetector) similar(action Action) int {
32+ if action.Shape == "" || action.Changed {
33+ return 0
34+ }
35+ count := 1
36+ for i := len(d.history) - 1; i >= 0; i-- {
37+ h := d.history[i]
38+ if h.Changed {
39+ break
40+ }
41+ if h.ToolName == action.ToolName && h.Shape == action.Shape {
42+ count++
43+ }
44+ }
45+ return count
46+}
new file mode 100644
@@ -0,0 +1,46 @@
1+package detector
2+
3+// Cycles of similar calls (ticket 297). Seen 2026-12-02 with
4+// Qwen3-Coder-Next: the server it wrote deadlocked on every write, its test
5+// hid curl's error, and for about twelve calls it alternated two bash
6+// commands — a GET ("the server works") and the full test ("the server
7+// exits") — changing only `pkill`, `timeout N`, `sleep N`, `2>&1`. No rule
8+// fired: each command differed a little and most exited 0.
9+//
10+// The caller reduces such a call to its Shape (for bash, tools/bashshape.go);
11+// WithSimilar counts the calls of the same Shape in the history window since
12+// the last file change. Re-running a test after a real change is the right
13+// thing to do, so this is only reported and noted in the tool result — the
14+// model is told to read the code instead — never a reason to stop the turn.
15+
16+// WithSimilar makes Check report, through WithReport and its own result,
17+// the n-th call of the same Shape since the last file change, and every
18+// one after it. 0 (the default) never looks.
19+//
20+// d := detector.NewLoopDetector(10, 3).WithSimilar(3).WithReport(show)
21+func (d *LoopDetector) WithSimilar(n int) *LoopDetector {
22+ d.historyMu.Lock()
23+ defer d.historyMu.Unlock()
24+ d.similarAfter = n
25+ return d
26+}
27+
28+// similar is how many calls of action's Shape the history holds since its
29+// last file change, action included; 0 when the action has no Shape or
30+// changes a file itself. Called under the lock, before action is remembered.
31+func (d *LoopDetector) similar(action Action) int {
32+ if action.Shape == "" || action.Changed {
33+ return 0
34+ }
35+ count := 1
36+ for i := len(d.history) - 1; i >= 0; i-- {
37+ h := d.history[i]
38+ if h.Changed {
39+ break
40+ }
41+ if h.ToolName == action.ToolName && h.Shape == action.Shape {
42+ count++
43+ }
44+ }
45+ return count
46+}
added internal/detector/similar_test.go +72 -0
new file mode 100644
@@ -0,0 +1,72 @@
1+package detector
2+
3+import "testing"
4+
5+// shaped is a successful bash call of the given shape, its input varying.
6+func shaped(input, shape string) Action {
7+ return Action{ToolName: "bash", Input: input, Output: "out", Shape: shape}
8+}
9+
10+// Ticket 297: two kinds of near-identical commands, alternating, no file
11+// changed. The third call of a shape is reported as similar; the turn is
12+// never stopped and the call is never flagged as a loop.
13+func TestSimilarCallsAlternatingAreReported(t *testing.T) {
14+ var reported []Loop
15+ d := NewLoopDetector(10, 3).WithStop(3).WithSimilar(3).WithReport(func(l Loop) { reported = append(reported, l) })
16+ sequence := []struct {
17+ input, shape string
18+ want int
19+ }{
20+ {"curl -s :8080/labels", "get", 0},
21+ {"pkill app; sleep 1; ./test.sh", "test", 0},
22+ {"sleep 2; curl -s :8080/labels", "get", 0},
23+ {"pkill -f app; timeout 5 ./test.sh", "test", 0},
24+ {"curl -s :8080/labels 2>/dev/null", "get", 3},
25+ {"pkill app; sleep 3; ./test.sh", "test", 3},
26+ {"curl -sS :8080/labels", "get", 4},
27+ }
28+ for i, c := range sequence {
29+ flagged, similar := d.Check(shaped(c.input, c.shape))
30+ if flagged || d.Stuck() {
31+ t.Fatalf("call %d flagged or stuck: similarity alone must never stop the turn", i+1)
32+ }
33+ if similar != c.want {
34+ t.Errorf("call %d (%s): similar = %d, want %d", i+1, c.shape, similar, c.want)
35+ }
36+ }
37+ if len(reported) != 3 || !reported[0].Similar || reported[0].Tool != "bash" || reported[0].Repeats != 3 {
38+ t.Errorf("reported = %+v", reported)
39+ }
40+}
41+
42+// A file change in between starts the count again: re-running a test
43+// after a real change is what a model should do.
44+func TestSimilarCountRestartsAfterAFileChange(t *testing.T) {
45+ d := NewLoopDetector(10, 3).WithSimilar(3)
46+ d.Check(shaped("go test ./...", "test"))
47+ d.Check(shaped("go test ./... 2>&1", "test"))
48+ d.Check(Action{ToolName: "edit_file", Input: "main.go", Output: "applied", Changed: true})
49+ if _, similar := d.Check(shaped("go test ./...", "test")); similar != 0 {
50+ t.Errorf("after an edit: similar = %d, want 0", similar)
51+ }
52+ d.Check(shaped("go test ./...", "test"))
53+ if _, similar := d.Check(shaped("go test -count=1 ./...", "test")); similar != 3 {
54+ t.Errorf("third run since the edit: similar = %d, want 3", similar)
55+ }
56+}
57+
58+// No shape, no comparison; and WithSimilar off reports nothing.
59+func TestSimilarNeedsAShapeAndTheSetting(t *testing.T) {
60+ d := NewLoopDetector(10, 3).WithSimilar(2)
61+ for i := 0; i < 3; i++ {
62+ if _, similar := d.Check(Action{ToolName: "read_file", Input: "a.go", Output: string(rune('a' + i))}); similar != 0 {
63+ t.Errorf("no shape: similar = %d", similar)
64+ }
65+ }
66+ off := NewLoopDetector(10, 3)
67+ for i := 0; i < 5; i++ {
68+ if _, similar := off.Check(shaped("x", "same")); similar != 0 {
69+ t.Errorf("setting off: similar = %d", similar)
70+ }
71+ }
72+}
new file mode 100644
@@ -0,0 +1,72 @@
1+package detector
2+
3+import "testing"
4+
5+// shaped is a successful bash call of the given shape, its input varying.
6+func shaped(input, shape string) Action {
7+ return Action{ToolName: "bash", Input: input, Output: "out", Shape: shape}
8+}
9+
10+// Ticket 297: two kinds of near-identical commands, alternating, no file
11+// changed. The third call of a shape is reported as similar; the turn is
12+// never stopped and the call is never flagged as a loop.
13+func TestSimilarCallsAlternatingAreReported(t *testing.T) {
14+ var reported []Loop
15+ d := NewLoopDetector(10, 3).WithStop(3).WithSimilar(3).WithReport(func(l Loop) { reported = append(reported, l) })
16+ sequence := []struct {
17+ input, shape string
18+ want int
19+ }{
20+ {"curl -s :8080/labels", "get", 0},
21+ {"pkill app; sleep 1; ./test.sh", "test", 0},
22+ {"sleep 2; curl -s :8080/labels", "get", 0},
23+ {"pkill -f app; timeout 5 ./test.sh", "test", 0},
24+ {"curl -s :8080/labels 2>/dev/null", "get", 3},
25+ {"pkill app; sleep 3; ./test.sh", "test", 3},
26+ {"curl -sS :8080/labels", "get", 4},
27+ }
28+ for i, c := range sequence {
29+ flagged, similar := d.Check(shaped(c.input, c.shape))
30+ if flagged || d.Stuck() {
31+ t.Fatalf("call %d flagged or stuck: similarity alone must never stop the turn", i+1)
32+ }
33+ if similar != c.want {
34+ t.Errorf("call %d (%s): similar = %d, want %d", i+1, c.shape, similar, c.want)
35+ }
36+ }
37+ if len(reported) != 3 || !reported[0].Similar || reported[0].Tool != "bash" || reported[0].Repeats != 3 {
38+ t.Errorf("reported = %+v", reported)
39+ }
40+}
41+
42+// A file change in between starts the count again: re-running a test
43+// after a real change is what a model should do.
44+func TestSimilarCountRestartsAfterAFileChange(t *testing.T) {
45+ d := NewLoopDetector(10, 3).WithSimilar(3)
46+ d.Check(shaped("go test ./...", "test"))
47+ d.Check(shaped("go test ./... 2>&1", "test"))
48+ d.Check(Action{ToolName: "edit_file", Input: "main.go", Output: "applied", Changed: true})
49+ if _, similar := d.Check(shaped("go test ./...", "test")); similar != 0 {
50+ t.Errorf("after an edit: similar = %d, want 0", similar)
51+ }
52+ d.Check(shaped("go test ./...", "test"))
53+ if _, similar := d.Check(shaped("go test -count=1 ./...", "test")); similar != 3 {
54+ t.Errorf("third run since the edit: similar = %d, want 3", similar)
55+ }
56+}
57+
58+// No shape, no comparison; and WithSimilar off reports nothing.
59+func TestSimilarNeedsAShapeAndTheSetting(t *testing.T) {
60+ d := NewLoopDetector(10, 3).WithSimilar(2)
61+ for i := 0; i < 3; i++ {
62+ if _, similar := d.Check(Action{ToolName: "read_file", Input: "a.go", Output: string(rune('a' + i))}); similar != 0 {
63+ t.Errorf("no shape: similar = %d", similar)
64+ }
65+ }
66+ off := NewLoopDetector(10, 3)
67+ for i := 0; i < 5; i++ {
68+ if _, similar := off.Check(shaped("x", "same")); similar != 0 {
69+ t.Errorf("setting off: similar = %d", similar)
70+ }
71+ }
72+}
added internal/engine/blanks_test.go +118 -0
new file mode 100644
@@ -0,0 +1,118 @@
1+package engine
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+
8+ "mm/internal/config"
9+
10+ "github.com/firebase/genkit/go/ai"
11+ "github.com/firebase/genkit/go/genkit"
12+)
13+
14+// mellumBlanks is the reply of ticket 298: one sentence, then thousands of
15+// blank lines and a little LaTeX, up to max_tokens.
16+func mellumBlanks() string {
17+ return "Great! The build was successful. Now let's test the API." +
18+ strings.Repeat("\n", 3935) + "\\begin{figure}\n\\end{figure}\n"
19+}
20+
21+// Ticket 298, acceptance: the reply above, finish reason length, gets the
22+// loop label — not "raise max_tokens" — and the blank lines leave the
23+// answer.
24+func TestBlankLineReplyIsALoopNotACut(t *testing.T) {
25+ withLimit(t, "max_tokens", 4096)
26+ resp := &ai.ModelResponse{Message: ai.NewModelTextMessage(mellumBlanks()), FinishReason: ai.FinishReasonLength}
27+ collapseAnswerLoops(resp)
28+ if strings.Count(resp.Text(), "\n") > 5 {
29+ t.Errorf("the blank lines are still in the answer: %d new lines", strings.Count(resp.Text(), "\n"))
30+ }
31+ s, ok := answerStruggle(resp)
32+ if !ok || !s.Severe || !strings.Contains(s.Label, "3934 blank lines in a row") || strings.Contains(s.Label, "raise sampling") {
33+ t.Errorf("struggle = %+v, want the loop label", s)
34+ }
35+}
36+
37+// A normal answer with a few blank lines between paragraphs is unchanged.
38+func TestAnswerWithAFewBlankLinesIsUnchanged(t *testing.T) {
39+ text := "First paragraph.\n\n\nSecond paragraph.\n\n```go\nfunc main() {}\n```\n\n\n\nEnd."
40+ if got, _ := collapseLoops(text); got != text {
41+ t.Errorf("collapseLoops changed a normal answer:\n%q", got)
42+ }
43+ cut := &ai.ModelResponse{Message: ai.NewModelTextMessage(text), FinishReason: ai.FinishReasonLength}
44+ if s, _ := answerStruggle(cut); s.Severe || !strings.Contains(s.Label, "answer cut at the limit") {
45+ t.Errorf("a long real answer cut at the limit: %+v", s)
46+ }
47+}
48+
49+func TestCollapseLoopsBlankRuns(t *testing.T) {
50+ got, longest := collapseLoops("ok" + strings.Repeat("\n", 100))
51+ if got != "ok\n[… 100 blank lines — removed by mm]" || longest != 0 {
52+ t.Errorf("collapseLoops = %q, %d", got, longest)
53+ }
54+ if n := blankLines(got); n != 100 {
55+ t.Errorf("blankLines = %d", n)
56+ }
57+ // Spaces-only lines are blank too.
58+ if got, _ := collapseLoops("a\n" + strings.Repeat(" \n", loopBlankLines) + "b"); !strings.Contains(got, "blank lines — removed by mm") {
59+ t.Errorf("space-only lines: %q", got)
60+ }
61+}
62+
63+// The streaming watch cuts a call that turned into blank lines, without
64+// waiting for max_tokens.
65+func TestLoopWatchTripsOnBlankLines(t *testing.T) {
66+ cancelled := false
67+ var w loopWatch
68+ w.arm(func() { cancelled = true })
69+ w.feed("Great! The build was successful.")
70+ for i := 0; i < streamBlankLines; i++ {
71+ w.feed("\n")
72+ }
73+ sample, times, cut := w.take()
74+ if !cut || !cancelled || sample != blankSample || times != streamBlankLines {
75+ t.Errorf("take = %q, %d, %v (cancelled %v)", sample, times, cut, cancelled)
76+ }
77+ // A run broken by text does not trip.
78+ var calm loopWatch
79+ calm.arm(func() { t.Error("cancelled") })
80+ calm.feed(strings.Repeat(strings.Repeat("\n", 30)+"}\n", 10))
81+ if _, _, cut := calm.take(); cut {
82+ t.Error("blank runs broken by text tripped the watch")
83+ }
84+}
85+
86+// End to end: the blank-line call is cut and handed back once with its own
87+// note; the model then makes its answer.
88+func TestBlankLineStreamIsStoppedAndHandedBack(t *testing.T) {
89+ g := genkit.Init(context.Background())
90+ var seen []*ai.ModelRequest
91+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
92+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
93+ func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) {
94+ seen = append(seen, req)
95+ if len(seen) > 1 {
96+ return modelTurn(ai.NewTextPart("The API answers on :8080.")), nil
97+ }
98+ _ = cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{ai.NewTextPart("Now let's test the API.")}})
99+ for i := 0; i < 4000 && ctx.Err() == nil; i++ {
100+ _ = cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{ai.NewTextPart("\n")}})
101+ }
102+ if ctx.Err() == nil {
103+ t.Error("the blank-line call was not cancelled")
104+ }
105+ return nil, ctx.Err()
106+ })
107+ resp, _, err := testEngine(g).Generate(context.Background(), []*ai.Message{ai.NewUserTextMessage("build and test it")}, nil)
108+ if err != nil || len(seen) != 2 || resp.Text() != "The API answers on :8080." {
109+ t.Fatalf("Generate = %v after %d calls, answer %q", err, len(seen), resp.Text())
110+ }
111+ note := seen[1].Messages[len(seen[1].Messages)-1].Text()
112+ if !strings.Contains(note, "your reply turned into blank lines") {
113+ t.Errorf("note = %q", note)
114+ }
115+ if le := (loopError{sample: blankSample, times: 100}); !strings.Contains(le.Error(), "100 blank lines in a row") {
116+ t.Errorf("loopError = %q", le.Error())
117+ }
118+}
new file mode 100644
@@ -0,0 +1,118 @@
1+package engine
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+
8+ "mm/internal/config"
9+
10+ "github.com/firebase/genkit/go/ai"
11+ "github.com/firebase/genkit/go/genkit"
12+)
13+
14+// mellumBlanks is the reply of ticket 298: one sentence, then thousands of
15+// blank lines and a little LaTeX, up to max_tokens.
16+func mellumBlanks() string {
17+ return "Great! The build was successful. Now let's test the API." +
18+ strings.Repeat("\n", 3935) + "\\begin{figure}\n\\end{figure}\n"
19+}
20+
21+// Ticket 298, acceptance: the reply above, finish reason length, gets the
22+// loop label — not "raise max_tokens" — and the blank lines leave the
23+// answer.
24+func TestBlankLineReplyIsALoopNotACut(t *testing.T) {
25+ withLimit(t, "max_tokens", 4096)
26+ resp := &ai.ModelResponse{Message: ai.NewModelTextMessage(mellumBlanks()), FinishReason: ai.FinishReasonLength}
27+ collapseAnswerLoops(resp)
28+ if strings.Count(resp.Text(), "\n") > 5 {
29+ t.Errorf("the blank lines are still in the answer: %d new lines", strings.Count(resp.Text(), "\n"))
30+ }
31+ s, ok := answerStruggle(resp)
32+ if !ok || !s.Severe || !strings.Contains(s.Label, "3934 blank lines in a row") || strings.Contains(s.Label, "raise sampling") {
33+ t.Errorf("struggle = %+v, want the loop label", s)
34+ }
35+}
36+
37+// A normal answer with a few blank lines between paragraphs is unchanged.
38+func TestAnswerWithAFewBlankLinesIsUnchanged(t *testing.T) {
39+ text := "First paragraph.\n\n\nSecond paragraph.\n\n```go\nfunc main() {}\n```\n\n\n\nEnd."
40+ if got, _ := collapseLoops(text); got != text {
41+ t.Errorf("collapseLoops changed a normal answer:\n%q", got)
42+ }
43+ cut := &ai.ModelResponse{Message: ai.NewModelTextMessage(text), FinishReason: ai.FinishReasonLength}
44+ if s, _ := answerStruggle(cut); s.Severe || !strings.Contains(s.Label, "answer cut at the limit") {
45+ t.Errorf("a long real answer cut at the limit: %+v", s)
46+ }
47+}
48+
49+func TestCollapseLoopsBlankRuns(t *testing.T) {
50+ got, longest := collapseLoops("ok" + strings.Repeat("\n", 100))
51+ if got != "ok\n[… 100 blank lines — removed by mm]" || longest != 0 {
52+ t.Errorf("collapseLoops = %q, %d", got, longest)
53+ }
54+ if n := blankLines(got); n != 100 {
55+ t.Errorf("blankLines = %d", n)
56+ }
57+ // Spaces-only lines are blank too.
58+ if got, _ := collapseLoops("a\n" + strings.Repeat(" \n", loopBlankLines) + "b"); !strings.Contains(got, "blank lines — removed by mm") {
59+ t.Errorf("space-only lines: %q", got)
60+ }
61+}
62+
63+// The streaming watch cuts a call that turned into blank lines, without
64+// waiting for max_tokens.
65+func TestLoopWatchTripsOnBlankLines(t *testing.T) {
66+ cancelled := false
67+ var w loopWatch
68+ w.arm(func() { cancelled = true })
69+ w.feed("Great! The build was successful.")
70+ for i := 0; i < streamBlankLines; i++ {
71+ w.feed("\n")
72+ }
73+ sample, times, cut := w.take()
74+ if !cut || !cancelled || sample != blankSample || times != streamBlankLines {
75+ t.Errorf("take = %q, %d, %v (cancelled %v)", sample, times, cut, cancelled)
76+ }
77+ // A run broken by text does not trip.
78+ var calm loopWatch
79+ calm.arm(func() { t.Error("cancelled") })
80+ calm.feed(strings.Repeat(strings.Repeat("\n", 30)+"}\n", 10))
81+ if _, _, cut := calm.take(); cut {
82+ t.Error("blank runs broken by text tripped the watch")
83+ }
84+}
85+
86+// End to end: the blank-line call is cut and handed back once with its own
87+// note; the model then makes its answer.
88+func TestBlankLineStreamIsStoppedAndHandedBack(t *testing.T) {
89+ g := genkit.Init(context.Background())
90+ var seen []*ai.ModelRequest
91+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
92+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
93+ func(ctx context.Context, req *ai.ModelRequest, _ any, cb ai.ModelStreamCallback) (*ai.ModelResponse, error) {
94+ seen = append(seen, req)
95+ if len(seen) > 1 {
96+ return modelTurn(ai.NewTextPart("The API answers on :8080.")), nil
97+ }
98+ _ = cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{ai.NewTextPart("Now let's test the API.")}})
99+ for i := 0; i < 4000 && ctx.Err() == nil; i++ {
100+ _ = cb(ctx, &ai.ModelResponseChunk{Content: []*ai.Part{ai.NewTextPart("\n")}})
101+ }
102+ if ctx.Err() == nil {
103+ t.Error("the blank-line call was not cancelled")
104+ }
105+ return nil, ctx.Err()
106+ })
107+ resp, _, err := testEngine(g).Generate(context.Background(), []*ai.Message{ai.NewUserTextMessage("build and test it")}, nil)
108+ if err != nil || len(seen) != 2 || resp.Text() != "The API answers on :8080." {
109+ t.Fatalf("Generate = %v after %d calls, answer %q", err, len(seen), resp.Text())
110+ }
111+ note := seen[1].Messages[len(seen[1].Messages)-1].Text()
112+ if !strings.Contains(note, "your reply turned into blank lines") {
113+ t.Errorf("note = %q", note)
114+ }
115+ if le := (loopError{sample: blankSample, times: 100}); !strings.Contains(le.Error(), "100 blank lines in a row") {
116+ t.Errorf("loopError = %q", le.Error())
117+ }
118+}
modified internal/engine/engine.go +6 -0
@@ -298,6 +298,12 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a
298298 return nil, t.full, errStalled
299299 }
300300
301+ // The loop detector stopped a tool call repeated with the same failing
302+ // result: the model still gives its answer, without tools (ticket 296).
303+ if _, stuck := stuckTurn(err); stuck && ctx.Err() == nil {
304+ resp, err = t.answerAfterStuck(genCtx, guard, err)
305+ }
306+
301307 if t.retryableWithoutStreaming(err) {
302308 spinner.Start("Retrying without streaming")
303309 if resp, err = genkit.Generate(ctx, e.G, opts...); err == nil {
@@ -298,6 +298,12 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a
298 return nil, t.full, errStalled298 return nil, t.full, errStalled
299 }299 }
300 300
301+ // The loop detector stopped a tool call repeated with the same failing
302+ // result: the model still gives its answer, without tools (ticket 296).
303+ if _, stuck := stuckTurn(err); stuck && ctx.Err() == nil {
304+ resp, err = t.answerAfterStuck(genCtx, guard, err)
305+ }
306+
301 if t.retryableWithoutStreaming(err) {307 if t.retryableWithoutStreaming(err) {
302 spinner.Start("Retrying without streaming")308 spinner.Start("Retrying without streaming")
303 if resp, err = genkit.Generate(ctx, e.G, opts...); err == nil {309 if resp, err = genkit.Generate(ctx, e.G, opts...); err == nil {
modified internal/engine/engine_test.go +7 -5
@@ -385,15 +385,17 @@ func TestLSPCallsCountsTheLSPTool(t *testing.T) {
385385 }
386386 }
387387
388-// A tool that ends the turn with the loop detector's error: Generate fails,
389-// the history keeps the calls that ran, and Explain returns the detector's
390-// sentence whichever way Genkit wrapped the error.
388+// A tool that ends the turn with the loop detector's error, and a model that
389+// then gives no answer either (ticket 296: the final call without tools
390+// brought nothing): Generate fails, the history keeps the calls that ran,
391+// and Explain returns the detector's sentence whichever way Genkit wrapped
392+// the error.
391393 func TestStuckToolEndsTheTurnAndIsExplained(t *testing.T) {
392394 stuckReq := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{
393395 Name: "stuck",
394396 Input: map[string]any{},
395397 }))
396- g, _ := fakeGenkit(t, stuckReq, modelTurn(ai.NewTextPart("never reached")))
398+ g, _ := fakeGenkit(t, stuckReq, modelTurn(ai.NewTextPart(" ")))
397399 genkit.DefineTool(g, "stuck", "always stuck",
398400 func(_ *ai.ToolContext, _ struct{}) (string, error) {
399401 return "", &detector.Stuck{Tool: "edit_file", Repeats: 6}
@@ -404,7 +406,7 @@ func TestStuckToolEndsTheTurnAndIsExplained(t *testing.T) {
404406 []*ai.Message{ai.NewUserTextMessage("rename greet")},
405407 []ai.ToolRef{ai.ToolName("stuck")})
406408 if err == nil {
407- t.Fatal("Generate succeeded despite the stuck tool")
409+ t.Fatal("Generate succeeded despite the stuck tool and an empty final answer")
408410 }
409411 if len(full) < 1 {
410412 t.Errorf("history lost: %d messages", len(full))
@@ -385,15 +385,17 @@ func TestLSPCallsCountsTheLSPTool(t *testing.T) {
385 }385 }
386 }386 }
387 387
388-// A tool that ends the turn with the loop detector's error: Generate fails,388+// A tool that ends the turn with the loop detector's error, and a model that
389-// the history keeps the calls that ran, and Explain returns the detector's389+// then gives no answer either (ticket 296: the final call without tools
390-// sentence whichever way Genkit wrapped the error.390+// brought nothing): Generate fails, the history keeps the calls that ran,
391+// and Explain returns the detector's sentence whichever way Genkit wrapped
392+// the error.
391 func TestStuckToolEndsTheTurnAndIsExplained(t *testing.T) {393 func TestStuckToolEndsTheTurnAndIsExplained(t *testing.T) {
392 stuckReq := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{394 stuckReq := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{
393 Name: "stuck",395 Name: "stuck",
394 Input: map[string]any{},396 Input: map[string]any{},
395 }))397 }))
396- g, _ := fakeGenkit(t, stuckReq, modelTurn(ai.NewTextPart("never reached")))398+ g, _ := fakeGenkit(t, stuckReq, modelTurn(ai.NewTextPart(" ")))
397 genkit.DefineTool(g, "stuck", "always stuck",399 genkit.DefineTool(g, "stuck", "always stuck",
398 func(_ *ai.ToolContext, _ struct{}) (string, error) {400 func(_ *ai.ToolContext, _ struct{}) (string, error) {
399 return "", &detector.Stuck{Tool: "edit_file", Repeats: 6}401 return "", &detector.Stuck{Tool: "edit_file", Repeats: 6}
@@ -404,7 +406,7 @@ func TestStuckToolEndsTheTurnAndIsExplained(t *testing.T) {
404 []*ai.Message{ai.NewUserTextMessage("rename greet")},406 []*ai.Message{ai.NewUserTextMessage("rename greet")},
405 []ai.ToolRef{ai.ToolName("stuck")})407 []ai.ToolRef{ai.ToolName("stuck")})
406 if err == nil {408 if err == nil {
407- t.Fatal("Generate succeeded despite the stuck tool")409+ t.Fatal("Generate succeeded despite the stuck tool and an empty final answer")
408 }410 }
409 if len(full) < 1 {411 if len(full) < 1 {
410 t.Errorf("history lost: %d messages", len(full))412 t.Errorf("history lost: %d messages", len(full))
modified internal/engine/loops.go +42 -2
@@ -31,11 +31,24 @@ const loopMarker = "[… the same line repeated %d more times — removed by mm]
3131
3232 var loopCount = regexp.MustCompile(`\[… the same line repeated (\d+) more times — removed by mm\]`)
3333
34+// loopBlankLines is how many blank lines in a row make a loop (ticket
35+// 298). Seen 2026-12-02 with Mellum2: one sentence, then 3,935 blank lines
36+// up to max_tokens. Prose and code leave a few blank lines between blocks,
37+// never dozens.
38+const loopBlankLines = 40
39+
40+// blankMarker replaces a run of blank lines; blankCount reads it back.
41+const blankMarker = "[… %d blank lines — removed by mm]"
42+
43+var blankCount = regexp.MustCompile(`\[… (\d+) blank lines — removed by mm\]`)
44+
3445 // collapseLoops returns text with every run of at least loopLines identical
35-// non-blank lines reduced to its first line and the marker, and the length of
36-// the longest run collapsed (0 when none).
46+// non-blank lines reduced to its first line and the marker, every run of at
47+// least loopBlankLines blank lines reduced to the blank marker, and the
48+// length of the longest run of identical lines collapsed (0 when none).
3749 //
3850 // collapseLoops(strings.Repeat("cannot.\n", 30)) // "cannot.\n[… the same line repeated 29 more times — removed by mm]\n", 30
51+// collapseLoops("ok" + strings.Repeat("\n", 100)) // "ok\n[… 99 blank lines — removed by mm]\n", 0
3952 func collapseLoops(text string) (string, int) {
4053 lines := strings.Split(text, "\n")
4154 var out []string
@@ -43,6 +56,12 @@ func collapseLoops(text string) (string, int) {
4356 for i := 0; i < len(lines); {
4457 line := lines[i]
4558 if strings.TrimSpace(line) == "" {
59+ blanks := blankRun(lines, i)
60+ if blanks >= loopBlankLines {
61+ out = append(out, fmt.Sprintf(blankMarker, blanks))
62+ i += blanks
63+ continue
64+ }
4665 out = append(out, line)
4766 i++
4867 continue
@@ -70,6 +89,27 @@ func collapseLoops(text string) (string, int) {
7089 return strings.Join(out, "\n"), longest
7190 }
7291
92+// blankRun is how many blank lines start at lines[i].
93+func blankRun(lines []string, i int) int {
94+ n := 0
95+ for i+n < len(lines) && strings.TrimSpace(lines[i+n]) == "" {
96+ n++
97+ }
98+ return n
99+}
100+
101+// blankLines returns the longest run of blank lines collapsed in an
102+// answer (0 when none), read from its markers.
103+func blankLines(text string) int {
104+ most := 0
105+ for _, m := range blankCount.FindAllStringSubmatch(text, -1) {
106+ if n, err := strconv.Atoi(m[1]); err == nil {
107+ most = max(most, n)
108+ }
109+ }
110+ return most
111+}
112+
73113 // collapseAnswerLoops applies collapseLoops to the text parts of the turn's
74114 // answer. The message is the same value as the last entry of the history
75115 // Generate returns, so both are cleaned.
@@ -31,11 +31,24 @@ const loopMarker = "[… the same line repeated %d more times — removed by mm]
31 31
32 var loopCount = regexp.MustCompile(`\[… the same line repeated (\d+) more times — removed by mm\]`)32 var loopCount = regexp.MustCompile(`\[… the same line repeated (\d+) more times — removed by mm\]`)
33 33
34+// loopBlankLines is how many blank lines in a row make a loop (ticket
35+// 298). Seen 2026-12-02 with Mellum2: one sentence, then 3,935 blank lines
36+// up to max_tokens. Prose and code leave a few blank lines between blocks,
37+// never dozens.
38+const loopBlankLines = 40
39+
40+// blankMarker replaces a run of blank lines; blankCount reads it back.
41+const blankMarker = "[… %d blank lines — removed by mm]"
42+
43+var blankCount = regexp.MustCompile(`\[… (\d+) blank lines — removed by mm\]`)
44+
34 // collapseLoops returns text with every run of at least loopLines identical45 // collapseLoops returns text with every run of at least loopLines identical
35-// non-blank lines reduced to its first line and the marker, and the length of46+// non-blank lines reduced to its first line and the marker, every run of at
36-// the longest run collapsed (0 when none).47+// least loopBlankLines blank lines reduced to the blank marker, and the
48+// length of the longest run of identical lines collapsed (0 when none).
37 //49 //
38 // collapseLoops(strings.Repeat("cannot.\n", 30)) // "cannot.\n[… the same line repeated 29 more times — removed by mm]\n", 3050 // collapseLoops(strings.Repeat("cannot.\n", 30)) // "cannot.\n[… the same line repeated 29 more times — removed by mm]\n", 30
51+// collapseLoops("ok" + strings.Repeat("\n", 100)) // "ok\n[… 99 blank lines — removed by mm]\n", 0
39 func collapseLoops(text string) (string, int) {52 func collapseLoops(text string) (string, int) {
40 lines := strings.Split(text, "\n")53 lines := strings.Split(text, "\n")
41 var out []string54 var out []string
@@ -43,6 +56,12 @@ func collapseLoops(text string) (string, int) {
43 for i := 0; i < len(lines); {56 for i := 0; i < len(lines); {
44 line := lines[i]57 line := lines[i]
45 if strings.TrimSpace(line) == "" {58 if strings.TrimSpace(line) == "" {
59+ blanks := blankRun(lines, i)
60+ if blanks >= loopBlankLines {
61+ out = append(out, fmt.Sprintf(blankMarker, blanks))
62+ i += blanks
63+ continue
64+ }
46 out = append(out, line)65 out = append(out, line)
47 i++66 i++
48 continue67 continue
@@ -70,6 +89,27 @@ func collapseLoops(text string) (string, int) {
70 return strings.Join(out, "\n"), longest89 return strings.Join(out, "\n"), longest
71 }90 }
72 91
92+// blankRun is how many blank lines start at lines[i].
93+func blankRun(lines []string, i int) int {
94+ n := 0
95+ for i+n < len(lines) && strings.TrimSpace(lines[i+n]) == "" {
96+ n++
97+ }
98+ return n
99+}
100+
101+// blankLines returns the longest run of blank lines collapsed in an
102+// answer (0 when none), read from its markers.
103+func blankLines(text string) int {
104+ most := 0
105+ for _, m := range blankCount.FindAllStringSubmatch(text, -1) {
106+ if n, err := strconv.Atoi(m[1]); err == nil {
107+ most = max(most, n)
108+ }
109+ }
110+ return most
111+}
112+
73 // collapseAnswerLoops applies collapseLoops to the text parts of the turn's113 // collapseAnswerLoops applies collapseLoops to the text parts of the turn's
74 // answer. The message is the same value as the last entry of the history114 // answer. The message is the same value as the last entry of the history
75 // Generate returns, so both are cleaned.115 // Generate returns, so both are cleaned.
added internal/engine/reasoningcall.go +100 -0
new file mode 100644
@@ -0,0 +1,100 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
10+
11+// A tool call written inside the reasoning (ticket 299). Seen 2026-12-02
12+// with Mellum2.1-12B-A2.5B-Thinking on llmman, twice in two runs with
13+// reasoning on: the reasoning ended with
14+// `<tool_call>{"name": "read_file", "arguments": {"path": "main.go"}}</tool_call>`,
15+// the content was empty, no tool_calls delta came, and the finish reason was
16+// "stop". mm saw no text and no call, and the turn ended silently in the
17+// middle of the work. The <tool_call> recovery (xmlcalls.go) reads the
18+// content only, and retryCutReasoning only a reply cut by the limit.
19+//
20+// Such a reply is handed back ONCE, with the call quoted: nothing written in
21+// the reasoning is ever run — the model makes the call itself. Once per
22+// occurrence, not per turn: a reply with a real tool call starts the count
23+// again. Seen 2026-12-05 with the same model: handed back after 31 calls, it
24+// made the call; 2 calls later it did it again, and a per-turn count ended
25+// the turn silently right after it had found the bug to fix.
26+
27+// maxReasoningCallRetries is how many times in a row a reply whose tool
28+// call stayed in the reasoning is handed back.
29+const maxReasoningCallRetries = 1
30+
31+// callInReasoning returns the last complete <tool_call> block of a reply
32+// that said nothing and called nothing, but whose reasoning holds one; ok
33+// is false for any other reply.
34+//
35+// callInReasoning(resp, nil) // `<tool_call>{"name": "read_file", …}</tool_call>`, true
36+func callInReasoning(resp *ai.ModelResponse, err error) (block string, ok bool) {
37+ if err != nil || resp == nil || resp.Message == nil || !saidNothing(resp) {
38+ return "", false
39+ }
40+ reasoning := reasoningOfReply(resp.Message)
41+ end := strings.LastIndex(reasoning, toolCallClose)
42+ if end < 0 {
43+ return "", false
44+ }
45+ start := strings.LastIndex(reasoning[:end], toolCallOpen)
46+ if start < 0 {
47+ return "", false
48+ }
49+ if _, parsed := parseCall(reasoning[start+len(toolCallOpen) : end]); !parsed {
50+ return "", false
51+ }
52+ return reasoning[start : end+len(toolCallClose)], true
53+}
54+
55+// reasoningOfReply is the text of a message's reasoning parts.
56+func reasoningOfReply(m *ai.Message) string {
57+ var b strings.Builder
58+ for _, p := range m.Content {
59+ if p.IsReasoning() {
60+ b.WriteString(p.Text)
61+ }
62+ }
63+ return b.String()
64+}
65+
66+// reasoningCallNote is what the model reads after such a reply.
67+func reasoningCallNote(block string) *ai.Message {
68+ return noteMessage(fmt.Sprintf("%syou wrote this tool call inside your reasoning, so it was NOT made — "+
69+ "the tools never see your reasoning:\n%s\n"+
70+ "Make the call now as a real tool call, without reasoning about it again — or give your answer.]",
71+ argsRetryPrefix, shorten(block, 400)))
72+}
73+
74+// retryCallInReasoning hands back, once, a reply whose only tool call is
75+// inside its reasoning (ticket 299).
76+func (t *turn) retryCallInReasoning(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) {
77+ for t.reasoningCallRetries < maxReasoningCallRetries && ctx.Err() == nil {
78+ block, ok := callInReasoning(resp, err)
79+ if !ok {
80+ break
81+ }
82+ t.reasoningCallRetries++
83+ name := "a tool"
84+ if c, parsed := parseCall(strings.TrimSuffix(strings.TrimPrefix(block, toolCallOpen), toolCallClose)); parsed {
85+ name = c.Name
86+ }
87+ struggle(fmt.Sprintf("the model wrote its %s call inside its reasoning, where it does not run — asking it to make the call, %d/%d", name, t.reasoningCallRetries, maxReasoningCallRetries),
88+ fmt.Sprintf("tool call in the reasoning — handed back %d/%d", t.reasoningCallRetries, maxReasoningCallRetries))
89+ resp, err = t.handBack(ctx, params, call, reasoningCallNote(block))
90+ }
91+ if madeACall(resp, err) {
92+ t.reasoningCallRetries = 0
93+ }
94+ return resp, err
95+}
96+
97+// madeACall reports whether a reply holds a real tool call.
98+func madeACall(resp *ai.ModelResponse, err error) bool {
99+ return err == nil && resp != nil && len(resp.ToolRequests()) > 0
100+}
new file mode 100644
@@ -0,0 +1,100 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
10+
11+// A tool call written inside the reasoning (ticket 299). Seen 2026-12-02
12+// with Mellum2.1-12B-A2.5B-Thinking on llmman, twice in two runs with
13+// reasoning on: the reasoning ended with
14+// `<tool_call>{"name": "read_file", "arguments": {"path": "main.go"}}</tool_call>`,
15+// the content was empty, no tool_calls delta came, and the finish reason was
16+// "stop". mm saw no text and no call, and the turn ended silently in the
17+// middle of the work. The <tool_call> recovery (xmlcalls.go) reads the
18+// content only, and retryCutReasoning only a reply cut by the limit.
19+//
20+// Such a reply is handed back ONCE, with the call quoted: nothing written in
21+// the reasoning is ever run — the model makes the call itself. Once per
22+// occurrence, not per turn: a reply with a real tool call starts the count
23+// again. Seen 2026-12-05 with the same model: handed back after 31 calls, it
24+// made the call; 2 calls later it did it again, and a per-turn count ended
25+// the turn silently right after it had found the bug to fix.
26+
27+// maxReasoningCallRetries is how many times in a row a reply whose tool
28+// call stayed in the reasoning is handed back.
29+const maxReasoningCallRetries = 1
30+
31+// callInReasoning returns the last complete <tool_call> block of a reply
32+// that said nothing and called nothing, but whose reasoning holds one; ok
33+// is false for any other reply.
34+//
35+// callInReasoning(resp, nil) // `<tool_call>{"name": "read_file", …}</tool_call>`, true
36+func callInReasoning(resp *ai.ModelResponse, err error) (block string, ok bool) {
37+ if err != nil || resp == nil || resp.Message == nil || !saidNothing(resp) {
38+ return "", false
39+ }
40+ reasoning := reasoningOfReply(resp.Message)
41+ end := strings.LastIndex(reasoning, toolCallClose)
42+ if end < 0 {
43+ return "", false
44+ }
45+ start := strings.LastIndex(reasoning[:end], toolCallOpen)
46+ if start < 0 {
47+ return "", false
48+ }
49+ if _, parsed := parseCall(reasoning[start+len(toolCallOpen) : end]); !parsed {
50+ return "", false
51+ }
52+ return reasoning[start : end+len(toolCallClose)], true
53+}
54+
55+// reasoningOfReply is the text of a message's reasoning parts.
56+func reasoningOfReply(m *ai.Message) string {
57+ var b strings.Builder
58+ for _, p := range m.Content {
59+ if p.IsReasoning() {
60+ b.WriteString(p.Text)
61+ }
62+ }
63+ return b.String()
64+}
65+
66+// reasoningCallNote is what the model reads after such a reply.
67+func reasoningCallNote(block string) *ai.Message {
68+ return noteMessage(fmt.Sprintf("%syou wrote this tool call inside your reasoning, so it was NOT made — "+
69+ "the tools never see your reasoning:\n%s\n"+
70+ "Make the call now as a real tool call, without reasoning about it again — or give your answer.]",
71+ argsRetryPrefix, shorten(block, 400)))
72+}
73+
74+// retryCallInReasoning hands back, once, a reply whose only tool call is
75+// inside its reasoning (ticket 299).
76+func (t *turn) retryCallInReasoning(ctx context.Context, params *ai.ModelParams, call modelCall, resp *ai.ModelResponse, err error) (*ai.ModelResponse, error) {
77+ for t.reasoningCallRetries < maxReasoningCallRetries && ctx.Err() == nil {
78+ block, ok := callInReasoning(resp, err)
79+ if !ok {
80+ break
81+ }
82+ t.reasoningCallRetries++
83+ name := "a tool"
84+ if c, parsed := parseCall(strings.TrimSuffix(strings.TrimPrefix(block, toolCallOpen), toolCallClose)); parsed {
85+ name = c.Name
86+ }
87+ struggle(fmt.Sprintf("the model wrote its %s call inside its reasoning, where it does not run — asking it to make the call, %d/%d", name, t.reasoningCallRetries, maxReasoningCallRetries),
88+ fmt.Sprintf("tool call in the reasoning — handed back %d/%d", t.reasoningCallRetries, maxReasoningCallRetries))
89+ resp, err = t.handBack(ctx, params, call, reasoningCallNote(block))
90+ }
91+ if madeACall(resp, err) {
92+ t.reasoningCallRetries = 0
93+ }
94+ return resp, err
95+}
96+
97+// madeACall reports whether a reply holds a real tool call.
98+func madeACall(resp *ai.ModelResponse, err error) bool {
99+ return err == nil && resp != nil && len(resp.ToolRequests()) > 0
100+}
added internal/engine/reasoningcall_test.go +91 -0
new file mode 100644
@@ -0,0 +1,91 @@
1+package engine
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
10+
11+// callInReasoningReply is the reply of ticket 299: reasoning ending with a
12+// complete <tool_call> block, empty content, finish reason stop.
13+func callInReasoningReply() *ai.ModelResponse {
14+ reasoning := strings.Repeat("Let me check main.go again. ", 20) +
15+ `<tool_call>{"name": "read_file", "arguments": {"path": "main.go", "start": 110}}</tool_call>`
16+ return &ai.ModelResponse{
17+ Message: ai.NewModelMessage(ai.NewReasoningPart(reasoning, nil)),
18+ FinishReason: ai.FinishReasonStop,
19+ }
20+}
21+
22+// Ticket 299, acceptance: the reply does not end the turn silently. It is
23+// handed back once with the call quoted, and the model makes the call.
24+func TestToolCallInReasoningIsHandedBack(t *testing.T) {
25+ readFile := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "bash", Ref: "r1", Input: map[string]any{"command": "sed -n 110,140p main.go"}}))
26+ g, seen := scriptedGenkit(t, callInReasoningReply(), readFile, modelTurn(ai.NewTextPart("main.go builds now")))
27+
28+ resp, _, err := testEngine(g).Generate(context.Background(),
29+ []*ai.Message{ai.NewUserTextMessage("fix main.go")}, []ai.ToolRef{ai.ToolName("bash")})
30+ if err != nil {
31+ t.Fatalf("Generate: %v", err)
32+ }
33+ if resp.Text() != "main.go builds now" || len(*seen) != 3 {
34+ t.Fatalf("answer %q after %d calls, want the answer on the third", resp.Text(), len(*seen))
35+ }
36+ retry := (*seen)[1].Messages
37+ note := retry[len(retry)-1].Text()
38+ if !strings.Contains(note, "you wrote this tool call inside your reasoning, so it was NOT made") ||
39+ !strings.Contains(note, `"name": "read_file"`) {
40+ t.Errorf("note = %q", note)
41+ }
42+}
43+
44+// Twice in a row: handed back once only, then the turn ends as before.
45+func TestToolCallInReasoningIsHandedBackOnce(t *testing.T) {
46+ g, seen := scriptedGenkit(t, callInReasoningReply(), callInReasoningReply())
47+ if _, _, err := testEngine(g).Generate(context.Background(), []*ai.Message{ai.NewUserTextMessage("fix it")}, nil); err != nil {
48+ t.Fatalf("Generate: %v", err)
49+ }
50+ if len(*seen) != 1+maxReasoningCallRetries {
51+ t.Errorf("model called %d times, want %d", len(*seen), 1+maxReasoningCallRetries)
52+ }
53+}
54+
55+// Once per occurrence: after a real tool call, a new call in the reasoning
56+// is handed back again (2026-12-05: the per-turn count ended the turn).
57+func TestToolCallInReasoningIsHandedBackAgainAfterARealCall(t *testing.T) {
58+ realCall := func(ref string) *ai.ModelResponse {
59+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "bash", Ref: ref, Input: map[string]any{"command": "go build ."}}))
60+ }
61+ g, seen := scriptedGenkit(t, callInReasoningReply(), realCall("r1"), callInReasoningReply(), realCall("r2"), modelTurn(ai.NewTextPart("fixed")))
62+ resp, _, err := testEngine(g).Generate(context.Background(),
63+ []*ai.Message{ai.NewUserTextMessage("fix main.go")}, []ai.ToolRef{ai.ToolName("bash")})
64+ if err != nil {
65+ t.Fatalf("Generate: %v", err)
66+ }
67+ if resp.Text() != "fixed" || len(*seen) != 5 {
68+ t.Fatalf("answer %q after %d calls, want \"fixed\" on the fifth", resp.Text(), len(*seen))
69+ }
70+}
71+
72+func TestCallInReasoning(t *testing.T) {
73+ if block, ok := callInReasoning(callInReasoningReply(), nil); !ok || !strings.HasPrefix(block, "<tool_call>{\"name\": \"read_file\"") || !strings.HasSuffix(block, "</tool_call>") {
74+ t.Errorf("block = %q, %v", block, ok)
75+ }
76+ notCases := map[string]*ai.ModelResponse{
77+ "text said": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>{\"name\":\"x\"}</tool_call>", nil), ai.NewTextPart("done"))},
78+ "no block": {Message: ai.NewModelMessage(ai.NewReasoningPart("I should read main.go.", nil))},
79+ "unfinished": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>{\"name\": \"read_f", nil))},
80+ "not a call": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>just words</tool_call>", nil))},
81+ "a real call too": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>{\"name\":\"x\"}</tool_call>", nil), ai.NewToolRequestPart(&ai.ToolRequest{Name: "x"}))},
82+ }
83+ for name, resp := range notCases {
84+ if _, ok := callInReasoning(resp, nil); ok {
85+ t.Errorf("%s: handed back", name)
86+ }
87+ }
88+ if _, ok := callInReasoning(nil, nil); ok {
89+ t.Error("nil reply")
90+ }
91+}
new file mode 100644
@@ -0,0 +1,91 @@
1+package engine
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
10+
11+// callInReasoningReply is the reply of ticket 299: reasoning ending with a
12+// complete <tool_call> block, empty content, finish reason stop.
13+func callInReasoningReply() *ai.ModelResponse {
14+ reasoning := strings.Repeat("Let me check main.go again. ", 20) +
15+ `<tool_call>{"name": "read_file", "arguments": {"path": "main.go", "start": 110}}</tool_call>`
16+ return &ai.ModelResponse{
17+ Message: ai.NewModelMessage(ai.NewReasoningPart(reasoning, nil)),
18+ FinishReason: ai.FinishReasonStop,
19+ }
20+}
21+
22+// Ticket 299, acceptance: the reply does not end the turn silently. It is
23+// handed back once with the call quoted, and the model makes the call.
24+func TestToolCallInReasoningIsHandedBack(t *testing.T) {
25+ readFile := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "bash", Ref: "r1", Input: map[string]any{"command": "sed -n 110,140p main.go"}}))
26+ g, seen := scriptedGenkit(t, callInReasoningReply(), readFile, modelTurn(ai.NewTextPart("main.go builds now")))
27+
28+ resp, _, err := testEngine(g).Generate(context.Background(),
29+ []*ai.Message{ai.NewUserTextMessage("fix main.go")}, []ai.ToolRef{ai.ToolName("bash")})
30+ if err != nil {
31+ t.Fatalf("Generate: %v", err)
32+ }
33+ if resp.Text() != "main.go builds now" || len(*seen) != 3 {
34+ t.Fatalf("answer %q after %d calls, want the answer on the third", resp.Text(), len(*seen))
35+ }
36+ retry := (*seen)[1].Messages
37+ note := retry[len(retry)-1].Text()
38+ if !strings.Contains(note, "you wrote this tool call inside your reasoning, so it was NOT made") ||
39+ !strings.Contains(note, `"name": "read_file"`) {
40+ t.Errorf("note = %q", note)
41+ }
42+}
43+
44+// Twice in a row: handed back once only, then the turn ends as before.
45+func TestToolCallInReasoningIsHandedBackOnce(t *testing.T) {
46+ g, seen := scriptedGenkit(t, callInReasoningReply(), callInReasoningReply())
47+ if _, _, err := testEngine(g).Generate(context.Background(), []*ai.Message{ai.NewUserTextMessage("fix it")}, nil); err != nil {
48+ t.Fatalf("Generate: %v", err)
49+ }
50+ if len(*seen) != 1+maxReasoningCallRetries {
51+ t.Errorf("model called %d times, want %d", len(*seen), 1+maxReasoningCallRetries)
52+ }
53+}
54+
55+// Once per occurrence: after a real tool call, a new call in the reasoning
56+// is handed back again (2026-12-05: the per-turn count ended the turn).
57+func TestToolCallInReasoningIsHandedBackAgainAfterARealCall(t *testing.T) {
58+ realCall := func(ref string) *ai.ModelResponse {
59+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "bash", Ref: ref, Input: map[string]any{"command": "go build ."}}))
60+ }
61+ g, seen := scriptedGenkit(t, callInReasoningReply(), realCall("r1"), callInReasoningReply(), realCall("r2"), modelTurn(ai.NewTextPart("fixed")))
62+ resp, _, err := testEngine(g).Generate(context.Background(),
63+ []*ai.Message{ai.NewUserTextMessage("fix main.go")}, []ai.ToolRef{ai.ToolName("bash")})
64+ if err != nil {
65+ t.Fatalf("Generate: %v", err)
66+ }
67+ if resp.Text() != "fixed" || len(*seen) != 5 {
68+ t.Fatalf("answer %q after %d calls, want \"fixed\" on the fifth", resp.Text(), len(*seen))
69+ }
70+}
71+
72+func TestCallInReasoning(t *testing.T) {
73+ if block, ok := callInReasoning(callInReasoningReply(), nil); !ok || !strings.HasPrefix(block, "<tool_call>{\"name\": \"read_file\"") || !strings.HasSuffix(block, "</tool_call>") {
74+ t.Errorf("block = %q, %v", block, ok)
75+ }
76+ notCases := map[string]*ai.ModelResponse{
77+ "text said": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>{\"name\":\"x\"}</tool_call>", nil), ai.NewTextPart("done"))},
78+ "no block": {Message: ai.NewModelMessage(ai.NewReasoningPart("I should read main.go.", nil))},
79+ "unfinished": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>{\"name\": \"read_f", nil))},
80+ "not a call": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>just words</tool_call>", nil))},
81+ "a real call too": {Message: ai.NewModelMessage(ai.NewReasoningPart("<tool_call>{\"name\":\"x\"}</tool_call>", nil), ai.NewToolRequestPart(&ai.ToolRequest{Name: "x"}))},
82+ }
83+ for name, resp := range notCases {
84+ if _, ok := callInReasoning(resp, nil); ok {
85+ t.Errorf("%s: handed back", name)
86+ }
87+ }
88+ if _, ok := callInReasoning(nil, nil); ok {
89+ t.Error("nil reply")
90+ }
91+}
modified internal/engine/reread.go +34 -4
@@ -3,6 +3,7 @@ package engine
33 import (
44 "context"
55 "fmt"
6+ "strings"
67 "sync"
78
89 "mm/internal/config"
@@ -79,9 +80,12 @@ func (r *rereads) compressed() {
7980 r.mu.Unlock()
8081 }
8182
82-// changed counts a successful write_file or edit_file.
83-func (r *rereads) changed(req *ai.ToolRequest) {
84- if req == nil || !writeTools[req.Name] {
83+// changed counts a write_file or edit_file that changed a file. A refused
84+// edit, an "unchanged" one (old == new, identical content) or a dry run is
85+// not a change (ticket 295): counted as one, the no-op edits of a model
86+// going in circles reset the re-read state between its reads.
87+func (r *rereads) changed(req *ai.ToolRequest, resp *ai.MultipartToolResponse) {
88+ if req == nil || !writeTools[req.Name] || !changedAFile(resp) {
8589 return
8690 }
8791 r.mu.Lock()
@@ -149,7 +153,7 @@ func (r *rereads) wrap(inner toolHook) toolHook {
149153 if err != nil {
150154 return resp, err
151155 }
152- r.changed(params.Request)
156+ r.changed(params.Request, resp)
153157 if rank > 0 {
154158 resp = withRereadNote(resp, rereadNoteFor(rank))
155159 }
@@ -157,6 +161,32 @@ func (r *rereads) wrap(inner toolHook) toolHook {
157161 }
158162 }
159163
164+// changedAFile reads a write_file / edit_file result: true when its
165+// headline says the file was created or changed. An output that is not
166+// text cannot be read, and counts as a change, as before ticket 295.
167+//
168+// changedAFile(&ai.MultipartToolResponse{Output: "main.go: 1 edit(s) applied, +1 -1, first change at line 3"}) // true
169+// changedAFile(&ai.MultipartToolResponse{Output: "main.go: unchanged"}) // false
170+func changedAFile(resp *ai.MultipartToolResponse) bool {
171+ if resp == nil {
172+ return false
173+ }
174+ text, ok := resp.Output.(string)
175+ if !ok {
176+ return true
177+ }
178+ first := strings.SplitN(pathNote.ReplaceAllString(strings.TrimSpace(text), ""), "\n", 2)[0]
179+ m := fileToolSuccess.FindStringSubmatch(first)
180+ if m == nil {
181+ return false // refused, rejected, invalid: nothing was written
182+ }
183+ switch m[1] {
184+ case "unchanged", "would be created", "dry run":
185+ return false
186+ }
187+ return true
188+}
189+
160190 // ordinal is n in words for the notice: 3 → "3rd".
161191 func ordinal(n int) string {
162192 switch {
@@ -3,6 +3,7 @@ package engine
3 import (3 import (
4 "context"4 "context"
5 "fmt"5 "fmt"
6+ "strings"
6 "sync"7 "sync"
7 8
8 "mm/internal/config"9 "mm/internal/config"
@@ -79,9 +80,12 @@ func (r *rereads) compressed() {
79 r.mu.Unlock()80 r.mu.Unlock()
80 }81 }
81 82
82-// changed counts a successful write_file or edit_file.83+// changed counts a write_file or edit_file that changed a file. A refused
83-func (r *rereads) changed(req *ai.ToolRequest) {84+// edit, an "unchanged" one (old == new, identical content) or a dry run is
84- if req == nil || !writeTools[req.Name] {85+// not a change (ticket 295): counted as one, the no-op edits of a model
86+// going in circles reset the re-read state between its reads.
87+func (r *rereads) changed(req *ai.ToolRequest, resp *ai.MultipartToolResponse) {
88+ if req == nil || !writeTools[req.Name] || !changedAFile(resp) {
85 return89 return
86 }90 }
87 r.mu.Lock()91 r.mu.Lock()
@@ -149,7 +153,7 @@ func (r *rereads) wrap(inner toolHook) toolHook {
149 if err != nil {153 if err != nil {
150 return resp, err154 return resp, err
151 }155 }
152- r.changed(params.Request)156+ r.changed(params.Request, resp)
153 if rank > 0 {157 if rank > 0 {
154 resp = withRereadNote(resp, rereadNoteFor(rank))158 resp = withRereadNote(resp, rereadNoteFor(rank))
155 }159 }
@@ -157,6 +161,32 @@ func (r *rereads) wrap(inner toolHook) toolHook {
157 }161 }
158 }162 }
159 163
164+// changedAFile reads a write_file / edit_file result: true when its
165+// headline says the file was created or changed. An output that is not
166+// text cannot be read, and counts as a change, as before ticket 295.
167+//
168+// changedAFile(&ai.MultipartToolResponse{Output: "main.go: 1 edit(s) applied, +1 -1, first change at line 3"}) // true
169+// changedAFile(&ai.MultipartToolResponse{Output: "main.go: unchanged"}) // false
170+func changedAFile(resp *ai.MultipartToolResponse) bool {
171+ if resp == nil {
172+ return false
173+ }
174+ text, ok := resp.Output.(string)
175+ if !ok {
176+ return true
177+ }
178+ first := strings.SplitN(pathNote.ReplaceAllString(strings.TrimSpace(text), ""), "\n", 2)[0]
179+ m := fileToolSuccess.FindStringSubmatch(first)
180+ if m == nil {
181+ return false // refused, rejected, invalid: nothing was written
182+ }
183+ switch m[1] {
184+ case "unchanged", "would be created", "dry run":
185+ return false
186+ }
187+ return true
188+}
189+
160 // ordinal is n in words for the notice: 3 → "3rd".190 // ordinal is n in words for the notice: 3 → "3rd".
161 func ordinal(n int) string {191 func ordinal(n int) string {
162 switch {192 switch {
modified internal/engine/reread_test.go +50 -2
@@ -55,17 +55,65 @@ func TestRereadsIgnoreACallAfterAChange(t *testing.T) {
5555 test := &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "go test ./..."}}
5656 r.repeated(test, 1)
5757 r.compressed()
58- r.changed(&ai.ToolRequest{Name: "edit_file"})
58+ r.changed(&ai.ToolRequest{Name: "edit_file"}, applied)
5959 if n, refused := r.repeated(test, 1); n != 0 || refused != 0 {
6060 t.Errorf("after an edit: rank %d, refused %d, want neither", n, refused)
6161 }
62- r.changed(&ai.ToolRequest{Name: "bash"}) // not a change mm can see
62+ r.changed(&ai.ToolRequest{Name: "bash"}, applied) // not a change mm can see
6363 r.compressed()
6464 if n, _ := r.repeated(test, 1); n != 1 {
6565 t.Errorf("no edit since: rank %d, want 1", n)
6666 }
6767 }
6868
69+// applied is an edit_file result that changed the file.
70+var applied = &ai.MultipartToolResponse{Output: "main.go: 1 edit(s) applied, +1 -1, first change at line 3"}
71+
72+// Ticket 295: an edit that changed nothing, a refused one or a dry run is
73+// not a change — a model alternating no-op edits and reads is re-reading.
74+func TestRereadsIgnoreEditsThatChangedNothing(t *testing.T) {
75+ outputs := []string{
76+ "main.go: unchanged — already as asked: 1 edit(s) with identical old and new, nothing to change",
77+ "main.go: unchanged",
78+ "main.go: dry run — nothing written (1 edit(s) applied, +1 -1, first change at line 3)",
79+ "edit #1: old text not found — it must match the file exactly",
80+ "[edit_file rejected by the user]",
81+ }
82+ for _, out := range outputs {
83+ var r rereads
84+ read := catRequest("main.go")
85+ r.repeated(read, 0)
86+ r.compressed()
87+ r.changed(&ai.ToolRequest{Name: "edit_file"}, &ai.MultipartToolResponse{Output: out})
88+ if n, _ := r.repeated(read, 0); n != 1 {
89+ t.Errorf("after %q: rank %d, want 1 (a re-read)", out, n)
90+ }
91+ }
92+}
93+
94+func TestChangedAFile(t *testing.T) {
95+ cases := []struct {
96+ out any
97+ want bool
98+ }{
99+ {"main.go: created, 12 line(s)", true},
100+ {"main.go: +3 -1, first change at line 4", true},
101+ {"[path main.go: fixed] main.go: 2 edit(s) applied, +2 -2, first change at line 1", true},
102+ {"main.go: unchanged", false},
103+ {"main.go: would be created, 3 line(s)", false},
104+ {"write_file: permission denied", false},
105+ {map[string]any{"x": 1}, true},
106+ }
107+ for _, c := range cases {
108+ if got := changedAFile(&ai.MultipartToolResponse{Output: c.out}); got != c.want {
109+ t.Errorf("changedAFile(%v) = %v, want %v", c.out, got, c.want)
110+ }
111+ }
112+ if changedAFile(nil) {
113+ t.Error("nil response")
114+ }
115+}
116+
69117 // context.rereadLimit 1: the third identical read is refused, and asking
70118 // again at once is refused again; 0 never refuses.
71119 func TestRereadLimit(t *testing.T) {
@@ -55,17 +55,65 @@ func TestRereadsIgnoreACallAfterAChange(t *testing.T) {
55 test := &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "go test ./..."}}55 test := &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "go test ./..."}}
56 r.repeated(test, 1)56 r.repeated(test, 1)
57 r.compressed()57 r.compressed()
58- r.changed(&ai.ToolRequest{Name: "edit_file"})58+ r.changed(&ai.ToolRequest{Name: "edit_file"}, applied)
59 if n, refused := r.repeated(test, 1); n != 0 || refused != 0 {59 if n, refused := r.repeated(test, 1); n != 0 || refused != 0 {
60 t.Errorf("after an edit: rank %d, refused %d, want neither", n, refused)60 t.Errorf("after an edit: rank %d, refused %d, want neither", n, refused)
61 }61 }
62- r.changed(&ai.ToolRequest{Name: "bash"}) // not a change mm can see62+ r.changed(&ai.ToolRequest{Name: "bash"}, applied) // not a change mm can see
63 r.compressed()63 r.compressed()
64 if n, _ := r.repeated(test, 1); n != 1 {64 if n, _ := r.repeated(test, 1); n != 1 {
65 t.Errorf("no edit since: rank %d, want 1", n)65 t.Errorf("no edit since: rank %d, want 1", n)
66 }66 }
67 }67 }
68 68
69+// applied is an edit_file result that changed the file.
70+var applied = &ai.MultipartToolResponse{Output: "main.go: 1 edit(s) applied, +1 -1, first change at line 3"}
71+
72+// Ticket 295: an edit that changed nothing, a refused one or a dry run is
73+// not a change — a model alternating no-op edits and reads is re-reading.
74+func TestRereadsIgnoreEditsThatChangedNothing(t *testing.T) {
75+ outputs := []string{
76+ "main.go: unchanged — already as asked: 1 edit(s) with identical old and new, nothing to change",
77+ "main.go: unchanged",
78+ "main.go: dry run — nothing written (1 edit(s) applied, +1 -1, first change at line 3)",
79+ "edit #1: old text not found — it must match the file exactly",
80+ "[edit_file rejected by the user]",
81+ }
82+ for _, out := range outputs {
83+ var r rereads
84+ read := catRequest("main.go")
85+ r.repeated(read, 0)
86+ r.compressed()
87+ r.changed(&ai.ToolRequest{Name: "edit_file"}, &ai.MultipartToolResponse{Output: out})
88+ if n, _ := r.repeated(read, 0); n != 1 {
89+ t.Errorf("after %q: rank %d, want 1 (a re-read)", out, n)
90+ }
91+ }
92+}
93+
94+func TestChangedAFile(t *testing.T) {
95+ cases := []struct {
96+ out any
97+ want bool
98+ }{
99+ {"main.go: created, 12 line(s)", true},
100+ {"main.go: +3 -1, first change at line 4", true},
101+ {"[path main.go: fixed] main.go: 2 edit(s) applied, +2 -2, first change at line 1", true},
102+ {"main.go: unchanged", false},
103+ {"main.go: would be created, 3 line(s)", false},
104+ {"write_file: permission denied", false},
105+ {map[string]any{"x": 1}, true},
106+ }
107+ for _, c := range cases {
108+ if got := changedAFile(&ai.MultipartToolResponse{Output: c.out}); got != c.want {
109+ t.Errorf("changedAFile(%v) = %v, want %v", c.out, got, c.want)
110+ }
111+ }
112+ if changedAFile(nil) {
113+ t.Error("nil response")
114+ }
115+}
116+
69 // context.rereadLimit 1: the third identical read is refused, and asking117 // context.rereadLimit 1: the third identical read is refused, and asking
70 // again at once is refused again; 0 never refuses.118 // again at once is refused again; 0 never refuses.
71 func TestRereadLimit(t *testing.T) {119 func TestRereadLimit(t *testing.T) {
modified internal/engine/struggle.go +9 -0
@@ -139,6 +139,15 @@ func answerStruggle(resp *ai.ModelResponse) (ui.Struggle, bool) {
139139 }
140140 return ui.Struggle{Severe: true, Label: label}, true
141141 }
142+ // A run of blank lines is a loop too (ticket 298): a larger limit only
143+ // buys more of them, so "raise max_tokens" would be the wrong advice.
144+ if n := blankLines(resp.Text()); n > 0 {
145+ label := fmt.Sprintf("the model looped: %d blank lines in a row — removed from the answer", n)
146+ if cut {
147+ label += " (it ran until the limit: a larger " + limitKey(config.Cfg.Sampling) + " would not help)"
148+ }
149+ return ui.Struggle{Severe: true, Label: label}, true
150+ }
142151 if cut {
143152 return ui.Struggle{Label: cutAnswerLabel()}, true
144153 }
@@ -139,6 +139,15 @@ func answerStruggle(resp *ai.ModelResponse) (ui.Struggle, bool) {
139 }139 }
140 return ui.Struggle{Severe: true, Label: label}, true140 return ui.Struggle{Severe: true, Label: label}, true
141 }141 }
142+ // A run of blank lines is a loop too (ticket 298): a larger limit only
143+ // buys more of them, so "raise max_tokens" would be the wrong advice.
144+ if n := blankLines(resp.Text()); n > 0 {
145+ label := fmt.Sprintf("the model looped: %d blank lines in a row — removed from the answer", n)
146+ if cut {
147+ label += " (it ran until the limit: a larger " + limitKey(config.Cfg.Sampling) + " would not help)"
148+ }
149+ return ui.Struggle{Severe: true, Label: label}, true
150+ }
142 if cut {151 if cut {
143 return ui.Struggle{Label: cutAnswerLabel()}, true152 return ui.Struggle{Label: cutAnswerLabel()}, true
144 }153 }
added internal/engine/stuckanswer.go +91 -0
new file mode 100644
@@ -0,0 +1,91 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "slices"
7+
8+ "mm/internal/config"
9+
10+ "github.com/firebase/genkit/go/ai"
11+ "github.com/firebase/genkit/go/genkit"
12+)
13+
14+// The answer after the loop detector's stop (ticket 296).
15+//
16+// The detector ends a turn whose model repeats the same failing tool call
17+// (detector.Stuck). Until ticket 296 that was the end: the user got an
18+// error and no answer. Seen 2026-12-02 with Qwen3-Coder-Next: the work was
19+// done and verified — built, run, ten curl calls, all correct — and the
20+// model then sent the same `plan update` without its status five times; the
21+// turn ended in error after a successful run. A looping TEXT is already
22+// handed back for an answer (textloop.go): a looping tool call now is too.
23+//
24+// The tool calls of the last reply are answered "not run", a note asks for
25+// the final answer, and the model is called ONCE more WITHOUT tools: it can
26+// only answer. If that call fails, or brings no text, the turn ends with the
27+// detector's error, as before.
28+
29+// stuckAnswerNote is what the model reads after the stop; %s is the
30+// detector's sentence.
31+const stuckAnswerNote = argsRetryPrefix + "mm stopped your tool calls: %s. No more tools in this turn. " +
32+ "Give your final answer now: what you did, what works, and what is left to do or failed — " +
33+ "from what is already in this conversation. Do not call any tool.]"
34+
35+// stuckToolOutput answers each tool call of the reply mm stopped.
36+const stuckToolOutput = argsRetryPrefix + "not run — the loop detector stopped the tool calls]"
37+
38+// answerAfterStuck asks the model, once and without tools, for its answer
39+// after the detector stopped the turn with stuck. It returns the answer, or
40+// stuck itself when none came.
41+func (t *turn) answerAfterStuck(ctx context.Context, guard *toolCallGuard, stuck error) (*ai.ModelResponse, error) {
42+ line, _ := stuckTurn(stuck)
43+ history := stuckHistory(t.full, t.reply, line)
44+ struggle(line+" — asked the model for its final answer, without tools", "loop detector stop — asked for the answer")
45+ t.full = history
46+ t.pl.expect()
47+ resp, err := genkit.Generate(ctx, t.e.G,
48+ ai.WithModelName(t.e.Model),
49+ ai.WithMessages(history...),
50+ ai.WithConfig(config.Cfg.Sampling),
51+ ai.WithStreaming(t.onChunk(guard)))
52+ if !isAnswer(resp, err) || saidNothing(resp) {
53+ return nil, stuck
54+ }
55+ dropReasoning(resp)
56+ return resp, nil
57+}
58+
59+// stuckHistory is the conversation the final call reads: the last request,
60+// the reply whose tool calls were stopped, a "not run" answer to each of
61+// them (a server refuses a tool call left without its result), and the
62+// note. reply may be nil.
63+//
64+// stuckHistory(full, reply, "the model repeated the same plan call 6 times …")
65+func stuckHistory(full []*ai.Message, reply *ai.Message, line string) []*ai.Message {
66+ history := slices.Clone(full)
67+ if reply != nil {
68+ history = append(history, reply)
69+ if answers := notRunAnswers(reply); answers != nil {
70+ history = append(history, answers)
71+ }
72+ }
73+ return append(history, noteMessage(fmt.Sprintf(stuckAnswerNote, line)))
74+}
75+
76+// notRunAnswers is the tool message answering every tool call of reply with
77+// stuckToolOutput; nil when the reply called no tool.
78+func notRunAnswers(reply *ai.Message) *ai.Message {
79+ var parts []*ai.Part
80+ for _, p := range reply.Content {
81+ if !p.IsToolRequest() {
82+ continue
83+ }
84+ req := p.ToolRequest
85+ parts = append(parts, ai.NewToolResponsePart(&ai.ToolResponse{Name: req.Name, Ref: req.Ref, Output: stuckToolOutput}))
86+ }
87+ if parts == nil {
88+ return nil
89+ }
90+ return ai.NewMessage(ai.RoleTool, nil, parts...)
91+}
new file mode 100644
@@ -0,0 +1,91 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "slices"
7+
8+ "mm/internal/config"
9+
10+ "github.com/firebase/genkit/go/ai"
11+ "github.com/firebase/genkit/go/genkit"
12+)
13+
14+// The answer after the loop detector's stop (ticket 296).
15+//
16+// The detector ends a turn whose model repeats the same failing tool call
17+// (detector.Stuck). Until ticket 296 that was the end: the user got an
18+// error and no answer. Seen 2026-12-02 with Qwen3-Coder-Next: the work was
19+// done and verified — built, run, ten curl calls, all correct — and the
20+// model then sent the same `plan update` without its status five times; the
21+// turn ended in error after a successful run. A looping TEXT is already
22+// handed back for an answer (textloop.go): a looping tool call now is too.
23+//
24+// The tool calls of the last reply are answered "not run", a note asks for
25+// the final answer, and the model is called ONCE more WITHOUT tools: it can
26+// only answer. If that call fails, or brings no text, the turn ends with the
27+// detector's error, as before.
28+
29+// stuckAnswerNote is what the model reads after the stop; %s is the
30+// detector's sentence.
31+const stuckAnswerNote = argsRetryPrefix + "mm stopped your tool calls: %s. No more tools in this turn. " +
32+ "Give your final answer now: what you did, what works, and what is left to do or failed — " +
33+ "from what is already in this conversation. Do not call any tool.]"
34+
35+// stuckToolOutput answers each tool call of the reply mm stopped.
36+const stuckToolOutput = argsRetryPrefix + "not run — the loop detector stopped the tool calls]"
37+
38+// answerAfterStuck asks the model, once and without tools, for its answer
39+// after the detector stopped the turn with stuck. It returns the answer, or
40+// stuck itself when none came.
41+func (t *turn) answerAfterStuck(ctx context.Context, guard *toolCallGuard, stuck error) (*ai.ModelResponse, error) {
42+ line, _ := stuckTurn(stuck)
43+ history := stuckHistory(t.full, t.reply, line)
44+ struggle(line+" — asked the model for its final answer, without tools", "loop detector stop — asked for the answer")
45+ t.full = history
46+ t.pl.expect()
47+ resp, err := genkit.Generate(ctx, t.e.G,
48+ ai.WithModelName(t.e.Model),
49+ ai.WithMessages(history...),
50+ ai.WithConfig(config.Cfg.Sampling),
51+ ai.WithStreaming(t.onChunk(guard)))
52+ if !isAnswer(resp, err) || saidNothing(resp) {
53+ return nil, stuck
54+ }
55+ dropReasoning(resp)
56+ return resp, nil
57+}
58+
59+// stuckHistory is the conversation the final call reads: the last request,
60+// the reply whose tool calls were stopped, a "not run" answer to each of
61+// them (a server refuses a tool call left without its result), and the
62+// note. reply may be nil.
63+//
64+// stuckHistory(full, reply, "the model repeated the same plan call 6 times …")
65+func stuckHistory(full []*ai.Message, reply *ai.Message, line string) []*ai.Message {
66+ history := slices.Clone(full)
67+ if reply != nil {
68+ history = append(history, reply)
69+ if answers := notRunAnswers(reply); answers != nil {
70+ history = append(history, answers)
71+ }
72+ }
73+ return append(history, noteMessage(fmt.Sprintf(stuckAnswerNote, line)))
74+}
75+
76+// notRunAnswers is the tool message answering every tool call of reply with
77+// stuckToolOutput; nil when the reply called no tool.
78+func notRunAnswers(reply *ai.Message) *ai.Message {
79+ var parts []*ai.Part
80+ for _, p := range reply.Content {
81+ if !p.IsToolRequest() {
82+ continue
83+ }
84+ req := p.ToolRequest
85+ parts = append(parts, ai.NewToolResponsePart(&ai.ToolResponse{Name: req.Name, Ref: req.Ref, Output: stuckToolOutput}))
86+ }
87+ if parts == nil {
88+ return nil
89+ }
90+ return ai.NewMessage(ai.RoleTool, nil, parts...)
91+}
added internal/engine/stuckanswer_test.go +87 -0
new file mode 100644
@@ -0,0 +1,87 @@
1+package engine
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+
8+ "mm/internal/detector"
9+
10+ "github.com/firebase/genkit/go/ai"
11+ "github.com/firebase/genkit/go/genkit"
12+)
13+
14+// Ticket 296: the work is done, then the model repeats the same failing
15+// plan call until the detector stops it. The turn still ends with an
16+// answer: one more model call, without tools, after a note — and the
17+// stopped tool call gets a "not run" result in the history.
18+func TestStuckToolIsFollowedByAnAnswerWithoutTools(t *testing.T) {
19+ planCall := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "plan", Ref: "c6", Input: map[string]any{"action": "update", "taskId": 6}}))
20+ answer := modelTurn(ai.NewTextPart("The server builds and all 10 curl checks pass; labels.yaml is written."))
21+ g, seen := scriptedGenkit(t, planCall, answer)
22+ genkit.DefineTool(g, "plan", "a todo list",
23+ func(_ *ai.ToolContext, _ map[string]any) (string, error) {
24+ return "", &detector.Stuck{Tool: "plan", Repeats: 6}
25+ })
26+
27+ resp, full, err := testEngine(g).Generate(context.Background(),
28+ []*ai.Message{ai.NewUserTextMessage("write the label API")},
29+ []ai.ToolRef{ai.ToolName("plan")})
30+ if err != nil {
31+ t.Fatalf("Generate: %v — the stop should have been followed by an answer", err)
32+ }
33+ if !strings.Contains(resp.Text(), "all 10 curl checks pass") {
34+ t.Errorf("answer = %q", resp.Text())
35+ }
36+ if len(*seen) != 2 {
37+ t.Fatalf("model called %d times, want 2", len(*seen))
38+ }
39+ final := (*seen)[1]
40+ if len(final.Tools) != 0 {
41+ t.Errorf("the final call offered %d tool(s), want none", len(final.Tools))
42+ }
43+ note := final.Messages[len(final.Messages)-1].Text()
44+ if !strings.Contains(note, "mm stopped your tool calls: the model repeated the same plan call 6 times") || !strings.Contains(note, "Give your final answer now") {
45+ t.Errorf("note = %q", note)
46+ }
47+ notRun := false
48+ for _, m := range full {
49+ for _, p := range m.Content {
50+ if p.IsToolResponse() && p.ToolResponse.Ref == "c6" && p.ToolResponse.Output == stuckToolOutput {
51+ notRun = true
52+ }
53+ }
54+ }
55+ if !notRun {
56+ t.Error("the stopped plan call has no \"not run\" result in the history")
57+ }
58+ if last := full[len(full)-1]; last.Text() != resp.Text() {
59+ t.Errorf("the history does not end with the answer: %q", last.Text())
60+ }
61+}
62+
63+// A final call that tries a tool anyway is no answer: the detector's error
64+// stands.
65+func TestStuckToolWithAToolCallForAnswerKeepsTheError(t *testing.T) {
66+ planCall := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "plan", Ref: "c1", Input: map[string]any{"action": "update"}}))
67+ g, _ := scriptedGenkit(t, planCall, planCall)
68+ genkit.DefineTool(g, "plan", "a todo list",
69+ func(_ *ai.ToolContext, _ map[string]any) (string, error) {
70+ return "", &detector.Stuck{Tool: "plan", Repeats: 6}
71+ })
72+ _, _, err := testEngine(g).Generate(context.Background(),
73+ []*ai.Message{ai.NewUserTextMessage("go")}, []ai.ToolRef{ai.ToolName("plan")})
74+ if _, stuck := stuckTurn(err); !stuck {
75+ t.Errorf("err = %v, want the detector's stop", err)
76+ }
77+}
78+
79+func TestStuckHistoryWithoutReply(t *testing.T) {
80+ h := stuckHistory([]*ai.Message{ai.NewUserTextMessage("q")}, nil, "the model repeated the same bash call 4 times")
81+ if len(h) != 2 || !strings.Contains(h[1].Text(), "the same bash call 4 times") {
82+ t.Errorf("history = %v", h)
83+ }
84+ if notRunAnswers(ai.NewModelTextMessage("text only")) != nil {
85+ t.Error("a reply without tool calls needs no answers")
86+ }
87+}
new file mode 100644
@@ -0,0 +1,87 @@
1+package engine
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+
8+ "mm/internal/detector"
9+
10+ "github.com/firebase/genkit/go/ai"
11+ "github.com/firebase/genkit/go/genkit"
12+)
13+
14+// Ticket 296: the work is done, then the model repeats the same failing
15+// plan call until the detector stops it. The turn still ends with an
16+// answer: one more model call, without tools, after a note — and the
17+// stopped tool call gets a "not run" result in the history.
18+func TestStuckToolIsFollowedByAnAnswerWithoutTools(t *testing.T) {
19+ planCall := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "plan", Ref: "c6", Input: map[string]any{"action": "update", "taskId": 6}}))
20+ answer := modelTurn(ai.NewTextPart("The server builds and all 10 curl checks pass; labels.yaml is written."))
21+ g, seen := scriptedGenkit(t, planCall, answer)
22+ genkit.DefineTool(g, "plan", "a todo list",
23+ func(_ *ai.ToolContext, _ map[string]any) (string, error) {
24+ return "", &detector.Stuck{Tool: "plan", Repeats: 6}
25+ })
26+
27+ resp, full, err := testEngine(g).Generate(context.Background(),
28+ []*ai.Message{ai.NewUserTextMessage("write the label API")},
29+ []ai.ToolRef{ai.ToolName("plan")})
30+ if err != nil {
31+ t.Fatalf("Generate: %v — the stop should have been followed by an answer", err)
32+ }
33+ if !strings.Contains(resp.Text(), "all 10 curl checks pass") {
34+ t.Errorf("answer = %q", resp.Text())
35+ }
36+ if len(*seen) != 2 {
37+ t.Fatalf("model called %d times, want 2", len(*seen))
38+ }
39+ final := (*seen)[1]
40+ if len(final.Tools) != 0 {
41+ t.Errorf("the final call offered %d tool(s), want none", len(final.Tools))
42+ }
43+ note := final.Messages[len(final.Messages)-1].Text()
44+ if !strings.Contains(note, "mm stopped your tool calls: the model repeated the same plan call 6 times") || !strings.Contains(note, "Give your final answer now") {
45+ t.Errorf("note = %q", note)
46+ }
47+ notRun := false
48+ for _, m := range full {
49+ for _, p := range m.Content {
50+ if p.IsToolResponse() && p.ToolResponse.Ref == "c6" && p.ToolResponse.Output == stuckToolOutput {
51+ notRun = true
52+ }
53+ }
54+ }
55+ if !notRun {
56+ t.Error("the stopped plan call has no \"not run\" result in the history")
57+ }
58+ if last := full[len(full)-1]; last.Text() != resp.Text() {
59+ t.Errorf("the history does not end with the answer: %q", last.Text())
60+ }
61+}
62+
63+// A final call that tries a tool anyway is no answer: the detector's error
64+// stands.
65+func TestStuckToolWithAToolCallForAnswerKeepsTheError(t *testing.T) {
66+ planCall := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "plan", Ref: "c1", Input: map[string]any{"action": "update"}}))
67+ g, _ := scriptedGenkit(t, planCall, planCall)
68+ genkit.DefineTool(g, "plan", "a todo list",
69+ func(_ *ai.ToolContext, _ map[string]any) (string, error) {
70+ return "", &detector.Stuck{Tool: "plan", Repeats: 6}
71+ })
72+ _, _, err := testEngine(g).Generate(context.Background(),
73+ []*ai.Message{ai.NewUserTextMessage("go")}, []ai.ToolRef{ai.ToolName("plan")})
74+ if _, stuck := stuckTurn(err); !stuck {
75+ t.Errorf("err = %v, want the detector's stop", err)
76+ }
77+}
78+
79+func TestStuckHistoryWithoutReply(t *testing.T) {
80+ h := stuckHistory([]*ai.Message{ai.NewUserTextMessage("q")}, nil, "the model repeated the same bash call 4 times")
81+ if len(h) != 2 || !strings.Contains(h[1].Text(), "the same bash call 4 times") {
82+ t.Errorf("history = %v", h)
83+ }
84+ if notRunAnswers(ai.NewModelTextMessage("text only")) != nil {
85+ t.Error("a reply without tool calls needs no answers")
86+ }
87+}
modified internal/engine/textloop.go +41 -1
@@ -31,6 +31,16 @@ const loopRepeats = 20
3131 // legitimate text.
3232 const loopMinUnit = 12
3333
34+// streamBlankLines is how many blank lines in a row cut a streaming call
35+// (ticket 298): Mellum2 streamed 3,935 of them, 40 seconds of a call that
36+// could only end at max_tokens. Higher than loopBlankLines: the stream is
37+// cut, not merely cleaned.
38+const streamBlankLines = 100
39+
40+// blankSample names a run of blank lines where a repeated sentence would
41+// be quoted.
42+const blankSample = "(a blank line)"
43+
3444 // maxLoopRetries is how many times one generation hands a looping model call
3545 // back to the model.
3646 const maxLoopRetries = 1
@@ -44,6 +54,7 @@ type loopWatch struct {
4454 pending string // the unfinished sentence
4555 last string
4656 count int
57+ blanks int // blank lines in a row
4758 sample string // the repeated sentence, once tripped
4859 times int
4960 tripped bool
@@ -54,7 +65,7 @@ type loopWatch struct {
5465 func (w *loopWatch) arm(cancel context.CancelFunc) {
5566 w.mu.Lock()
5667 defer w.mu.Unlock()
57- w.pending, w.last, w.count = "", "", 0
68+ w.pending, w.last, w.count, w.blanks = "", "", 0, 0
5869 w.tripped, w.sample, w.times = false, "", 0
5970 w.cancel = cancel
6071 }
@@ -75,6 +86,13 @@ func (w *loopWatch) feed(text string) {
7586 }
7687 unit := strings.TrimSpace(w.pending[:end])
7788 w.pending = w.pending[end:]
89+ if unit == "" {
90+ if w.blank() {
91+ return
92+ }
93+ continue
94+ }
95+ w.blanks = 0
7896 if len(unit) < loopMinUnit {
7997 continue
8098 }
@@ -91,6 +109,20 @@ func (w *loopWatch) feed(text string) {
91109 }
92110 }
93111
112+// blank counts one more blank unit and trips the watch past
113+// streamBlankLines of them in a row; it reports whether it tripped. A
114+// unit is blank when only white space stood between two sentence ends:
115+// "\n\n\n" is three of them. w.mu is held.
116+func (w *loopWatch) blank() bool {
117+ w.blanks++
118+ if w.blanks < streamBlankLines {
119+ return false
120+ }
121+ w.tripped, w.sample, w.times = true, blankSample, w.blanks
122+ w.cancel()
123+ return true
124+}
125+
94126 // sentenceEnd is the index just past the first sentence end in s: a newline,
95127 // or '.', '!', '?' followed by white space. -1 when s holds no full sentence.
96128 func sentenceEnd(s string) int {
@@ -129,6 +161,11 @@ func (w *loopWatch) disarm() {
129161
130162 // loopRetryNote is what the model reads after a call cut for looping.
131163 func loopRetryNote(sample string, times int) *ai.Message {
164+ if sample == blankSample {
165+ return noteMessage(fmt.Sprintf("%syour reply turned into blank lines — %d in a row — so mm stopped it. "+
166+ "Do NOT start over. Continue from where you were: make the next tool call, or give your answer, in a few lines.]",
167+ argsRetryPrefix, times))
168+ }
132169 return noteMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+
133170 "Do NOT start over and do not repeat that sentence. You already have what you need in this conversation: "+
134171 "give your answer now (or make the one tool call still needed), with at most a few lines of reasoning.]",
@@ -142,6 +179,9 @@ type loopError struct {
142179 }
143180
144181 func (e loopError) Error() string {
182+ if e.sample == blankSample {
183+ return fmt.Sprintf("the model looped: %d blank lines in a row — stopped; ask again, or lower the temperature", e.times)
184+ }
145185 return fmt.Sprintf("the model looped: %q repeated %d times in a row — stopped; ask again, or lower the temperature / reasoning effort", shorten(e.sample, 80), e.times)
146186 }
147187
@@ -31,6 +31,16 @@ const loopRepeats = 20
31 // legitimate text.31 // legitimate text.
32 const loopMinUnit = 1232 const loopMinUnit = 12
33 33
34+// streamBlankLines is how many blank lines in a row cut a streaming call
35+// (ticket 298): Mellum2 streamed 3,935 of them, 40 seconds of a call that
36+// could only end at max_tokens. Higher than loopBlankLines: the stream is
37+// cut, not merely cleaned.
38+const streamBlankLines = 100
39+
40+// blankSample names a run of blank lines where a repeated sentence would
41+// be quoted.
42+const blankSample = "(a blank line)"
43+
34 // maxLoopRetries is how many times one generation hands a looping model call44 // maxLoopRetries is how many times one generation hands a looping model call
35 // back to the model.45 // back to the model.
36 const maxLoopRetries = 146 const maxLoopRetries = 1
@@ -44,6 +54,7 @@ type loopWatch struct {
44 pending string // the unfinished sentence54 pending string // the unfinished sentence
45 last string55 last string
46 count int56 count int
57+ blanks int // blank lines in a row
47 sample string // the repeated sentence, once tripped58 sample string // the repeated sentence, once tripped
48 times int59 times int
49 tripped bool60 tripped bool
@@ -54,7 +65,7 @@ type loopWatch struct {
54 func (w *loopWatch) arm(cancel context.CancelFunc) {65 func (w *loopWatch) arm(cancel context.CancelFunc) {
55 w.mu.Lock()66 w.mu.Lock()
56 defer w.mu.Unlock()67 defer w.mu.Unlock()
57- w.pending, w.last, w.count = "", "", 068+ w.pending, w.last, w.count, w.blanks = "", "", 0, 0
58 w.tripped, w.sample, w.times = false, "", 069 w.tripped, w.sample, w.times = false, "", 0
59 w.cancel = cancel70 w.cancel = cancel
60 }71 }
@@ -75,6 +86,13 @@ func (w *loopWatch) feed(text string) {
75 }86 }
76 unit := strings.TrimSpace(w.pending[:end])87 unit := strings.TrimSpace(w.pending[:end])
77 w.pending = w.pending[end:]88 w.pending = w.pending[end:]
89+ if unit == "" {
90+ if w.blank() {
91+ return
92+ }
93+ continue
94+ }
95+ w.blanks = 0
78 if len(unit) < loopMinUnit {96 if len(unit) < loopMinUnit {
79 continue97 continue
80 }98 }
@@ -91,6 +109,20 @@ func (w *loopWatch) feed(text string) {
91 }109 }
92 }110 }
93 111
112+// blank counts one more blank unit and trips the watch past
113+// streamBlankLines of them in a row; it reports whether it tripped. A
114+// unit is blank when only white space stood between two sentence ends:
115+// "\n\n\n" is three of them. w.mu is held.
116+func (w *loopWatch) blank() bool {
117+ w.blanks++
118+ if w.blanks < streamBlankLines {
119+ return false
120+ }
121+ w.tripped, w.sample, w.times = true, blankSample, w.blanks
122+ w.cancel()
123+ return true
124+}
125+
94 // sentenceEnd is the index just past the first sentence end in s: a newline,126 // sentenceEnd is the index just past the first sentence end in s: a newline,
95 // or '.', '!', '?' followed by white space. -1 when s holds no full sentence.127 // or '.', '!', '?' followed by white space. -1 when s holds no full sentence.
96 func sentenceEnd(s string) int {128 func sentenceEnd(s string) int {
@@ -129,6 +161,11 @@ func (w *loopWatch) disarm() {
129 161
130 // loopRetryNote is what the model reads after a call cut for looping.162 // loopRetryNote is what the model reads after a call cut for looping.
131 func loopRetryNote(sample string, times int) *ai.Message {163 func loopRetryNote(sample string, times int) *ai.Message {
164+ if sample == blankSample {
165+ return noteMessage(fmt.Sprintf("%syour reply turned into blank lines — %d in a row — so mm stopped it. "+
166+ "Do NOT start over. Continue from where you were: make the next tool call, or give your answer, in a few lines.]",
167+ argsRetryPrefix, times))
168+ }
132 return noteMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+169 return noteMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+
133 "Do NOT start over and do not repeat that sentence. You already have what you need in this conversation: "+170 "Do NOT start over and do not repeat that sentence. You already have what you need in this conversation: "+
134 "give your answer now (or make the one tool call still needed), with at most a few lines of reasoning.]",171 "give your answer now (or make the one tool call still needed), with at most a few lines of reasoning.]",
@@ -142,6 +179,9 @@ type loopError struct {
142 }179 }
143 180
144 func (e loopError) Error() string {181 func (e loopError) Error() string {
182+ if e.sample == blankSample {
183+ return fmt.Sprintf("the model looped: %d blank lines in a row — stopped; ask again, or lower the temperature", e.times)
184+ }
145 return fmt.Sprintf("the model looped: %q repeated %d times in a row — stopped; ask again, or lower the temperature / reasoning effort", shorten(e.sample, 80), e.times)185 return fmt.Sprintf("the model looped: %q repeated %d times in a row — stopped; ask again, or lower the temperature / reasoning effort", shorten(e.sample, 80), e.times)
146 }186 }
147 187
modified internal/engine/turn.go +4 -2
@@ -15,7 +15,8 @@ import (
1515 // One turn of generate (engine.go): its state, and the steps Genkit calls
1616 // back into — every model call (wrapModel, with the hand-backs: a looping
1717 // stream, a broken stream, broken tool-call arguments, a reply cut while
18-// reasoning, an answer after a failed file change), every tool call
18+// reasoning, a tool call left in the reasoning, an answer after a failed
19+// file change), every tool call
1920 // (wrapTool), every streamed chunk (onChunk, emit).
2021
2122 // turn is the state of one generation.
@@ -51,7 +52,7 @@ type turn struct {
5152 // (reread.go, ticket 292).
5253 reads rereads
5354 // The hand-backs of this generation, each bounded by its max*Retries.
54- argRetries, cutRetries, loopRetries, editRetries int
55+ argRetries, cutRetries, loopRetries, editRetries, reasoningCallRetries int
5556 // printed: some answer text reached the screen or the client.
5657 printed bool
5758 }
@@ -259,6 +260,7 @@ func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.Mo
259260 resp, err = t.retryBrokenStream(ctx, call, resp, err)
260261 resp, err = t.retryBrokenArgs(ctx, params, call, resp, err)
261262 resp, err = t.retryCutReasoning(ctx, params, call, resp, err)
263+ resp, err = t.retryCallInReasoning(ctx, params, call, resp, err)
262264 resp, err = t.retryFailedEdit(ctx, params, call, resp, err)
263265 t.recordUsage(params, resp)
264266 dropReasoning(resp)
@@ -15,7 +15,8 @@ import (
15 // One turn of generate (engine.go): its state, and the steps Genkit calls15 // One turn of generate (engine.go): its state, and the steps Genkit calls
16 // back into — every model call (wrapModel, with the hand-backs: a looping16 // back into — every model call (wrapModel, with the hand-backs: a looping
17 // stream, a broken stream, broken tool-call arguments, a reply cut while17 // stream, a broken stream, broken tool-call arguments, a reply cut while
18-// reasoning, an answer after a failed file change), every tool call18+// reasoning, a tool call left in the reasoning, an answer after a failed
19+// file change), every tool call
19 // (wrapTool), every streamed chunk (onChunk, emit).20 // (wrapTool), every streamed chunk (onChunk, emit).
20 21
21 // turn is the state of one generation.22 // turn is the state of one generation.
@@ -51,7 +52,7 @@ type turn struct {
51 // (reread.go, ticket 292).52 // (reread.go, ticket 292).
52 reads rereads53 reads rereads
53 // The hand-backs of this generation, each bounded by its max*Retries.54 // The hand-backs of this generation, each bounded by its max*Retries.
54- argRetries, cutRetries, loopRetries, editRetries int55+ argRetries, cutRetries, loopRetries, editRetries, reasoningCallRetries int
55 // printed: some answer text reached the screen or the client.56 // printed: some answer text reached the screen or the client.
56 printed bool57 printed bool
57 }58 }
@@ -259,6 +260,7 @@ func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.Mo
259 resp, err = t.retryBrokenStream(ctx, call, resp, err)260 resp, err = t.retryBrokenStream(ctx, call, resp, err)
260 resp, err = t.retryBrokenArgs(ctx, params, call, resp, err)261 resp, err = t.retryBrokenArgs(ctx, params, call, resp, err)
261 resp, err = t.retryCutReasoning(ctx, params, call, resp, err)262 resp, err = t.retryCutReasoning(ctx, params, call, resp, err)
263+ resp, err = t.retryCallInReasoning(ctx, params, call, resp, err)
262 resp, err = t.retryFailedEdit(ctx, params, call, resp, err)264 resp, err = t.retryFailedEdit(ctx, params, call, resp, err)
263 t.recordUsage(params, resp)265 t.recordUsage(params, resp)
264 dropReasoning(resp)266 dropReasoning(resp)
added internal/fileedit/controlchars.go +68 -0
new file mode 100644
@@ -0,0 +1,68 @@
1+package fileedit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// controlNote follows a diff whose added lines hold control characters. The
9+// usual cause is JSON: "\func" in a tool call's arguments is a form feed
10+// followed by "unc" (ticket 294, seen with every Mellum run of 2026-12-02).
11+const controlNote = `note: the new text holds control characters, shown escaped above (\f is U+000C, a form feed). In JSON, "\f" IS a form feed: write "\n" then "f" for a new line, or "\\f" for a backslash and an f.`
12+
13+// controlNoteFor is controlNote and a new line when an added line holds a
14+// control character, "" otherwise.
15+func controlNoteFor(lines []line) string {
16+ for _, l := range lines {
17+ if l.op == add && strings.ContainsFunc(l.text, isHidden) {
18+ return controlNote + "\n"
19+ }
20+ }
21+ return ""
22+}
23+
24+// visible shows a line's control characters as escapes — \f, \x00… — instead
25+// of writing them raw, where they are invisible: the model saw "unc main()"
26+// with a form feed in front, could not tell what to replace, and its edit
27+// failed (ticket 294). A tab stays a tab, and a carriage return at the end
28+// of the line stays too: CRLF files would otherwise show it on every line.
29+//
30+// visible("\func main()") // `\func main()`
31+// visible("a\x00b") // `a\x00b`
32+func visible(text string) string {
33+ if !strings.ContainsFunc(text, isHidden) {
34+ return text
35+ }
36+ body, cr := strings.CutSuffix(text, "\r")
37+ var b strings.Builder
38+ for _, r := range body {
39+ if isHidden(r) {
40+ b.WriteString(escapeControl(r))
41+ } else {
42+ b.WriteRune(r)
43+ }
44+ }
45+ if cr {
46+ b.WriteString("\r")
47+ }
48+ return b.String()
49+}
50+
51+// isHidden reports a control character that a line would show as nothing:
52+// C0 controls but the tab, and DEL. The carriage return counts here;
53+// visible keeps the one that ends a CRLF line.
54+func isHidden(r rune) bool {
55+ return (r < 0x20 && r != '\t') || r == 0x7f
56+}
57+
58+// controlEscapes are the escapes Go and JSON strings share; any other
59+// control character is written \xNN.
60+var controlEscapes = map[rune]string{'\f': `\f`, '\v': `\v`, '\b': `\b`, '\a': `\a`, '\r': `\r`}
61+
62+// escapeControl is the escape a Go or JSON string would use for r.
63+func escapeControl(r rune) string {
64+ if escaped, ok := controlEscapes[r]; ok {
65+ return escaped
66+ }
67+ return fmt.Sprintf(`\x%02x`, r)
68+}
new file mode 100644
@@ -0,0 +1,68 @@
1+package fileedit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// controlNote follows a diff whose added lines hold control characters. The
9+// usual cause is JSON: "\func" in a tool call's arguments is a form feed
10+// followed by "unc" (ticket 294, seen with every Mellum run of 2026-12-02).
11+const controlNote = `note: the new text holds control characters, shown escaped above (\f is U+000C, a form feed). In JSON, "\f" IS a form feed: write "\n" then "f" for a new line, or "\\f" for a backslash and an f.`
12+
13+// controlNoteFor is controlNote and a new line when an added line holds a
14+// control character, "" otherwise.
15+func controlNoteFor(lines []line) string {
16+ for _, l := range lines {
17+ if l.op == add && strings.ContainsFunc(l.text, isHidden) {
18+ return controlNote + "\n"
19+ }
20+ }
21+ return ""
22+}
23+
24+// visible shows a line's control characters as escapes — \f, \x00… — instead
25+// of writing them raw, where they are invisible: the model saw "unc main()"
26+// with a form feed in front, could not tell what to replace, and its edit
27+// failed (ticket 294). A tab stays a tab, and a carriage return at the end
28+// of the line stays too: CRLF files would otherwise show it on every line.
29+//
30+// visible("\func main()") // `\func main()`
31+// visible("a\x00b") // `a\x00b`
32+func visible(text string) string {
33+ if !strings.ContainsFunc(text, isHidden) {
34+ return text
35+ }
36+ body, cr := strings.CutSuffix(text, "\r")
37+ var b strings.Builder
38+ for _, r := range body {
39+ if isHidden(r) {
40+ b.WriteString(escapeControl(r))
41+ } else {
42+ b.WriteRune(r)
43+ }
44+ }
45+ if cr {
46+ b.WriteString("\r")
47+ }
48+ return b.String()
49+}
50+
51+// isHidden reports a control character that a line would show as nothing:
52+// C0 controls but the tab, and DEL. The carriage return counts here;
53+// visible keeps the one that ends a CRLF line.
54+func isHidden(r rune) bool {
55+ return (r < 0x20 && r != '\t') || r == 0x7f
56+}
57+
58+// controlEscapes are the escapes Go and JSON strings share; any other
59+// control character is written \xNN.
60+var controlEscapes = map[rune]string{'\f': `\f`, '\v': `\v`, '\b': `\b`, '\a': `\a`, '\r': `\r`}
61+
62+// escapeControl is the escape a Go or JSON string would use for r.
63+func escapeControl(r rune) string {
64+ if escaped, ok := controlEscapes[r]; ok {
65+ return escaped
66+ }
67+ return fmt.Sprintf(`\x%02x`, r)
68+}
modified internal/fileedit/diff_render.go +2 -2
@@ -143,8 +143,8 @@ func (r comparison) render() string {
143143 } else {
144144 no = current + 1
145145 }
146- fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, l.text)
146+ fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, visible(l.text))
147147 }
148148 }
149- return b.String()
149+ return b.String() + controlNoteFor(r.lines)
150150 }
@@ -143,8 +143,8 @@ func (r comparison) render() string {
143 } else {143 } else {
144 no = current + 1144 no = current + 1
145 }145 }
146- fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, l.text)146+ fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, visible(l.text))
147 }147 }
148 }148 }
149- return b.String()149+ return b.String() + controlNoteFor(r.lines)
150 }150 }
modified internal/fileedit/edits.go +32 -0
@@ -61,6 +61,9 @@ func resolve(body string, list []Edit) ([]span, int, error) {
6161 loose := 0
6262 spans := make([]span, 0, len(list))
6363 for i, e := range list {
64+ if err := checkLine(body, e, i); err != nil {
65+ return nil, 0, err
66+ }
6467 if e.Old == e.New && e.Old != "" {
6568 // Already as asked (ticket 154): nothing to replace, but the text
6669 // must be THERE — an identical pair for a text the file does not
@@ -158,6 +161,35 @@ func pickOccurrence(body string, e Edit, i int, spans []match, loose bool) (span
158161 i+1, len(spans), occurrenceLines(body, spans), e.Line)
159162 }
160163
164+// checkLine refuses a "line" outside the file (ticket 294): Mellum2 sent
165+// line 1000000000000000 and was told "1 edit(s) applied" — the old text was
166+// unique, so the line was ignored, and the model learned nothing about its
167+// picture of the file. A line INSIDE the file still only matters when old
168+// appears several times (pickOccurrence). 0 means no line.
169+//
170+// checkLine("a\nb\n", Edit{Old: "a", New: "c", Line: 9}, 0) // error: the file has 2 lines
171+func checkLine(body string, e Edit, i int) error {
172+ if e.Line == 0 {
173+ return nil
174+ }
175+ total := lineCount(body)
176+ if e.Line > 0 && e.Line <= total {
177+ return nil
178+ }
179+ return fmt.Errorf(
180+ "edit #%d: \"line\": %d is outside the file, which has %d line(s) — \"line\" is only needed when old appears several times; leave it out, or give the line where old starts, as read_file numbered=true shows it",
181+ i+1, e.Line, total)
182+}
183+
184+// lineCount is the number of lines of a body: a final newline does not
185+// start one more.
186+func lineCount(body string) int {
187+ if body == "" {
188+ return 0
189+ }
190+ return strings.Count(strings.TrimSuffix(body, "\n"), "\n") + 1
191+}
192+
161193 // present checks that the text of an edit whose old and new are identical is
162194 // in the file. Such an edit changes nothing: a model sends it when it believes
163195 // a change still has to be made that is in fact already there — a success,
@@ -61,6 +61,9 @@ func resolve(body string, list []Edit) ([]span, int, error) {
61 loose := 061 loose := 0
62 spans := make([]span, 0, len(list))62 spans := make([]span, 0, len(list))
63 for i, e := range list {63 for i, e := range list {
64+ if err := checkLine(body, e, i); err != nil {
65+ return nil, 0, err
66+ }
64 if e.Old == e.New && e.Old != "" {67 if e.Old == e.New && e.Old != "" {
65 // Already as asked (ticket 154): nothing to replace, but the text68 // Already as asked (ticket 154): nothing to replace, but the text
66 // must be THERE — an identical pair for a text the file does not69 // must be THERE — an identical pair for a text the file does not
@@ -158,6 +161,35 @@ func pickOccurrence(body string, e Edit, i int, spans []match, loose bool) (span
158 i+1, len(spans), occurrenceLines(body, spans), e.Line)161 i+1, len(spans), occurrenceLines(body, spans), e.Line)
159 }162 }
160 163
164+// checkLine refuses a "line" outside the file (ticket 294): Mellum2 sent
165+// line 1000000000000000 and was told "1 edit(s) applied" — the old text was
166+// unique, so the line was ignored, and the model learned nothing about its
167+// picture of the file. A line INSIDE the file still only matters when old
168+// appears several times (pickOccurrence). 0 means no line.
169+//
170+// checkLine("a\nb\n", Edit{Old: "a", New: "c", Line: 9}, 0) // error: the file has 2 lines
171+func checkLine(body string, e Edit, i int) error {
172+ if e.Line == 0 {
173+ return nil
174+ }
175+ total := lineCount(body)
176+ if e.Line > 0 && e.Line <= total {
177+ return nil
178+ }
179+ return fmt.Errorf(
180+ "edit #%d: \"line\": %d is outside the file, which has %d line(s) — \"line\" is only needed when old appears several times; leave it out, or give the line where old starts, as read_file numbered=true shows it",
181+ i+1, e.Line, total)
182+}
183+
184+// lineCount is the number of lines of a body: a final newline does not
185+// start one more.
186+func lineCount(body string) int {
187+ if body == "" {
188+ return 0
189+ }
190+ return strings.Count(strings.TrimSuffix(body, "\n"), "\n") + 1
191+}
192+
161 // present checks that the text of an edit whose old and new are identical is193 // present checks that the text of an edit whose old and new are identical is
162 // in the file. Such an edit changes nothing: a model sends it when it believes194 // in the file. Such an edit changes nothing: a model sends it when it believes
163 // a change still has to be made that is in fact already there — a success,195 // a change still has to be made that is in fact already there — a success,
modified internal/fileedit/fileedit_test.go +39 -0
@@ -353,3 +353,42 @@ func ExampleIdentical() {
353353 fmt.Println(Identical([]Edit{{Old: "a", New: "a"}, {Old: "b", New: "c"}}))
354354 // Output: 1
355355 }
356+
357+// TestVisibleEscapesControlCharacters is ticket 294, item 3: a form feed in
358+// written code was invisible in the diff.
359+func TestVisibleEscapesControlCharacters(t *testing.T) {
360+ cases := map[string]string{
361+ "\func main()": `\func main()`,
362+ "a\x00b\x1bc": `a\x00b\x1bc`,
363+ "\tindented": "\tindented",
364+ "crlf line\r": "crlf line\r",
365+ "mid\rline": `mid\rline`,
366+ "del\x7f": `del\x7f`,
367+ "plain, café ✓": "plain, café ✓",
368+ }
369+ for in, want := range cases {
370+ if got := visible(in); got != want {
371+ t.Errorf("visible(%q) = %q, want %q", in, got, want)
372+ }
373+ }
374+}
375+
376+// The diff shows the escape and explains it; a diff without control
377+// characters carries no note.
378+func TestRenderShowsControlCharacters(t *testing.T) {
379+ out := compare("package main\n", "package main\n\func main() {}\n").render()
380+ if !strings.Contains(out, `+ \func main() {}`) || !strings.Contains(out, "note: the new text holds control characters") {
381+ t.Errorf("render = %q", out)
382+ }
383+ if strings.ContainsRune(out, '\f') {
384+ t.Errorf("render kept a raw form feed: %q", out)
385+ }
386+ if out := compare("a\n", "b\n").render(); strings.Contains(out, "note:") {
387+ t.Errorf("plain diff got a note: %q", out)
388+ }
389+ // A form feed only REMOVED is shown escaped, without the note: the new
390+ // text is clean.
391+ if out := compare("\fx\n", "fx\n").render(); !strings.Contains(out, `- \fx`) || strings.Contains(out, "note:") {
392+ t.Errorf("removed form feed: %q", out)
393+ }
394+}
@@ -353,3 +353,42 @@ func ExampleIdentical() {
353 fmt.Println(Identical([]Edit{{Old: "a", New: "a"}, {Old: "b", New: "c"}}))353 fmt.Println(Identical([]Edit{{Old: "a", New: "a"}, {Old: "b", New: "c"}}))
354 // Output: 1354 // Output: 1
355 }355 }
356+
357+// TestVisibleEscapesControlCharacters is ticket 294, item 3: a form feed in
358+// written code was invisible in the diff.
359+func TestVisibleEscapesControlCharacters(t *testing.T) {
360+ cases := map[string]string{
361+ "\func main()": `\func main()`,
362+ "a\x00b\x1bc": `a\x00b\x1bc`,
363+ "\tindented": "\tindented",
364+ "crlf line\r": "crlf line\r",
365+ "mid\rline": `mid\rline`,
366+ "del\x7f": `del\x7f`,
367+ "plain, café ✓": "plain, café ✓",
368+ }
369+ for in, want := range cases {
370+ if got := visible(in); got != want {
371+ t.Errorf("visible(%q) = %q, want %q", in, got, want)
372+ }
373+ }
374+}
375+
376+// The diff shows the escape and explains it; a diff without control
377+// characters carries no note.
378+func TestRenderShowsControlCharacters(t *testing.T) {
379+ out := compare("package main\n", "package main\n\func main() {}\n").render()
380+ if !strings.Contains(out, `+ \func main() {}`) || !strings.Contains(out, "note: the new text holds control characters") {
381+ t.Errorf("render = %q", out)
382+ }
383+ if strings.ContainsRune(out, '\f') {
384+ t.Errorf("render kept a raw form feed: %q", out)
385+ }
386+ if out := compare("a\n", "b\n").render(); strings.Contains(out, "note:") {
387+ t.Errorf("plain diff got a note: %q", out)
388+ }
389+ // A form feed only REMOVED is shown escaped, without the note: the new
390+ // text is clean.
391+ if out := compare("\fx\n", "fx\n").render(); !strings.Contains(out, `- \fx`) || strings.Contains(out, "note:") {
392+ t.Errorf("removed form feed: %q", out)
393+ }
394+}
modified internal/fileedit/match_test.go +34 -2
@@ -1,6 +1,7 @@
11 package fileedit
22
33 import (
4+ "strconv"
45 "strings"
56 "testing"
67 )
@@ -249,8 +250,39 @@ func TestLineRules(t *testing.T) {
249250 if err == nil || !strings.Contains(err.Error(), "none starts at line 3") || !strings.Contains(err.Error(), "8, 9") {
250251 t.Errorf("wrong line: err = %v", err)
251252 }
252- // A unique old ignores line, whatever it says.
253- if _, _, err := apply(diceFile, []Edit{{Old: "return dice;", New: "return dice; // ok", Line: 99}}); err != nil {
253+ // A unique old ignores a line inside the file, whatever it says.
254+ if _, _, err := apply(diceFile, []Edit{{Old: "return dice;", New: "return dice; // ok", Line: 2}}); err != nil {
254255 t.Errorf("unique old with a stray line: %v", err)
255256 }
256257 }
258+
259+// TestLineOutsideTheFileIsRefused is ticket 294: line 1000000000000000 with
260+// a unique old was applied. A line past the end, or below 1, is refused —
261+// for an identical old/new pair too — and the message gives the file's size.
262+func TestLineOutsideTheFileIsRefused(t *testing.T) {
263+ total := lineCount(diceFile)
264+ cases := []Edit{
265+ {Old: "return dice;", New: "return dice; // ok", Line: 1000000000000000},
266+ {Old: "return dice;", New: "x", Line: total + 1},
267+ {Old: "return dice;", New: "x", Line: -3},
268+ {Old: "return dice;", New: "return dice;", Line: 500},
269+ }
270+ for _, e := range cases {
271+ _, _, err := apply(diceFile, []Edit{e})
272+ if err == nil || !strings.Contains(err.Error(), "is outside the file, which has "+strconv.Itoa(total)+" line(s)") {
273+ t.Errorf("line %d: err = %v, want the outside-the-file refusal", e.Line, err)
274+ }
275+ }
276+ // The last line is inside.
277+ if _, _, err := apply(diceFile, []Edit{{Old: "return dice;", New: "x", Line: total}}); err != nil {
278+ t.Errorf("last line: %v", err)
279+ }
280+}
281+
282+func TestLineCount(t *testing.T) {
283+ for body, want := range map[string]int{"": 0, "a": 1, "a\n": 1, "a\nb": 2, "a\nb\n": 2, "\n": 1} {
284+ if got := lineCount(body); got != want {
285+ t.Errorf("lineCount(%q) = %d, want %d", body, got, want)
286+ }
287+ }
288+}
@@ -1,6 +1,7 @@
1 package fileedit1 package fileedit
2 2
3 import (3 import (
4+ "strconv"
4 "strings"5 "strings"
5 "testing"6 "testing"
6 )7 )
@@ -249,8 +250,39 @@ func TestLineRules(t *testing.T) {
249 if err == nil || !strings.Contains(err.Error(), "none starts at line 3") || !strings.Contains(err.Error(), "8, 9") {250 if err == nil || !strings.Contains(err.Error(), "none starts at line 3") || !strings.Contains(err.Error(), "8, 9") {
250 t.Errorf("wrong line: err = %v", err)251 t.Errorf("wrong line: err = %v", err)
251 }252 }
252- // A unique old ignores line, whatever it says.253+ // A unique old ignores a line inside the file, whatever it says.
253- if _, _, err := apply(diceFile, []Edit{{Old: "return dice;", New: "return dice; // ok", Line: 99}}); err != nil {254+ if _, _, err := apply(diceFile, []Edit{{Old: "return dice;", New: "return dice; // ok", Line: 2}}); err != nil {
254 t.Errorf("unique old with a stray line: %v", err)255 t.Errorf("unique old with a stray line: %v", err)
255 }256 }
256 }257 }
258+
259+// TestLineOutsideTheFileIsRefused is ticket 294: line 1000000000000000 with
260+// a unique old was applied. A line past the end, or below 1, is refused —
261+// for an identical old/new pair too — and the message gives the file's size.
262+func TestLineOutsideTheFileIsRefused(t *testing.T) {
263+ total := lineCount(diceFile)
264+ cases := []Edit{
265+ {Old: "return dice;", New: "return dice; // ok", Line: 1000000000000000},
266+ {Old: "return dice;", New: "x", Line: total + 1},
267+ {Old: "return dice;", New: "x", Line: -3},
268+ {Old: "return dice;", New: "return dice;", Line: 500},
269+ }
270+ for _, e := range cases {
271+ _, _, err := apply(diceFile, []Edit{e})
272+ if err == nil || !strings.Contains(err.Error(), "is outside the file, which has "+strconv.Itoa(total)+" line(s)") {
273+ t.Errorf("line %d: err = %v, want the outside-the-file refusal", e.Line, err)
274+ }
275+ }
276+ // The last line is inside.
277+ if _, _, err := apply(diceFile, []Edit{{Old: "return dice;", New: "x", Line: total}}); err != nil {
278+ t.Errorf("last line: %v", err)
279+ }
280+}
281+
282+func TestLineCount(t *testing.T) {
283+ for body, want := range map[string]int{"": 0, "a": 1, "a\n": 1, "a\nb": 2, "a\nb\n": 2, "\n": 1} {
284+ if got := lineCount(body); got != want {
285+ t.Errorf("lineCount(%q) = %d, want %d", body, got, want)
286+ }
287+ }
288+}
modified internal/lsp/caps_test.go +4 -0
@@ -22,6 +22,10 @@ func TestInitializeDeclaresPublishDiagnostics(t *testing.T) {
2222 if !strings.Contains(string(b), `"publishDiagnostics":{}`) {
2323 t.Errorf("initialize params = %s, want textDocument.publishDiagnostics", b)
2424 }
25+ // Ticket 294: without it, gopls never says it is loading the workspace.
26+ if !strings.Contains(string(b), `"window":{"workDoneProgress":true}`) {
27+ t.Errorf("initialize params = %s, want window.workDoneProgress", b)
28+ }
2529 }
2630
2731 // With the real typescript-language-server (skipped when it is not on the
@@ -22,6 +22,10 @@ func TestInitializeDeclaresPublishDiagnostics(t *testing.T) {
22 if !strings.Contains(string(b), `"publishDiagnostics":{}`) {22 if !strings.Contains(string(b), `"publishDiagnostics":{}`) {
23 t.Errorf("initialize params = %s, want textDocument.publishDiagnostics", b)23 t.Errorf("initialize params = %s, want textDocument.publishDiagnostics", b)
24 }24 }
25+ // Ticket 294: without it, gopls never says it is loading the workspace.
26+ if !strings.Contains(string(b), `"window":{"workDoneProgress":true}`) {
27+ t.Errorf("initialize params = %s, want window.workDoneProgress", b)
28+ }
25 }29 }
26 30
27 // With the real typescript-language-server (skipped when it is not on the31 // With the real typescript-language-server (skipped when it is not on the
modified internal/lsp/change.go +49 -11
@@ -18,7 +18,9 @@ import (
1818 // warnings, hints — one per line with its position. The file is synced
1919 // first, then the call waits (briefly) for the server's publication; a
2020 // server that publishes nothing new in time is reported as such rather than
21-// blocking the turn.
21+// blocking the turn. An empty publication counts only once it has settled
22+// (settle.go, ticket 294): a server reloading its workspace may publish
23+// "nothing" before its real answer.
2224 func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {
2325 if path == "" {
2426 return "", fmt.Errorf("path is required")
@@ -34,7 +36,7 @@ func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {
3436 }
3537 // The request failed: wait for a publication as below.
3638 }
37- fresh, err := s.published(ctx, path, u, c.diagWait)
39+ fresh, err := s.published(ctx, path, u, c.diagWait, c.settle)
3840 if err != nil {
3941 return "", err
4042 }
@@ -45,12 +47,12 @@ func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {
4547 // triggers; fresh is false when none came in time. The sequence is read
4648 // BEFORE the sync: the publication may arrive before this function gets to
4749 // look.
48-func (s *session) published(ctx context.Context, path string, u uri.URI, wait time.Duration) (bool, error) {
50+func (s *session) published(ctx context.Context, path string, u uri.URI, wait, quiet time.Duration) (bool, error) {
4951 before := s.publications(u)
5052 if _, err := s.sync(ctx, path); err != nil {
5153 return false, err
5254 }
53- return s.waitPublication(ctx, u, before, wait)
55+ return s.waitSettled(ctx, u, before, wait, quiet)
5456 }
5557
5658 // pullsDiagnostics reports whether the server answers textDocument/diagnostic
@@ -97,24 +99,58 @@ func (s *session) publications(u uri.URI) int {
9799 }
98100
99101 // waitPublication waits until the server has published for u since `before`,
100-// or the delay is over, and reports which.
102+// or the delay is over, and reports which. It takes the first publication,
103+// whatever it says: see waitSettled for the answer to a question.
101104 func (s *session) waitPublication(ctx context.Context, u uri.URI, before int, wait time.Duration) (bool, error) {
102- deadline := time.After(wait)
103- for s.publications(u) <= before {
105+ return s.waitUntil(ctx, wait, func(time.Time) (bool, time.Duration) {
106+ return s.publications(u) > before, time.Hour
107+ })
108+}
109+
110+// waitSettled waits until the publications for u since `before` give a
111+// final answer (settled), or the delay is over. fresh is true when the
112+// server published since `before`, even if that publication had not
113+// settled when the delay ran out.
114+func (s *session) waitSettled(ctx context.Context, u uri.URI, before int, wait, quiet time.Duration) (bool, error) {
115+ if _, err := s.waitUntil(ctx, wait, func(now time.Time) (bool, time.Duration) {
116+ return s.settled(u, before, now, quiet)
117+ }); err != nil {
118+ return false, err
119+ }
120+ return s.publications(u) > before, nil
121+}
122+
123+// waitUntil calls ready until it says done, waking on every message from
124+// the server and when ready's recheck delay is over, for at most wait.
125+// It reports whether ready said done in time.
126+func (s *session) waitUntil(ctx context.Context, wait time.Duration, ready func(time.Time) (bool, time.Duration)) (bool, error) {
127+ deadline := time.Now().Add(wait)
128+ for {
129+ now := time.Now()
130+ done, recheck := ready(now)
131+ if done {
132+ return true, nil
133+ }
134+ remaining := deadline.Sub(now)
135+ if remaining <= 0 {
136+ return false, nil
137+ }
138+ timer := time.NewTimer(min(remaining, recheck))
104139 select {
105140 case <-s.wake:
106- case <-deadline:
107- return false, nil
141+ case <-timer.C:
108142 case <-ctx.Done():
143+ timer.Stop()
109144 return false, ctx.Err()
110145 }
146+ timer.Stop()
111147 }
112- return true, nil
113148 }
114149
115150 // renderDiagnostics renders what the server last said about u. An
116151 // unchanged file gets no new publication: what the server last said still
117-// holds, and is labelled as such.
152+// holds, and is labelled as such. An empty list while the server is still
153+// loading is not called clean (ticket 294).
118154 func (c *Client) renderDiagnostics(s *session, u uri.URI, fresh bool) string {
119155 s.diagMu.Lock()
120156 diags := append([]protocol.Diagnostic(nil), s.diags[u]...)
@@ -125,6 +161,8 @@ func (c *Client) renderDiagnostics(s *session, u uri.URI, fresh bool) string {
125161 switch {
126162 case !known:
127163 return fmt.Sprintf("no diagnostics received for %s within %s (the server may still be indexing — ask again)", rel, c.diagWait)
164+ case len(diags) == 0 && s.loading():
165+ return fmt.Sprintf("no diagnostics yet for %s, but the server is still loading the workspace — this does NOT mean the file is clean: ask again in a moment, or build it", rel)
128166 case len(diags) == 0:
129167 return "no diagnostics: " + rel + " is clean"
130168 }
@@ -18,7 +18,9 @@ import (
18 // warnings, hints — one per line with its position. The file is synced18 // warnings, hints — one per line with its position. The file is synced
19 // first, then the call waits (briefly) for the server's publication; a19 // first, then the call waits (briefly) for the server's publication; a
20 // server that publishes nothing new in time is reported as such rather than20 // server that publishes nothing new in time is reported as such rather than
21-// blocking the turn.21+// blocking the turn. An empty publication counts only once it has settled
22+// (settle.go, ticket 294): a server reloading its workspace may publish
23+// "nothing" before its real answer.
22 func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {24 func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {
23 if path == "" {25 if path == "" {
24 return "", fmt.Errorf("path is required")26 return "", fmt.Errorf("path is required")
@@ -34,7 +36,7 @@ func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {
34 }36 }
35 // The request failed: wait for a publication as below.37 // The request failed: wait for a publication as below.
36 }38 }
37- fresh, err := s.published(ctx, path, u, c.diagWait)39+ fresh, err := s.published(ctx, path, u, c.diagWait, c.settle)
38 if err != nil {40 if err != nil {
39 return "", err41 return "", err
40 }42 }
@@ -45,12 +47,12 @@ func (c *Client) Diagnostics(ctx context.Context, path string) (string, error) {
45 // triggers; fresh is false when none came in time. The sequence is read47 // triggers; fresh is false when none came in time. The sequence is read
46 // BEFORE the sync: the publication may arrive before this function gets to48 // BEFORE the sync: the publication may arrive before this function gets to
47 // look.49 // look.
48-func (s *session) published(ctx context.Context, path string, u uri.URI, wait time.Duration) (bool, error) {50+func (s *session) published(ctx context.Context, path string, u uri.URI, wait, quiet time.Duration) (bool, error) {
49 before := s.publications(u)51 before := s.publications(u)
50 if _, err := s.sync(ctx, path); err != nil {52 if _, err := s.sync(ctx, path); err != nil {
51 return false, err53 return false, err
52 }54 }
53- return s.waitPublication(ctx, u, before, wait)55+ return s.waitSettled(ctx, u, before, wait, quiet)
54 }56 }
55 57
56 // pullsDiagnostics reports whether the server answers textDocument/diagnostic58 // pullsDiagnostics reports whether the server answers textDocument/diagnostic
@@ -97,24 +99,58 @@ func (s *session) publications(u uri.URI) int {
97 }99 }
98 100
99 // waitPublication waits until the server has published for u since `before`,101 // waitPublication waits until the server has published for u since `before`,
100-// or the delay is over, and reports which.102+// or the delay is over, and reports which. It takes the first publication,
103+// whatever it says: see waitSettled for the answer to a question.
101 func (s *session) waitPublication(ctx context.Context, u uri.URI, before int, wait time.Duration) (bool, error) {104 func (s *session) waitPublication(ctx context.Context, u uri.URI, before int, wait time.Duration) (bool, error) {
102- deadline := time.After(wait)105+ return s.waitUntil(ctx, wait, func(time.Time) (bool, time.Duration) {
103- for s.publications(u) <= before {106+ return s.publications(u) > before, time.Hour
107+ })
108+}
109+
110+// waitSettled waits until the publications for u since `before` give a
111+// final answer (settled), or the delay is over. fresh is true when the
112+// server published since `before`, even if that publication had not
113+// settled when the delay ran out.
114+func (s *session) waitSettled(ctx context.Context, u uri.URI, before int, wait, quiet time.Duration) (bool, error) {
115+ if _, err := s.waitUntil(ctx, wait, func(now time.Time) (bool, time.Duration) {
116+ return s.settled(u, before, now, quiet)
117+ }); err != nil {
118+ return false, err
119+ }
120+ return s.publications(u) > before, nil
121+}
122+
123+// waitUntil calls ready until it says done, waking on every message from
124+// the server and when ready's recheck delay is over, for at most wait.
125+// It reports whether ready said done in time.
126+func (s *session) waitUntil(ctx context.Context, wait time.Duration, ready func(time.Time) (bool, time.Duration)) (bool, error) {
127+ deadline := time.Now().Add(wait)
128+ for {
129+ now := time.Now()
130+ done, recheck := ready(now)
131+ if done {
132+ return true, nil
133+ }
134+ remaining := deadline.Sub(now)
135+ if remaining <= 0 {
136+ return false, nil
137+ }
138+ timer := time.NewTimer(min(remaining, recheck))
104 select {139 select {
105 case <-s.wake:140 case <-s.wake:
106- case <-deadline:141+ case <-timer.C:
107- return false, nil
108 case <-ctx.Done():142 case <-ctx.Done():
143+ timer.Stop()
109 return false, ctx.Err()144 return false, ctx.Err()
110 }145 }
146+ timer.Stop()
111 }147 }
112- return true, nil
113 }148 }
114 149
115 // renderDiagnostics renders what the server last said about u. An150 // renderDiagnostics renders what the server last said about u. An
116 // unchanged file gets no new publication: what the server last said still151 // unchanged file gets no new publication: what the server last said still
117-// holds, and is labelled as such.152+// holds, and is labelled as such. An empty list while the server is still
153+// loading is not called clean (ticket 294).
118 func (c *Client) renderDiagnostics(s *session, u uri.URI, fresh bool) string {154 func (c *Client) renderDiagnostics(s *session, u uri.URI, fresh bool) string {
119 s.diagMu.Lock()155 s.diagMu.Lock()
120 diags := append([]protocol.Diagnostic(nil), s.diags[u]...)156 diags := append([]protocol.Diagnostic(nil), s.diags[u]...)
@@ -125,6 +161,8 @@ func (c *Client) renderDiagnostics(s *session, u uri.URI, fresh bool) string {
125 switch {161 switch {
126 case !known:162 case !known:
127 return fmt.Sprintf("no diagnostics received for %s within %s (the server may still be indexing — ask again)", rel, c.diagWait)163 return fmt.Sprintf("no diagnostics received for %s within %s (the server may still be indexing — ask again)", rel, c.diagWait)
164+ case len(diags) == 0 && s.loading():
165+ return fmt.Sprintf("no diagnostics yet for %s, but the server is still loading the workspace — this does NOT mean the file is clean: ask again in a moment, or build it", rel)
128 case len(diags) == 0:166 case len(diags) == 0:
129 return "no diagnostics: " + rel + " is clean"167 return "no diagnostics: " + rel + " is clean"
130 }168 }
added internal/lsp/gopls_test.go +104 -0
new file mode 100644
@@ -0,0 +1,104 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "os"
6+ "os/exec"
7+ "path/filepath"
8+ "strings"
9+ "testing"
10+ "time"
11+
12+ "mm/internal/config"
13+)
14+
15+// With the real gopls (skipped when it is not on the PATH), the session of
16+// ticket 294: files written with no go.mod, then the workspace's first
17+// go.mod, then edits that break the imports. Every edit must report its
18+// errors — never "clean".
19+func TestDiagnosticsWithGoplsAfterAGoModAppears(t *testing.T) {
20+ if _, err := exec.LookPath("gopls"); err != nil {
21+ t.Skip("gopls not on the PATH")
22+ }
23+ root, err := filepath.EvalSymlinks(t.TempDir())
24+ if err != nil {
25+ t.Fatal(err)
26+ }
27+ api := filepath.Join(root, "label-api")
28+ write := func(name, text string) string {
29+ t.Helper()
30+ path := filepath.Join(api, name)
31+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
32+ t.Fatal(err)
33+ }
34+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
35+ t.Fatal(err)
36+ }
37+ return path
38+ }
39+ c := New(root, []config.LSPServer{{Name: "gopls", Command: "gopls", Extensions: []string{".go"}}})
40+ c.diagWait = 20 * time.Second // a cold gopls loads the standard library first
41+ t.Cleanup(c.Close)
42+ ctx := context.Background()
43+
44+ models := write("models/models.go", "package models\n\ntype Label struct{ Name string }\n")
45+ handlers := write("handlers/handlers.go", "package handlers\n\nimport \"label-api/models\"\n\nvar All []models.Label\n")
46+ for _, path := range []string{models, handlers} {
47+ if _, err := c.Diagnostics(ctx, path); err != nil {
48+ t.Fatal(err)
49+ }
50+ }
51+ write("go.mod", "module label-api\n\ngo 1.22\n")
52+
53+ write("handlers/handlers.go", "package handlers\n\nimport (\n\t\"encoding/yaml\"\n\t\"../models\"\n)\n\nvar All []models.Label\nvar _ = yaml.Marshal\n")
54+ got, err := c.Diagnostics(ctx, handlers)
55+ if err != nil || !strings.Contains(got, "error label-api/handlers/handlers.go:4:2") || strings.Contains(got, "clean") {
56+ t.Errorf("an edit with wrong imports after go.mod appeared: %q, %v", got, err)
57+ }
58+}
59+
60+// With the real gopls, ticket 308: main.go imports a module go.mod does not
61+// require yet; the model then changes go.mod OUTSIDE mm's file tools (a
62+// bash `go get`, here a plain write), and asks for the diagnostics again.
63+// gopls must see the new go.mod: no "could not import" left.
64+func TestDiagnosticsWithGoplsAfterGoModChangesOutsideTheTools(t *testing.T) {
65+ if _, err := exec.LookPath("gopls"); err != nil {
66+ t.Skip("gopls not on the PATH")
67+ }
68+ root, err := filepath.EvalSymlinks(t.TempDir())
69+ if err != nil {
70+ t.Fatal(err)
71+ }
72+ write := func(name, text string) string {
73+ t.Helper()
74+ path := filepath.Join(root, name)
75+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
76+ t.Fatal(err)
77+ }
78+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
79+ t.Fatal(err)
80+ }
81+ return path
82+ }
83+ write("dep/go.mod", "module example.com/dep\n\ngo 1.22\n")
84+ write("dep/dep.go", "package dep\n\nfunc Hello() string { return \"hi\" }\n")
85+ write("app/go.mod", "module app\n\ngo 1.22\n")
86+ main := write("app/main.go", "package main\n\nimport \"example.com/dep\"\n\nfunc main() { println(dep.Hello()) }\n")
87+
88+ c := New(filepath.Join(root, "app"), []config.LSPServer{{Name: "gopls", Command: "gopls", Extensions: []string{".go"}}})
89+ c.diagWait = 20 * time.Second
90+ t.Cleanup(c.Close)
91+ ctx := context.Background()
92+
93+ got, err := c.Diagnostics(ctx, main)
94+ if err != nil || !strings.Contains(got, "error") {
95+ t.Fatalf("before go.mod requires the module: want an import error, got %q, %v", got, err)
96+ }
97+ // What `go get` does, behind mm's back.
98+ write("app/go.mod", "module app\n\ngo 1.22\n\nrequire example.com/dep v0.0.0\n\nreplace example.com/dep => ../dep\n")
99+
100+ got, err = c.Diagnostics(ctx, main)
101+ if err != nil || strings.Contains(got, "error") {
102+ t.Errorf("after go.mod changed outside the tools: want no error, got %q, %v", got, err)
103+ }
104+}
new file mode 100644
@@ -0,0 +1,104 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "os"
6+ "os/exec"
7+ "path/filepath"
8+ "strings"
9+ "testing"
10+ "time"
11+
12+ "mm/internal/config"
13+)
14+
15+// With the real gopls (skipped when it is not on the PATH), the session of
16+// ticket 294: files written with no go.mod, then the workspace's first
17+// go.mod, then edits that break the imports. Every edit must report its
18+// errors — never "clean".
19+func TestDiagnosticsWithGoplsAfterAGoModAppears(t *testing.T) {
20+ if _, err := exec.LookPath("gopls"); err != nil {
21+ t.Skip("gopls not on the PATH")
22+ }
23+ root, err := filepath.EvalSymlinks(t.TempDir())
24+ if err != nil {
25+ t.Fatal(err)
26+ }
27+ api := filepath.Join(root, "label-api")
28+ write := func(name, text string) string {
29+ t.Helper()
30+ path := filepath.Join(api, name)
31+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
32+ t.Fatal(err)
33+ }
34+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
35+ t.Fatal(err)
36+ }
37+ return path
38+ }
39+ c := New(root, []config.LSPServer{{Name: "gopls", Command: "gopls", Extensions: []string{".go"}}})
40+ c.diagWait = 20 * time.Second // a cold gopls loads the standard library first
41+ t.Cleanup(c.Close)
42+ ctx := context.Background()
43+
44+ models := write("models/models.go", "package models\n\ntype Label struct{ Name string }\n")
45+ handlers := write("handlers/handlers.go", "package handlers\n\nimport \"label-api/models\"\n\nvar All []models.Label\n")
46+ for _, path := range []string{models, handlers} {
47+ if _, err := c.Diagnostics(ctx, path); err != nil {
48+ t.Fatal(err)
49+ }
50+ }
51+ write("go.mod", "module label-api\n\ngo 1.22\n")
52+
53+ write("handlers/handlers.go", "package handlers\n\nimport (\n\t\"encoding/yaml\"\n\t\"../models\"\n)\n\nvar All []models.Label\nvar _ = yaml.Marshal\n")
54+ got, err := c.Diagnostics(ctx, handlers)
55+ if err != nil || !strings.Contains(got, "error label-api/handlers/handlers.go:4:2") || strings.Contains(got, "clean") {
56+ t.Errorf("an edit with wrong imports after go.mod appeared: %q, %v", got, err)
57+ }
58+}
59+
60+// With the real gopls, ticket 308: main.go imports a module go.mod does not
61+// require yet; the model then changes go.mod OUTSIDE mm's file tools (a
62+// bash `go get`, here a plain write), and asks for the diagnostics again.
63+// gopls must see the new go.mod: no "could not import" left.
64+func TestDiagnosticsWithGoplsAfterGoModChangesOutsideTheTools(t *testing.T) {
65+ if _, err := exec.LookPath("gopls"); err != nil {
66+ t.Skip("gopls not on the PATH")
67+ }
68+ root, err := filepath.EvalSymlinks(t.TempDir())
69+ if err != nil {
70+ t.Fatal(err)
71+ }
72+ write := func(name, text string) string {
73+ t.Helper()
74+ path := filepath.Join(root, name)
75+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
76+ t.Fatal(err)
77+ }
78+ if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
79+ t.Fatal(err)
80+ }
81+ return path
82+ }
83+ write("dep/go.mod", "module example.com/dep\n\ngo 1.22\n")
84+ write("dep/dep.go", "package dep\n\nfunc Hello() string { return \"hi\" }\n")
85+ write("app/go.mod", "module app\n\ngo 1.22\n")
86+ main := write("app/main.go", "package main\n\nimport \"example.com/dep\"\n\nfunc main() { println(dep.Hello()) }\n")
87+
88+ c := New(filepath.Join(root, "app"), []config.LSPServer{{Name: "gopls", Command: "gopls", Extensions: []string{".go"}}})
89+ c.diagWait = 20 * time.Second
90+ t.Cleanup(c.Close)
91+ ctx := context.Background()
92+
93+ got, err := c.Diagnostics(ctx, main)
94+ if err != nil || !strings.Contains(got, "error") {
95+ t.Fatalf("before go.mod requires the module: want an import error, got %q, %v", got, err)
96+ }
97+ // What `go get` does, behind mm's back.
98+ write("app/go.mod", "module app\n\ngo 1.22\n\nrequire example.com/dep v0.0.0\n\nreplace example.com/dep => ../dep\n")
99+
100+ got, err = c.Diagnostics(ctx, main)
101+ if err != nil || strings.Contains(got, "error") {
102+ t.Errorf("after go.mod changed outside the tools: want no error, got %q, %v", got, err)
103+ }
104+}
modified internal/lsp/lsp.go +63 -20
@@ -48,6 +48,9 @@ type Client struct {
4848 // diagWait bounds how long Diagnostics waits for the server's push
4949 // after a file was synced; a server that never publishes still answers.
5050 diagWait time.Duration
51+ // settle is how long an empty publication must stand alone before
52+ // Diagnostics believes it (settle.go, ticket 294).
53+ settle time.Duration
5154 // handshake bounds initialize/initialized on start.
5255 handshake time.Duration
5356
@@ -64,6 +67,7 @@ func New(root string, servers []config.LSPServer) *Client {
6467 servers: servers,
6568 launch: launchProcess,
6669 diagWait: 3 * time.Second,
70+ settle: defaultSettle,
6771 handshake: 15 * time.Second,
6872 running: map[string]*session{},
6973 }
@@ -161,10 +165,21 @@ type session struct {
161165 diags map[uri.URI][]protocol.Diagnostic
162166 seq map[uri.URI]int
163167 wake chan struct{}
168+ // lastAt is when each file was last published for, and busy the
169+ // server's work-done operations still running ($/progress tokens): an
170+ // empty publication is believed only once it has settled (settle.go).
171+ lastAt map[uri.URI]time.Time
172+ busy map[string]bool
173+
174+ // watched: the stamp of each workspace file (go.mod, package.json…) as
175+ // the server last knew it, by absolute path (watch.go, ticket 308).
176+ // Guarded by mu.
177+ watched map[string]FileStamp
164178 }
165179
166180 // document is a file the server was told about.
167181 type document struct {
182+ path string // absolute
168183 version int32
169184 text string
170185 }
@@ -176,13 +191,16 @@ func (c *Client) start(ctx context.Context, cfg config.LSPServer) (*session, err
176191 return nil, fmt.Errorf("start %s: %w", cfg.Name, err)
177192 }
178193 s := &session{
179- name: cfg.Name,
180- root: c.root,
181- end: end,
182- docs: map[uri.URI]*document{},
183- diags: map[uri.URI][]protocol.Diagnostic{},
184- seq: map[uri.URI]int{},
185- wake: make(chan struct{}, 1),
194+ name: cfg.Name,
195+ root: c.root,
196+ end: end,
197+ docs: map[uri.URI]*document{},
198+ diags: map[uri.URI][]protocol.Diagnostic{},
199+ seq: map[uri.URI]int{},
200+ wake: make(chan struct{}, 1),
201+ lastAt: map[uri.URI]time.Time{},
202+ busy: map[string]bool{},
203+ watched: map[string]FileStamp{},
186204 }
187205 _, conn, server := protocol.NewClient(context.Background(), &receiver{s: s}, jsonrpc2.NewStream(rwc))
188206 s.conn, s.server = conn, server
@@ -212,6 +230,10 @@ func (c *Client) start(ctx context.Context, cfg config.LSPServer) (*session, err
212230 func (c *Client) initializeParams() *protocol.InitializeParams {
213231 pid := int32(os.Getpid())
214232 root := uri.File(c.root)
233+ // workDoneProgress (ticket 294): a server only reports "Loading
234+ // packages…" to a client that declares it, and that report is what tells
235+ // an empty publication during a reload from a real "clean" (settle.go).
236+ progress := true
215237 p := &protocol.InitializeParams{
216238 ProcessID: &pid,
217239 ClientInfo: protocol.ClientInfo{Name: "mm"},
@@ -223,6 +245,7 @@ func (c *Client) initializeParams() *protocol.InitializeParams {
223245 // `tsc --lsp` publishes none and answers textDocument/diagnostic.
224246 Diagnostic: &protocol.DiagnosticClientCapabilities{},
225247 },
248+ Window: &protocol.WindowClientCapabilities{WorkDoneProgress: &progress},
226249 },
227250 }
228251 p.WorkspaceFolders = protocol.NewNullable([]protocol.WorkspaceFolder{{URI: root, Name: filepath.Base(c.root)}})
@@ -257,24 +280,39 @@ func (s *session) stop() {
257280 // sync tells the server the file's current content: didOpen the first time,
258281 // didChange (whole document) after — unless the text has not moved since
259282 // the last sync. The model edits files with edit_file, not through the
260-// server, so what is on disk is the truth and is re-read every time.
283+// server, so what is on disk is the truth and is re-read every time. The
284+// workspace files that changed since the last sync (a bash `go get`) are
285+// announced first (notifyWatched, ticket 308).
261286 func (s *session) sync(ctx context.Context, path string) (uri.URI, error) {
262- abs, err := filepath.Abs(path)
287+ abs, text, err := readOnDisk(path)
263288 if err != nil {
264289 return "", err
265290 }
266- data, err := os.ReadFile(abs)
267- if err != nil {
291+ s.mu.Lock()
292+ defer s.mu.Unlock()
293+ if err := s.notifyWatched(ctx, abs); err != nil {
268294 return "", err
269295 }
270- text := string(data)
296+ return s.syncText(ctx, abs, text)
297+}
298+
299+// readOnDisk returns a file's absolute path and its content.
300+func readOnDisk(path string) (abs, text string, err error) {
301+ if abs, err = filepath.Abs(path); err != nil {
302+ return "", "", err
303+ }
304+ data, err := os.ReadFile(abs)
305+ return abs, string(data), err
306+}
307+
308+// syncText sends the document's text: didOpen, didChange or nothing. The
309+// caller holds s.mu.
310+func (s *session) syncText(ctx context.Context, abs, text string) (uri.URI, error) {
271311 u := uri.File(abs)
272- s.mu.Lock()
273- defer s.mu.Unlock()
274312 doc, opened := s.docs[u]
275313 switch {
276314 case !opened:
277- s.docs[u] = &document{version: 1, text: text}
315+ s.docs[u] = &document{path: abs, version: 1, text: text}
278316 return u, s.server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{TextDocument: protocol.TextDocumentItem{
279317 URI: u, LanguageID: languageID(abs), Version: 1, Text: text,
280318 }})
@@ -319,11 +357,16 @@ func (r *receiver) PublishDiagnostics(_ context.Context, p *protocol.PublishDiag
319357 r.s.diagMu.Lock()
320358 r.s.diags[p.URI] = p.Diagnostics
321359 r.s.seq[p.URI]++
360+ r.s.lastAt[p.URI] = time.Now()
322361 r.s.diagMu.Unlock()
323- select {
324- case r.s.wake <- struct{}{}:
325- default:
326- }
362+ r.s.signal()
363+ return nil
364+}
365+
366+// Progress follows the server's work-done operations: while one runs, an
367+// empty publication is not taken as "clean" (settle.go, ticket 294).
368+func (r *receiver) Progress(_ context.Context, p *protocol.ProgressParams) error {
369+ r.s.track(p)
327370 return nil
328371 }
329372
@@ -359,7 +402,7 @@ func (r *receiver) ShowMessageRequest(context.Context, *protocol.ShowMessageRequ
359402 }
360403
361404 // WorkDoneProgressCreate accepts the token; the progress that follows is
362-// dropped by UnimplementedClient.
405+// read by Progress.
363406 func (r *receiver) WorkDoneProgressCreate(context.Context, *protocol.WorkDoneProgressCreateParams) error {
364407 return nil
365408 }
@@ -48,6 +48,9 @@ type Client struct {
48 // diagWait bounds how long Diagnostics waits for the server's push48 // diagWait bounds how long Diagnostics waits for the server's push
49 // after a file was synced; a server that never publishes still answers.49 // after a file was synced; a server that never publishes still answers.
50 diagWait time.Duration50 diagWait time.Duration
51+ // settle is how long an empty publication must stand alone before
52+ // Diagnostics believes it (settle.go, ticket 294).
53+ settle time.Duration
51 // handshake bounds initialize/initialized on start.54 // handshake bounds initialize/initialized on start.
52 handshake time.Duration55 handshake time.Duration
53 56
@@ -64,6 +67,7 @@ func New(root string, servers []config.LSPServer) *Client {
64 servers: servers,67 servers: servers,
65 launch: launchProcess,68 launch: launchProcess,
66 diagWait: 3 * time.Second,69 diagWait: 3 * time.Second,
70+ settle: defaultSettle,
67 handshake: 15 * time.Second,71 handshake: 15 * time.Second,
68 running: map[string]*session{},72 running: map[string]*session{},
69 }73 }
@@ -161,10 +165,21 @@ type session struct {
161 diags map[uri.URI][]protocol.Diagnostic165 diags map[uri.URI][]protocol.Diagnostic
162 seq map[uri.URI]int166 seq map[uri.URI]int
163 wake chan struct{}167 wake chan struct{}
168+ // lastAt is when each file was last published for, and busy the
169+ // server's work-done operations still running ($/progress tokens): an
170+ // empty publication is believed only once it has settled (settle.go).
171+ lastAt map[uri.URI]time.Time
172+ busy map[string]bool
173+
174+ // watched: the stamp of each workspace file (go.mod, package.json…) as
175+ // the server last knew it, by absolute path (watch.go, ticket 308).
176+ // Guarded by mu.
177+ watched map[string]FileStamp
164 }178 }
165 179
166 // document is a file the server was told about.180 // document is a file the server was told about.
167 type document struct {181 type document struct {
182+ path string // absolute
168 version int32183 version int32
169 text string184 text string
170 }185 }
@@ -176,13 +191,16 @@ func (c *Client) start(ctx context.Context, cfg config.LSPServer) (*session, err
176 return nil, fmt.Errorf("start %s: %w", cfg.Name, err)191 return nil, fmt.Errorf("start %s: %w", cfg.Name, err)
177 }192 }
178 s := &session{193 s := &session{
179- name: cfg.Name,194+ name: cfg.Name,
180- root: c.root,195+ root: c.root,
181- end: end,196+ end: end,
182- docs: map[uri.URI]*document{},197+ docs: map[uri.URI]*document{},
183- diags: map[uri.URI][]protocol.Diagnostic{},198+ diags: map[uri.URI][]protocol.Diagnostic{},
184- seq: map[uri.URI]int{},199+ seq: map[uri.URI]int{},
185- wake: make(chan struct{}, 1),200+ wake: make(chan struct{}, 1),
201+ lastAt: map[uri.URI]time.Time{},
202+ busy: map[string]bool{},
203+ watched: map[string]FileStamp{},
186 }204 }
187 _, conn, server := protocol.NewClient(context.Background(), &receiver{s: s}, jsonrpc2.NewStream(rwc))205 _, conn, server := protocol.NewClient(context.Background(), &receiver{s: s}, jsonrpc2.NewStream(rwc))
188 s.conn, s.server = conn, server206 s.conn, s.server = conn, server
@@ -212,6 +230,10 @@ func (c *Client) start(ctx context.Context, cfg config.LSPServer) (*session, err
212 func (c *Client) initializeParams() *protocol.InitializeParams {230 func (c *Client) initializeParams() *protocol.InitializeParams {
213 pid := int32(os.Getpid())231 pid := int32(os.Getpid())
214 root := uri.File(c.root)232 root := uri.File(c.root)
233+ // workDoneProgress (ticket 294): a server only reports "Loading
234+ // packages…" to a client that declares it, and that report is what tells
235+ // an empty publication during a reload from a real "clean" (settle.go).
236+ progress := true
215 p := &protocol.InitializeParams{237 p := &protocol.InitializeParams{
216 ProcessID: &pid,238 ProcessID: &pid,
217 ClientInfo: protocol.ClientInfo{Name: "mm"},239 ClientInfo: protocol.ClientInfo{Name: "mm"},
@@ -223,6 +245,7 @@ func (c *Client) initializeParams() *protocol.InitializeParams {
223 // `tsc --lsp` publishes none and answers textDocument/diagnostic.245 // `tsc --lsp` publishes none and answers textDocument/diagnostic.
224 Diagnostic: &protocol.DiagnosticClientCapabilities{},246 Diagnostic: &protocol.DiagnosticClientCapabilities{},
225 },247 },
248+ Window: &protocol.WindowClientCapabilities{WorkDoneProgress: &progress},
226 },249 },
227 }250 }
228 p.WorkspaceFolders = protocol.NewNullable([]protocol.WorkspaceFolder{{URI: root, Name: filepath.Base(c.root)}})251 p.WorkspaceFolders = protocol.NewNullable([]protocol.WorkspaceFolder{{URI: root, Name: filepath.Base(c.root)}})
@@ -257,24 +280,39 @@ func (s *session) stop() {
257 // sync tells the server the file's current content: didOpen the first time,280 // sync tells the server the file's current content: didOpen the first time,
258 // didChange (whole document) after — unless the text has not moved since281 // didChange (whole document) after — unless the text has not moved since
259 // the last sync. The model edits files with edit_file, not through the282 // the last sync. The model edits files with edit_file, not through the
260-// server, so what is on disk is the truth and is re-read every time.283+// server, so what is on disk is the truth and is re-read every time. The
284+// workspace files that changed since the last sync (a bash `go get`) are
285+// announced first (notifyWatched, ticket 308).
261 func (s *session) sync(ctx context.Context, path string) (uri.URI, error) {286 func (s *session) sync(ctx context.Context, path string) (uri.URI, error) {
262- abs, err := filepath.Abs(path)287+ abs, text, err := readOnDisk(path)
263 if err != nil {288 if err != nil {
264 return "", err289 return "", err
265 }290 }
266- data, err := os.ReadFile(abs)291+ s.mu.Lock()
267- if err != nil {292+ defer s.mu.Unlock()
293+ if err := s.notifyWatched(ctx, abs); err != nil {
268 return "", err294 return "", err
269 }295 }
270- text := string(data)296+ return s.syncText(ctx, abs, text)
297+}
298+
299+// readOnDisk returns a file's absolute path and its content.
300+func readOnDisk(path string) (abs, text string, err error) {
301+ if abs, err = filepath.Abs(path); err != nil {
302+ return "", "", err
303+ }
304+ data, err := os.ReadFile(abs)
305+ return abs, string(data), err
306+}
307+
308+// syncText sends the document's text: didOpen, didChange or nothing. The
309+// caller holds s.mu.
310+func (s *session) syncText(ctx context.Context, abs, text string) (uri.URI, error) {
271 u := uri.File(abs)311 u := uri.File(abs)
272- s.mu.Lock()
273- defer s.mu.Unlock()
274 doc, opened := s.docs[u]312 doc, opened := s.docs[u]
275 switch {313 switch {
276 case !opened:314 case !opened:
277- s.docs[u] = &document{version: 1, text: text}315+ s.docs[u] = &document{path: abs, version: 1, text: text}
278 return u, s.server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{TextDocument: protocol.TextDocumentItem{316 return u, s.server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{TextDocument: protocol.TextDocumentItem{
279 URI: u, LanguageID: languageID(abs), Version: 1, Text: text,317 URI: u, LanguageID: languageID(abs), Version: 1, Text: text,
280 }})318 }})
@@ -319,11 +357,16 @@ func (r *receiver) PublishDiagnostics(_ context.Context, p *protocol.PublishDiag
319 r.s.diagMu.Lock()357 r.s.diagMu.Lock()
320 r.s.diags[p.URI] = p.Diagnostics358 r.s.diags[p.URI] = p.Diagnostics
321 r.s.seq[p.URI]++359 r.s.seq[p.URI]++
360+ r.s.lastAt[p.URI] = time.Now()
322 r.s.diagMu.Unlock()361 r.s.diagMu.Unlock()
323- select {362+ r.s.signal()
324- case r.s.wake <- struct{}{}:363+ return nil
325- default:364+}
326- }365+
366+// Progress follows the server's work-done operations: while one runs, an
367+// empty publication is not taken as "clean" (settle.go, ticket 294).
368+func (r *receiver) Progress(_ context.Context, p *protocol.ProgressParams) error {
369+ r.s.track(p)
327 return nil370 return nil
328 }371 }
329 372
@@ -359,7 +402,7 @@ func (r *receiver) ShowMessageRequest(context.Context, *protocol.ShowMessageRequ
359 }402 }
360 403
361 // WorkDoneProgressCreate accepts the token; the progress that follows is404 // WorkDoneProgressCreate accepts the token; the progress that follows is
362-// dropped by UnimplementedClient.405+// read by Progress.
363 func (r *receiver) WorkDoneProgressCreate(context.Context, *protocol.WorkDoneProgressCreateParams) error {406 func (r *receiver) WorkDoneProgressCreate(context.Context, *protocol.WorkDoneProgressCreateParams) error {
364 return nil407 return nil
365 }408 }
modified internal/lsp/lsp_test.go +24 -3
@@ -32,6 +32,17 @@ type fakeServer struct {
3232 publish bool // publish a diagnostic on didOpen
3333 pull bool // declare diagnosticProvider and answer textDocument/diagnostic
3434 pulled int // textDocument/diagnostic requests received
35+ // onSync, when set, replaces the didOpen publication and also runs on
36+ // didChange: a test scripts what the server says after a sync.
37+ onSync func(client protocol.Client, u uri.URI)
38+ watched []protocol.FileEvent // workspace/didChangeWatchedFiles received
39+}
40+
41+func (f *fakeServer) DidChangeWatchedFiles(_ context.Context, p *protocol.DidChangeWatchedFilesParams) error {
42+ f.mu.Lock()
43+ f.watched = append(f.watched, p.Changes...)
44+ f.mu.Unlock()
45+ return nil
3546 }
3647
3748 func newFake() *fakeServer {
@@ -74,8 +85,13 @@ func (f *fakeServer) DidOpen(ctx context.Context, p *protocol.DidOpenTextDocumen
7485 f.mu.Lock()
7586 f.opened[p.TextDocument.URI] = p.TextDocument.Version
7687 f.texts[p.TextDocument.URI] = p.TextDocument.Text
77- publish := f.publish
88+ publish, onSync := f.publish, f.onSync
7889 f.mu.Unlock()
90+ if onSync != nil {
91+ client, _ := protocol.ClientFromContext(ctx)
92+ go onSync(client, p.TextDocument.URI)
93+ return nil
94+ }
7995 if !publish {
8096 return nil
8197 }
@@ -94,13 +110,18 @@ func (f *fakeServer) DidOpen(ctx context.Context, p *protocol.DidOpenTextDocumen
94110 return nil
95111 }
96112
97-func (f *fakeServer) DidChange(_ context.Context, p *protocol.DidChangeTextDocumentParams) error {
113+func (f *fakeServer) DidChange(ctx context.Context, p *protocol.DidChangeTextDocumentParams) error {
98114 f.mu.Lock()
99- defer f.mu.Unlock()
100115 f.opened[p.TextDocument.URI] = p.TextDocument.Version
101116 if whole, ok := p.ContentChanges[0].(*protocol.TextDocumentContentChangeWholeDocument); ok {
102117 f.texts[p.TextDocument.URI] = whole.Text
103118 }
119+ onSync := f.onSync
120+ f.mu.Unlock()
121+ if onSync != nil {
122+ client, _ := protocol.ClientFromContext(ctx)
123+ go onSync(client, p.TextDocument.URI)
124+ }
104125 return nil
105126 }
106127
@@ -32,6 +32,17 @@ type fakeServer struct {
32 publish bool // publish a diagnostic on didOpen32 publish bool // publish a diagnostic on didOpen
33 pull bool // declare diagnosticProvider and answer textDocument/diagnostic33 pull bool // declare diagnosticProvider and answer textDocument/diagnostic
34 pulled int // textDocument/diagnostic requests received34 pulled int // textDocument/diagnostic requests received
35+ // onSync, when set, replaces the didOpen publication and also runs on
36+ // didChange: a test scripts what the server says after a sync.
37+ onSync func(client protocol.Client, u uri.URI)
38+ watched []protocol.FileEvent // workspace/didChangeWatchedFiles received
39+}
40+
41+func (f *fakeServer) DidChangeWatchedFiles(_ context.Context, p *protocol.DidChangeWatchedFilesParams) error {
42+ f.mu.Lock()
43+ f.watched = append(f.watched, p.Changes...)
44+ f.mu.Unlock()
45+ return nil
35 }46 }
36 47
37 func newFake() *fakeServer {48 func newFake() *fakeServer {
@@ -74,8 +85,13 @@ func (f *fakeServer) DidOpen(ctx context.Context, p *protocol.DidOpenTextDocumen
74 f.mu.Lock()85 f.mu.Lock()
75 f.opened[p.TextDocument.URI] = p.TextDocument.Version86 f.opened[p.TextDocument.URI] = p.TextDocument.Version
76 f.texts[p.TextDocument.URI] = p.TextDocument.Text87 f.texts[p.TextDocument.URI] = p.TextDocument.Text
77- publish := f.publish88+ publish, onSync := f.publish, f.onSync
78 f.mu.Unlock()89 f.mu.Unlock()
90+ if onSync != nil {
91+ client, _ := protocol.ClientFromContext(ctx)
92+ go onSync(client, p.TextDocument.URI)
93+ return nil
94+ }
79 if !publish {95 if !publish {
80 return nil96 return nil
81 }97 }
@@ -94,13 +110,18 @@ func (f *fakeServer) DidOpen(ctx context.Context, p *protocol.DidOpenTextDocumen
94 return nil110 return nil
95 }111 }
96 112
97-func (f *fakeServer) DidChange(_ context.Context, p *protocol.DidChangeTextDocumentParams) error {113+func (f *fakeServer) DidChange(ctx context.Context, p *protocol.DidChangeTextDocumentParams) error {
98 f.mu.Lock()114 f.mu.Lock()
99- defer f.mu.Unlock()
100 f.opened[p.TextDocument.URI] = p.TextDocument.Version115 f.opened[p.TextDocument.URI] = p.TextDocument.Version
101 if whole, ok := p.ContentChanges[0].(*protocol.TextDocumentContentChangeWholeDocument); ok {116 if whole, ok := p.ContentChanges[0].(*protocol.TextDocumentContentChangeWholeDocument); ok {
102 f.texts[p.TextDocument.URI] = whole.Text117 f.texts[p.TextDocument.URI] = whole.Text
103 }118 }
119+ onSync := f.onSync
120+ f.mu.Unlock()
121+ if onSync != nil {
122+ client, _ := protocol.ClientFromContext(ctx)
123+ go onSync(client, p.TextDocument.URI)
124+ }
104 return nil125 return nil
105 }126 }
106 127
added internal/lsp/settle.go +110 -0
new file mode 100644
@@ -0,0 +1,110 @@
1+package lsp
2+
3+// When is a publication the answer? (ticket 294)
4+//
5+// Seen 2026-12-02 with Mellum2 and gopls: the model created the workspace's
6+// first go.mod, then edited three files with wrong imports ("../models",
7+// "encoding/yaml"); each edit was answered "no diagnostics: <file> is
8+// clean". `go build` and `gopls check` reported every error. The inferred
9+// cause: gopls, reloading the workspace for the new go.mod, first published
10+// an EMPTY list for the file, and mm took the first publication after the
11+// sync as final. A false "clean" is worse than no diagnostics: the model
12+// believes broken code builds.
13+//
14+// Two rules, applied to the PUBLISHED diagnostics only (a pull answer,
15+// ticket 247, is the server's reply to the question and is final):
16+//
17+// 1. A publication with diagnostics is taken at once: errors are never a
18+// false "clean", and a later publication rarely removes them.
19+// 2. An EMPTY publication is taken only once it has settled: no other
20+// publication for the file during Client.settle (defaultSettle), and no work-done
21+// operation of the server running ($/progress, "Loading packages…").
22+// If the wait ends first, the answer says the server was still busy
23+// rather than "clean".
24+//
25+// The cost is that delay on a clean file, nothing on a broken one.
26+
27+import (
28+ "encoding/json"
29+ "fmt"
30+ "time"
31+
32+ "go.lsp.dev/protocol"
33+ "go.lsp.dev/uri"
34+)
35+
36+// defaultSettle is how long an empty publication must stand alone before
37+// it is believed. gopls publishes a reload's real answer within a few
38+// hundred milliseconds of the empty one; a clean file costs this much more.
39+const defaultSettle = 400 * time.Millisecond
40+
41+// settled reports whether the publications for u since `before` give a
42+// final answer at `now`; when they do not, recheck is how long to wait
43+// before asking again (a wake-up from the server may come earlier).
44+// Called with nothing locked.
45+func (s *session) settled(u uri.URI, before int, now time.Time, quiet time.Duration) (done bool, recheck time.Duration) {
46+ s.diagMu.Lock()
47+ defer s.diagMu.Unlock()
48+ switch {
49+ case s.seq[u] <= before:
50+ return false, time.Hour // nothing new yet: only a wake-up helps
51+ case len(s.diags[u]) > 0:
52+ return true, 0
53+ case len(s.busy) > 0:
54+ return false, time.Hour // the end of the operation wakes the waiter
55+ }
56+ if waited := now.Sub(s.lastAt[u]); waited < quiet {
57+ return false, quiet - waited
58+ }
59+ return true, 0
60+}
61+
62+// loading reports whether the server has a work-done operation running —
63+// its own word that what it published may not be its last.
64+func (s *session) loading() bool {
65+ s.diagMu.Lock()
66+ defer s.diagMu.Unlock()
67+ return len(s.busy) > 0
68+}
69+
70+// signal wakes a waiting Diagnostics call, without ever blocking the
71+// server's notification handler.
72+func (s *session) signal() {
73+ select {
74+ case s.wake <- struct{}{}:
75+ default:
76+ }
77+}
78+
79+// track records a $/progress notification: a "begin" marks the token busy,
80+// an "end" frees it. Reports are ignored: only "is anything running" matters.
81+func (s *session) track(p *protocol.ProgressParams) {
82+ kind := progressKind(p.Value)
83+ if kind != "begin" && kind != "end" {
84+ return
85+ }
86+ token := fmt.Sprint(p.Token)
87+ s.diagMu.Lock()
88+ if kind == "begin" {
89+ s.busy[token] = true
90+ } else {
91+ delete(s.busy, token)
92+ }
93+ s.diagMu.Unlock()
94+ s.signal()
95+}
96+
97+// progressKind reads the "kind" of a work-done progress value: "begin",
98+// "report" or "end"; "" for anything else (a partial-result token carries
99+// no kind).
100+//
101+// progressKind(protocol.LSPAny(`{"kind":"begin","title":"Loading packages..."}`)) // "begin"
102+func progressKind(value protocol.LSPAny) string {
103+ var v struct {
104+ Kind string `json:"kind"`
105+ }
106+ if json.Unmarshal(value, &v) != nil {
107+ return ""
108+ }
109+ return v.Kind
110+}
new file mode 100644
@@ -0,0 +1,110 @@
1+package lsp
2+
3+// When is a publication the answer? (ticket 294)
4+//
5+// Seen 2026-12-02 with Mellum2 and gopls: the model created the workspace's
6+// first go.mod, then edited three files with wrong imports ("../models",
7+// "encoding/yaml"); each edit was answered "no diagnostics: <file> is
8+// clean". `go build` and `gopls check` reported every error. The inferred
9+// cause: gopls, reloading the workspace for the new go.mod, first published
10+// an EMPTY list for the file, and mm took the first publication after the
11+// sync as final. A false "clean" is worse than no diagnostics: the model
12+// believes broken code builds.
13+//
14+// Two rules, applied to the PUBLISHED diagnostics only (a pull answer,
15+// ticket 247, is the server's reply to the question and is final):
16+//
17+// 1. A publication with diagnostics is taken at once: errors are never a
18+// false "clean", and a later publication rarely removes them.
19+// 2. An EMPTY publication is taken only once it has settled: no other
20+// publication for the file during Client.settle (defaultSettle), and no work-done
21+// operation of the server running ($/progress, "Loading packages…").
22+// If the wait ends first, the answer says the server was still busy
23+// rather than "clean".
24+//
25+// The cost is that delay on a clean file, nothing on a broken one.
26+
27+import (
28+ "encoding/json"
29+ "fmt"
30+ "time"
31+
32+ "go.lsp.dev/protocol"
33+ "go.lsp.dev/uri"
34+)
35+
36+// defaultSettle is how long an empty publication must stand alone before
37+// it is believed. gopls publishes a reload's real answer within a few
38+// hundred milliseconds of the empty one; a clean file costs this much more.
39+const defaultSettle = 400 * time.Millisecond
40+
41+// settled reports whether the publications for u since `before` give a
42+// final answer at `now`; when they do not, recheck is how long to wait
43+// before asking again (a wake-up from the server may come earlier).
44+// Called with nothing locked.
45+func (s *session) settled(u uri.URI, before int, now time.Time, quiet time.Duration) (done bool, recheck time.Duration) {
46+ s.diagMu.Lock()
47+ defer s.diagMu.Unlock()
48+ switch {
49+ case s.seq[u] <= before:
50+ return false, time.Hour // nothing new yet: only a wake-up helps
51+ case len(s.diags[u]) > 0:
52+ return true, 0
53+ case len(s.busy) > 0:
54+ return false, time.Hour // the end of the operation wakes the waiter
55+ }
56+ if waited := now.Sub(s.lastAt[u]); waited < quiet {
57+ return false, quiet - waited
58+ }
59+ return true, 0
60+}
61+
62+// loading reports whether the server has a work-done operation running —
63+// its own word that what it published may not be its last.
64+func (s *session) loading() bool {
65+ s.diagMu.Lock()
66+ defer s.diagMu.Unlock()
67+ return len(s.busy) > 0
68+}
69+
70+// signal wakes a waiting Diagnostics call, without ever blocking the
71+// server's notification handler.
72+func (s *session) signal() {
73+ select {
74+ case s.wake <- struct{}{}:
75+ default:
76+ }
77+}
78+
79+// track records a $/progress notification: a "begin" marks the token busy,
80+// an "end" frees it. Reports are ignored: only "is anything running" matters.
81+func (s *session) track(p *protocol.ProgressParams) {
82+ kind := progressKind(p.Value)
83+ if kind != "begin" && kind != "end" {
84+ return
85+ }
86+ token := fmt.Sprint(p.Token)
87+ s.diagMu.Lock()
88+ if kind == "begin" {
89+ s.busy[token] = true
90+ } else {
91+ delete(s.busy, token)
92+ }
93+ s.diagMu.Unlock()
94+ s.signal()
95+}
96+
97+// progressKind reads the "kind" of a work-done progress value: "begin",
98+// "report" or "end"; "" for anything else (a partial-result token carries
99+// no kind).
100+//
101+// progressKind(protocol.LSPAny(`{"kind":"begin","title":"Loading packages..."}`)) // "begin"
102+func progressKind(value protocol.LSPAny) string {
103+ var v struct {
104+ Kind string `json:"kind"`
105+ }
106+ if json.Unmarshal(value, &v) != nil {
107+ return ""
108+ }
109+ return v.Kind
110+}
added internal/lsp/settle_test.go +143 -0
new file mode 100644
@@ -0,0 +1,143 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+ "time"
8+
9+ "go.lsp.dev/protocol"
10+ "go.lsp.dev/uri"
11+)
12+
13+// importError is the diagnostic a reloaded workspace publishes for a wrong
14+// import, as gopls did for "../models" (ticket 294).
15+func importError() []protocol.Diagnostic {
16+ return []protocol.Diagnostic{{
17+ Range: span(4, 1, 4, 12),
18+ Severity: protocol.DiagnosticSeverityError,
19+ Source: protocol.NewOptional("compiler"),
20+ Message: protocol.String(`could not import ../models`),
21+ }}
22+}
23+
24+// publish sends one publication for u, empty when diags is nil.
25+func publish(client protocol.Client, u uri.URI, diags []protocol.Diagnostic) {
26+ if diags == nil {
27+ diags = []protocol.Diagnostic{}
28+ }
29+ _ = client.PublishDiagnostics(context.Background(), &protocol.PublishDiagnosticsParams{URI: u, Diagnostics: diags})
30+}
31+
32+// progress sends a $/progress notification of the given kind for token.
33+func progress(client protocol.Client, token, kind string) {
34+ _ = client.Progress(context.Background(), &protocol.ProgressParams{
35+ Token: protocol.String(token),
36+ Value: protocol.LSPAny(`{"kind":"` + kind + `","title":"Loading packages..."}`),
37+ })
38+}
39+
40+// The bug of ticket 294: the server first publishes an empty list (it is
41+// reloading the workspace), then the real errors. The first publication
42+// must not be taken as "clean".
43+func TestDiagnosticsWaitsPastAnEmptyPublicationFollowedByErrors(t *testing.T) {
44+ fake := newFake()
45+ fake.onSync = func(client protocol.Client, u uri.URI) {
46+ publish(client, u, nil)
47+ time.Sleep(100 * time.Millisecond)
48+ publish(client, u, importError())
49+ }
50+ c, _ := newClient(t, fake)
51+ c.diagWait, c.settle = 2*time.Second, 300*time.Millisecond
52+
53+ got, err := c.Diagnostics(context.Background(), "main.go")
54+ if err != nil || !strings.HasPrefix(got, "1 diagnostic(s) in main.go:\nerror main.go:5:2 could not import ../models") {
55+ t.Errorf("an empty publication followed by errors: %q, %v", got, err)
56+ }
57+}
58+
59+// While the server reports a work-done operation, an empty publication is
60+// not final, however long it stands: the end of the operation and the
61+// publication after it are what count.
62+func TestDiagnosticsWaitsForTheServersLoadToEnd(t *testing.T) {
63+ fake := newFake()
64+ fake.onSync = func(client protocol.Client, u uri.URI) {
65+ progress(client, "load-1", "begin")
66+ publish(client, u, nil)
67+ time.Sleep(250 * time.Millisecond) // longer than the settle delay
68+ publish(client, u, importError())
69+ progress(client, "load-1", "end")
70+ }
71+ c, _ := newClient(t, fake)
72+ c.diagWait, c.settle = 2*time.Second, 50*time.Millisecond
73+
74+ got, err := c.Diagnostics(context.Background(), "main.go")
75+ if err != nil || !strings.Contains(got, "could not import ../models") {
76+ t.Errorf("an empty publication during a load: %q, %v", got, err)
77+ }
78+}
79+
80+// A load still running when the wait is over is said plainly: never
81+// "clean".
82+func TestDiagnosticsDuringALoadThatOutlastsTheWaitIsNotClean(t *testing.T) {
83+ fake := newFake()
84+ fake.onSync = func(client protocol.Client, u uri.URI) {
85+ progress(client, "load-2", "begin")
86+ publish(client, u, nil)
87+ }
88+ c, _ := newClient(t, fake)
89+ c.diagWait, c.settle = 300*time.Millisecond, 50*time.Millisecond
90+
91+ got, err := c.Diagnostics(context.Background(), "main.go")
92+ if err != nil || !strings.Contains(got, "still loading the workspace — this does NOT mean the file is clean") {
93+ t.Errorf("a load that outlasts the wait: %q, %v", got, err)
94+ }
95+}
96+
97+// A clean file is still clean, once the empty publication has settled.
98+func TestDiagnosticsOnACleanFileAfterTheSettleDelay(t *testing.T) {
99+ fake := newFake()
100+ fake.onSync = func(client protocol.Client, u uri.URI) { publish(client, u, nil) }
101+ c, _ := newClient(t, fake)
102+ c.diagWait, c.settle = 2*time.Second, 100*time.Millisecond
103+
104+ start := time.Now()
105+ got, err := c.Diagnostics(context.Background(), "main.go")
106+ if err != nil || got != "no diagnostics: main.go is clean" {
107+ t.Errorf("clean file: %q, %v", got, err)
108+ }
109+ if waited := time.Since(start); waited < 100*time.Millisecond {
110+ t.Errorf("an empty publication was believed after %s, before the settle delay", waited)
111+ }
112+}
113+
114+// Errors are taken at once: no settle delay on a broken file.
115+func TestDiagnosticsWithErrorsAnswersWithoutTheSettleDelay(t *testing.T) {
116+ fake := newFake()
117+ fake.onSync = func(client protocol.Client, u uri.URI) { publish(client, u, importError()) }
118+ c, _ := newClient(t, fake)
119+ c.diagWait, c.settle = 2*time.Second, time.Second
120+
121+ start := time.Now()
122+ got, err := c.Diagnostics(context.Background(), "main.go")
123+ if err != nil || !strings.Contains(got, "could not import") {
124+ t.Errorf("broken file: %q, %v", got, err)
125+ }
126+ if waited := time.Since(start); waited > 500*time.Millisecond {
127+ t.Errorf("errors waited %s: they must be taken at once", waited)
128+ }
129+}
130+
131+func TestProgressKind(t *testing.T) {
132+ for value, want := range map[string]string{
133+ `{"kind":"begin","title":"Loading packages..."}`: "begin",
134+ `{"kind":"report","percentage":50}`: "report",
135+ `{"kind":"end"}`: "end",
136+ `[1,2]`: "",
137+ ``: "",
138+ } {
139+ if got := progressKind(protocol.LSPAny(value)); got != want {
140+ t.Errorf("progressKind(%s) = %q, want %q", value, got, want)
141+ }
142+ }
143+}
new file mode 100644
@@ -0,0 +1,143 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "strings"
6+ "testing"
7+ "time"
8+
9+ "go.lsp.dev/protocol"
10+ "go.lsp.dev/uri"
11+)
12+
13+// importError is the diagnostic a reloaded workspace publishes for a wrong
14+// import, as gopls did for "../models" (ticket 294).
15+func importError() []protocol.Diagnostic {
16+ return []protocol.Diagnostic{{
17+ Range: span(4, 1, 4, 12),
18+ Severity: protocol.DiagnosticSeverityError,
19+ Source: protocol.NewOptional("compiler"),
20+ Message: protocol.String(`could not import ../models`),
21+ }}
22+}
23+
24+// publish sends one publication for u, empty when diags is nil.
25+func publish(client protocol.Client, u uri.URI, diags []protocol.Diagnostic) {
26+ if diags == nil {
27+ diags = []protocol.Diagnostic{}
28+ }
29+ _ = client.PublishDiagnostics(context.Background(), &protocol.PublishDiagnosticsParams{URI: u, Diagnostics: diags})
30+}
31+
32+// progress sends a $/progress notification of the given kind for token.
33+func progress(client protocol.Client, token, kind string) {
34+ _ = client.Progress(context.Background(), &protocol.ProgressParams{
35+ Token: protocol.String(token),
36+ Value: protocol.LSPAny(`{"kind":"` + kind + `","title":"Loading packages..."}`),
37+ })
38+}
39+
40+// The bug of ticket 294: the server first publishes an empty list (it is
41+// reloading the workspace), then the real errors. The first publication
42+// must not be taken as "clean".
43+func TestDiagnosticsWaitsPastAnEmptyPublicationFollowedByErrors(t *testing.T) {
44+ fake := newFake()
45+ fake.onSync = func(client protocol.Client, u uri.URI) {
46+ publish(client, u, nil)
47+ time.Sleep(100 * time.Millisecond)
48+ publish(client, u, importError())
49+ }
50+ c, _ := newClient(t, fake)
51+ c.diagWait, c.settle = 2*time.Second, 300*time.Millisecond
52+
53+ got, err := c.Diagnostics(context.Background(), "main.go")
54+ if err != nil || !strings.HasPrefix(got, "1 diagnostic(s) in main.go:\nerror main.go:5:2 could not import ../models") {
55+ t.Errorf("an empty publication followed by errors: %q, %v", got, err)
56+ }
57+}
58+
59+// While the server reports a work-done operation, an empty publication is
60+// not final, however long it stands: the end of the operation and the
61+// publication after it are what count.
62+func TestDiagnosticsWaitsForTheServersLoadToEnd(t *testing.T) {
63+ fake := newFake()
64+ fake.onSync = func(client protocol.Client, u uri.URI) {
65+ progress(client, "load-1", "begin")
66+ publish(client, u, nil)
67+ time.Sleep(250 * time.Millisecond) // longer than the settle delay
68+ publish(client, u, importError())
69+ progress(client, "load-1", "end")
70+ }
71+ c, _ := newClient(t, fake)
72+ c.diagWait, c.settle = 2*time.Second, 50*time.Millisecond
73+
74+ got, err := c.Diagnostics(context.Background(), "main.go")
75+ if err != nil || !strings.Contains(got, "could not import ../models") {
76+ t.Errorf("an empty publication during a load: %q, %v", got, err)
77+ }
78+}
79+
80+// A load still running when the wait is over is said plainly: never
81+// "clean".
82+func TestDiagnosticsDuringALoadThatOutlastsTheWaitIsNotClean(t *testing.T) {
83+ fake := newFake()
84+ fake.onSync = func(client protocol.Client, u uri.URI) {
85+ progress(client, "load-2", "begin")
86+ publish(client, u, nil)
87+ }
88+ c, _ := newClient(t, fake)
89+ c.diagWait, c.settle = 300*time.Millisecond, 50*time.Millisecond
90+
91+ got, err := c.Diagnostics(context.Background(), "main.go")
92+ if err != nil || !strings.Contains(got, "still loading the workspace — this does NOT mean the file is clean") {
93+ t.Errorf("a load that outlasts the wait: %q, %v", got, err)
94+ }
95+}
96+
97+// A clean file is still clean, once the empty publication has settled.
98+func TestDiagnosticsOnACleanFileAfterTheSettleDelay(t *testing.T) {
99+ fake := newFake()
100+ fake.onSync = func(client protocol.Client, u uri.URI) { publish(client, u, nil) }
101+ c, _ := newClient(t, fake)
102+ c.diagWait, c.settle = 2*time.Second, 100*time.Millisecond
103+
104+ start := time.Now()
105+ got, err := c.Diagnostics(context.Background(), "main.go")
106+ if err != nil || got != "no diagnostics: main.go is clean" {
107+ t.Errorf("clean file: %q, %v", got, err)
108+ }
109+ if waited := time.Since(start); waited < 100*time.Millisecond {
110+ t.Errorf("an empty publication was believed after %s, before the settle delay", waited)
111+ }
112+}
113+
114+// Errors are taken at once: no settle delay on a broken file.
115+func TestDiagnosticsWithErrorsAnswersWithoutTheSettleDelay(t *testing.T) {
116+ fake := newFake()
117+ fake.onSync = func(client protocol.Client, u uri.URI) { publish(client, u, importError()) }
118+ c, _ := newClient(t, fake)
119+ c.diagWait, c.settle = 2*time.Second, time.Second
120+
121+ start := time.Now()
122+ got, err := c.Diagnostics(context.Background(), "main.go")
123+ if err != nil || !strings.Contains(got, "could not import") {
124+ t.Errorf("broken file: %q, %v", got, err)
125+ }
126+ if waited := time.Since(start); waited > 500*time.Millisecond {
127+ t.Errorf("errors waited %s: they must be taken at once", waited)
128+ }
129+}
130+
131+func TestProgressKind(t *testing.T) {
132+ for value, want := range map[string]string{
133+ `{"kind":"begin","title":"Loading packages..."}`: "begin",
134+ `{"kind":"report","percentage":50}`: "report",
135+ `{"kind":"end"}`: "end",
136+ `[1,2]`: "",
137+ ``: "",
138+ } {
139+ if got := progressKind(protocol.LSPAny(value)); got != want {
140+ t.Errorf("progressKind(%s) = %q, want %q", value, got, want)
141+ }
142+ }
143+}
added internal/lsp/watch.go +118 -0
new file mode 100644
@@ -0,0 +1,118 @@
1+package lsp
2+
3+// Ticket 308: the project files a server reads its workspace from (go.mod,
4+// go.sum, package.json…) change behind mm's back — a bash `go get`, a
5+// `go mod tidy`, an `npm install`. Seen 2026-12-05 with Mellum2.1 Thinking:
6+// after `go get gopkg.in/yaml.v3`, gopls kept answering `could not import
7+// gopkg.in/yaml.v3` on every edit, the build passed, and the model spent
8+// calls chasing an error that no longer existed. A server learns about such
9+// changes only from the client (workspace/didChangeWatchedFiles), so mm
10+// looks at those files before each sync and tells the server what moved.
11+
12+import (
13+ "context"
14+ "os"
15+ "path/filepath"
16+ "sort"
17+ "strings"
18+ "time"
19+
20+ "go.lsp.dev/protocol"
21+ "go.lsp.dev/uri"
22+)
23+
24+// WorkspaceFiles are the files that describe a project rather than hold
25+// its code, by name: where a server finds its modules and dependencies.
26+var WorkspaceFiles = []string{
27+ "go.mod", "go.sum", "go.work", "go.work.sum",
28+ "package.json", "package-lock.json", "tsconfig.json", "jsconfig.json",
29+ "Cargo.toml", "Cargo.lock",
30+ "pyproject.toml", "requirements.txt",
31+}
32+
33+// FileStamp is one version of a file: its modification time and size, or
34+// absent. Comparable: two stamps are equal when the file did not change.
35+type FileStamp struct {
36+ Exists bool
37+ Mod time.Time
38+ Size int64
39+}
40+
41+// StampOf reads a file's stamp; a file that cannot be read is absent.
42+func StampOf(path string) FileStamp {
43+ info, err := os.Stat(path)
44+ if err != nil || info.IsDir() {
45+ return FileStamp{}
46+ }
47+ return FileStamp{Exists: true, Mod: info.ModTime(), Size: info.Size()}
48+}
49+
50+// WorkspaceFilesFor lists the workspace files that may concern a file: each
51+// name of WorkspaceFiles in the file's directory and in every directory
52+// above it up to root (included) — a Go module may sit in a subdirectory.
53+// A file outside root gets its own directory only.
54+//
55+// WorkspaceFilesFor("/p", "/p/api/main.go") // /p/api/go.mod … /p/go.mod …
56+func WorkspaceFilesFor(root, path string) []string {
57+ var out []string
58+ dir := filepath.Dir(path)
59+ for {
60+ for _, name := range WorkspaceFiles {
61+ out = append(out, filepath.Join(dir, name))
62+ }
63+ rel, err := filepath.Rel(root, dir)
64+ if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
65+ return out
66+ }
67+ parent := filepath.Dir(dir)
68+ if parent == dir {
69+ return out
70+ }
71+ dir = parent
72+ }
73+}
74+
75+// notifyWatched tells the server which workspace files changed since it
76+// last looked — for the directories of every document it holds and of
77+// path — with one workspace/didChangeWatchedFiles. A file seen for the first
78+// time only records its stamp: a server that starts reads the workspace as
79+// it is. Called by sync, before the file itself is synced, so the server
80+// rebuilds its view of the project before it diagnoses the file. The caller
81+// holds s.mu.
82+func (s *session) notifyWatched(ctx context.Context, path string) error {
83+ files := map[string]bool{}
84+ for _, f := range WorkspaceFilesFor(s.root, path) {
85+ files[f] = true
86+ }
87+ for _, doc := range s.docs {
88+ for _, f := range WorkspaceFilesFor(s.root, doc.path) {
89+ files[f] = true
90+ }
91+ }
92+ names := make([]string, 0, len(files))
93+ for f := range files {
94+ names = append(names, f)
95+ }
96+ sort.Strings(names) // a stable order for the server and the tests
97+ var changes []protocol.FileEvent
98+ for _, f := range names {
99+ now := StampOf(f)
100+ before, known := s.watched[f]
101+ s.watched[f] = now
102+ if !known || before == now {
103+ continue
104+ }
105+ kind := protocol.FileChangeTypeChanged
106+ switch {
107+ case !before.Exists:
108+ kind = protocol.FileChangeTypeCreated
109+ case !now.Exists:
110+ kind = protocol.FileChangeTypeDeleted
111+ }
112+ changes = append(changes, protocol.FileEvent{URI: uri.File(f), Type: kind})
113+ }
114+ if len(changes) == 0 {
115+ return nil
116+ }
117+ return s.server.DidChangeWatchedFiles(ctx, &protocol.DidChangeWatchedFilesParams{Changes: changes})
118+}
new file mode 100644
@@ -0,0 +1,118 @@
1+package lsp
2+
3+// Ticket 308: the project files a server reads its workspace from (go.mod,
4+// go.sum, package.json…) change behind mm's back — a bash `go get`, a
5+// `go mod tidy`, an `npm install`. Seen 2026-12-05 with Mellum2.1 Thinking:
6+// after `go get gopkg.in/yaml.v3`, gopls kept answering `could not import
7+// gopkg.in/yaml.v3` on every edit, the build passed, and the model spent
8+// calls chasing an error that no longer existed. A server learns about such
9+// changes only from the client (workspace/didChangeWatchedFiles), so mm
10+// looks at those files before each sync and tells the server what moved.
11+
12+import (
13+ "context"
14+ "os"
15+ "path/filepath"
16+ "sort"
17+ "strings"
18+ "time"
19+
20+ "go.lsp.dev/protocol"
21+ "go.lsp.dev/uri"
22+)
23+
24+// WorkspaceFiles are the files that describe a project rather than hold
25+// its code, by name: where a server finds its modules and dependencies.
26+var WorkspaceFiles = []string{
27+ "go.mod", "go.sum", "go.work", "go.work.sum",
28+ "package.json", "package-lock.json", "tsconfig.json", "jsconfig.json",
29+ "Cargo.toml", "Cargo.lock",
30+ "pyproject.toml", "requirements.txt",
31+}
32+
33+// FileStamp is one version of a file: its modification time and size, or
34+// absent. Comparable: two stamps are equal when the file did not change.
35+type FileStamp struct {
36+ Exists bool
37+ Mod time.Time
38+ Size int64
39+}
40+
41+// StampOf reads a file's stamp; a file that cannot be read is absent.
42+func StampOf(path string) FileStamp {
43+ info, err := os.Stat(path)
44+ if err != nil || info.IsDir() {
45+ return FileStamp{}
46+ }
47+ return FileStamp{Exists: true, Mod: info.ModTime(), Size: info.Size()}
48+}
49+
50+// WorkspaceFilesFor lists the workspace files that may concern a file: each
51+// name of WorkspaceFiles in the file's directory and in every directory
52+// above it up to root (included) — a Go module may sit in a subdirectory.
53+// A file outside root gets its own directory only.
54+//
55+// WorkspaceFilesFor("/p", "/p/api/main.go") // /p/api/go.mod … /p/go.mod …
56+func WorkspaceFilesFor(root, path string) []string {
57+ var out []string
58+ dir := filepath.Dir(path)
59+ for {
60+ for _, name := range WorkspaceFiles {
61+ out = append(out, filepath.Join(dir, name))
62+ }
63+ rel, err := filepath.Rel(root, dir)
64+ if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
65+ return out
66+ }
67+ parent := filepath.Dir(dir)
68+ if parent == dir {
69+ return out
70+ }
71+ dir = parent
72+ }
73+}
74+
75+// notifyWatched tells the server which workspace files changed since it
76+// last looked — for the directories of every document it holds and of
77+// path — with one workspace/didChangeWatchedFiles. A file seen for the first
78+// time only records its stamp: a server that starts reads the workspace as
79+// it is. Called by sync, before the file itself is synced, so the server
80+// rebuilds its view of the project before it diagnoses the file. The caller
81+// holds s.mu.
82+func (s *session) notifyWatched(ctx context.Context, path string) error {
83+ files := map[string]bool{}
84+ for _, f := range WorkspaceFilesFor(s.root, path) {
85+ files[f] = true
86+ }
87+ for _, doc := range s.docs {
88+ for _, f := range WorkspaceFilesFor(s.root, doc.path) {
89+ files[f] = true
90+ }
91+ }
92+ names := make([]string, 0, len(files))
93+ for f := range files {
94+ names = append(names, f)
95+ }
96+ sort.Strings(names) // a stable order for the server and the tests
97+ var changes []protocol.FileEvent
98+ for _, f := range names {
99+ now := StampOf(f)
100+ before, known := s.watched[f]
101+ s.watched[f] = now
102+ if !known || before == now {
103+ continue
104+ }
105+ kind := protocol.FileChangeTypeChanged
106+ switch {
107+ case !before.Exists:
108+ kind = protocol.FileChangeTypeCreated
109+ case !now.Exists:
110+ kind = protocol.FileChangeTypeDeleted
111+ }
112+ changes = append(changes, protocol.FileEvent{URI: uri.File(f), Type: kind})
113+ }
114+ if len(changes) == 0 {
115+ return nil
116+ }
117+ return s.server.DidChangeWatchedFiles(ctx, &protocol.DidChangeWatchedFilesParams{Changes: changes})
118+}
added internal/lsp/watch_test.go +103 -0
new file mode 100644
@@ -0,0 +1,103 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "os"
6+ "path/filepath"
7+ "reflect"
8+ "testing"
9+ "time"
10+
11+ "go.lsp.dev/protocol"
12+ "go.lsp.dev/uri"
13+)
14+
15+// awaitWatched waits until the server has received n file events, and
16+// returns them (a notification is handled after the call that sent it
17+// returns: see awaitDoc).
18+func (f *fakeServer) awaitWatched(t *testing.T, n int) []protocol.FileEvent {
19+ t.Helper()
20+ deadline := time.Now().Add(2 * time.Second)
21+ for {
22+ f.mu.Lock()
23+ got := append([]protocol.FileEvent(nil), f.watched...)
24+ f.mu.Unlock()
25+ if len(got) >= n || time.Now().After(deadline) {
26+ return got
27+ }
28+ time.Sleep(5 * time.Millisecond)
29+ }
30+}
31+
32+// Ticket 308: a workspace file changed behind mm's back (a bash `go get`)
33+// is announced before the next sync — created, changed, deleted — and
34+// nothing is sent when nothing moved, nor for what the server found on its
35+// first look.
36+func TestWorkspaceFileChangesAreAnnounced(t *testing.T) {
37+ fake := newFake()
38+ c, root := newClient(t, fake)
39+ ctx := context.Background()
40+ gomod := filepath.Join(root, "go.mod")
41+ if err := os.WriteFile(filepath.Join(root, "go.sum"), []byte("x\n"), 0o644); err != nil {
42+ t.Fatal(err)
43+ }
44+ call := func() {
45+ t.Helper()
46+ if _, err := c.Symbols(ctx, "main.go"); err != nil {
47+ t.Fatal(err)
48+ }
49+ }
50+ event := func(kind protocol.FileChangeType) protocol.FileEvent {
51+ return protocol.FileEvent{URI: uri.File(gomod), Type: kind}
52+ }
53+
54+ call() // first look: go.sum exists, go.mod does not — nothing to announce
55+ call()
56+ if got := fake.awaitWatched(t, 1); len(got) != 0 { // waits the full 2 s: proves a silence
57+ t.Fatalf("nothing changed, yet the server got %v", got)
58+ }
59+
60+ if err := os.WriteFile(gomod, []byte("module app\n"), 0o644); err != nil {
61+ t.Fatal(err)
62+ }
63+ call()
64+ if err := os.WriteFile(gomod, []byte("module app\n\nrequire example.com/dep v1.0.0\n"), 0o644); err != nil {
65+ t.Fatal(err)
66+ }
67+ call()
68+ if err := os.Remove(gomod); err != nil {
69+ t.Fatal(err)
70+ }
71+ call()
72+ call() // nothing more
73+ want := []protocol.FileEvent{
74+ event(protocol.FileChangeTypeCreated),
75+ event(protocol.FileChangeTypeChanged),
76+ event(protocol.FileChangeTypeDeleted),
77+ }
78+ if got := fake.awaitWatched(t, len(want)); !reflect.DeepEqual(got, want) {
79+ t.Errorf("events: got %v, want %v", got, want)
80+ }
81+}
82+
83+// The workspace files of a file: its directory and every one above it up
84+// to the root — a Go module may live in a subdirectory.
85+func TestWorkspaceFilesFor(t *testing.T) {
86+ root := filepath.FromSlash("/p")
87+ got := WorkspaceFilesFor(root, filepath.FromSlash("/p/api/main.go"))
88+ has := map[string]bool{}
89+ for _, f := range got {
90+ has[f] = true
91+ }
92+ for _, want := range []string{"/p/api/go.mod", "/p/go.mod", "/p/package.json"} {
93+ if !has[filepath.FromSlash(want)] {
94+ t.Errorf("%s missing from %v", want, got)
95+ }
96+ }
97+ if has[filepath.FromSlash("/go.mod")] {
98+ t.Errorf("went above the root: %v", got)
99+ }
100+ if out := WorkspaceFilesFor(root, filepath.FromSlash("/elsewhere/x.go")); len(out) != len(WorkspaceFiles) {
101+ t.Errorf("a file outside the root: only its own directory, got %v", out)
102+ }
103+}
new file mode 100644
@@ -0,0 +1,103 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "os"
6+ "path/filepath"
7+ "reflect"
8+ "testing"
9+ "time"
10+
11+ "go.lsp.dev/protocol"
12+ "go.lsp.dev/uri"
13+)
14+
15+// awaitWatched waits until the server has received n file events, and
16+// returns them (a notification is handled after the call that sent it
17+// returns: see awaitDoc).
18+func (f *fakeServer) awaitWatched(t *testing.T, n int) []protocol.FileEvent {
19+ t.Helper()
20+ deadline := time.Now().Add(2 * time.Second)
21+ for {
22+ f.mu.Lock()
23+ got := append([]protocol.FileEvent(nil), f.watched...)
24+ f.mu.Unlock()
25+ if len(got) >= n || time.Now().After(deadline) {
26+ return got
27+ }
28+ time.Sleep(5 * time.Millisecond)
29+ }
30+}
31+
32+// Ticket 308: a workspace file changed behind mm's back (a bash `go get`)
33+// is announced before the next sync — created, changed, deleted — and
34+// nothing is sent when nothing moved, nor for what the server found on its
35+// first look.
36+func TestWorkspaceFileChangesAreAnnounced(t *testing.T) {
37+ fake := newFake()
38+ c, root := newClient(t, fake)
39+ ctx := context.Background()
40+ gomod := filepath.Join(root, "go.mod")
41+ if err := os.WriteFile(filepath.Join(root, "go.sum"), []byte("x\n"), 0o644); err != nil {
42+ t.Fatal(err)
43+ }
44+ call := func() {
45+ t.Helper()
46+ if _, err := c.Symbols(ctx, "main.go"); err != nil {
47+ t.Fatal(err)
48+ }
49+ }
50+ event := func(kind protocol.FileChangeType) protocol.FileEvent {
51+ return protocol.FileEvent{URI: uri.File(gomod), Type: kind}
52+ }
53+
54+ call() // first look: go.sum exists, go.mod does not — nothing to announce
55+ call()
56+ if got := fake.awaitWatched(t, 1); len(got) != 0 { // waits the full 2 s: proves a silence
57+ t.Fatalf("nothing changed, yet the server got %v", got)
58+ }
59+
60+ if err := os.WriteFile(gomod, []byte("module app\n"), 0o644); err != nil {
61+ t.Fatal(err)
62+ }
63+ call()
64+ if err := os.WriteFile(gomod, []byte("module app\n\nrequire example.com/dep v1.0.0\n"), 0o644); err != nil {
65+ t.Fatal(err)
66+ }
67+ call()
68+ if err := os.Remove(gomod); err != nil {
69+ t.Fatal(err)
70+ }
71+ call()
72+ call() // nothing more
73+ want := []protocol.FileEvent{
74+ event(protocol.FileChangeTypeCreated),
75+ event(protocol.FileChangeTypeChanged),
76+ event(protocol.FileChangeTypeDeleted),
77+ }
78+ if got := fake.awaitWatched(t, len(want)); !reflect.DeepEqual(got, want) {
79+ t.Errorf("events: got %v, want %v", got, want)
80+ }
81+}
82+
83+// The workspace files of a file: its directory and every one above it up
84+// to the root — a Go module may live in a subdirectory.
85+func TestWorkspaceFilesFor(t *testing.T) {
86+ root := filepath.FromSlash("/p")
87+ got := WorkspaceFilesFor(root, filepath.FromSlash("/p/api/main.go"))
88+ has := map[string]bool{}
89+ for _, f := range got {
90+ has[f] = true
91+ }
92+ for _, want := range []string{"/p/api/go.mod", "/p/go.mod", "/p/package.json"} {
93+ if !has[filepath.FromSlash(want)] {
94+ t.Errorf("%s missing from %v", want, got)
95+ }
96+ }
97+ if has[filepath.FromSlash("/go.mod")] {
98+ t.Errorf("went above the root: %v", got)
99+ }
100+ if out := WorkspaceFilesFor(root, filepath.FromSlash("/elsewhere/x.go")); len(out) != len(WorkspaceFiles) {
101+ t.Errorf("a file outside the root: only its own directory, got %v", out)
102+ }
103+}
added internal/tools/bashshape.go +104 -0
new file mode 100644
@@ -0,0 +1,104 @@
1+package tools
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "strings"
7+
8+ "mm/internal/detector"
9+)
10+
11+// The shape of a bash call (ticket 297): what stays when the details a model
12+// changes while re-running the same test are removed. Two commands of the
13+// same shape, with outputs of the same shape and no file changed in between,
14+// are the same test run again — the loop detector counts them (WithSimilar)
15+// and, from the third, the result carries similarNote.
16+
17+// segmentSplit cuts a command line into its commands: `;`, `&&`, `||` and
18+// new lines. A pipe stays inside its command: `curl … | jq` is one test.
19+var segmentSplit = regexp.MustCompile(`;|&&|\|\||\n`)
20+
21+// waitCommands only kill, wait or say nothing: a model adds and removes them
22+// around the same test (`pkill app; sleep 2; ./test.sh`).
23+var waitCommands = map[string]bool{"pkill": true, "kill": true, "killall": true, "sleep": true, "wait": true, "true": true, ":": true}
24+
25+var (
26+ timeoutPrefix = regexp.MustCompile(`^timeout(\s+-\S+)*\s+\S+\s+`)
27+ redirection = regexp.MustCompile(`\s*\d*(>>|>|<)\s*&?\s*\S+`)
28+ number = regexp.MustCompile(`\d+(\.\d+)?`)
29+ space = regexp.MustCompile(`\s+`)
30+ // longNumber is a pid, a timing, a byte count: noise in an output. A
31+ // short number ("000", "404") is kept: it is often the result itself.
32+ longNumber = regexp.MustCompile(`\d+\.\d+|\d{4,}`)
33+)
34+
35+// commandShape reduces a command line to its tests: the wait commands
36+// dropped, `timeout N` and the redirections removed, every number written N,
37+// a trailing `&` and extra spaces gone.
38+//
39+// commandShape("pkill app; sleep 2; timeout 5 ./test.sh 2>&1") // "./test.sh"
40+// commandShape("curl -s localhost:8080/labels") // "curl -s localhost:N/labels"
41+func commandShape(command string) string {
42+ var kept []string
43+ for _, segment := range segmentSplit.Split(command, -1) {
44+ segment = strings.TrimSpace(segment)
45+ fields := strings.Fields(segment)
46+ if len(fields) == 0 || waitCommands[fields[0]] {
47+ continue
48+ }
49+ segment = timeoutPrefix.ReplaceAllString(segment, "")
50+ segment = redirection.ReplaceAllString(segment, "")
51+ segment = strings.TrimSuffix(strings.TrimSpace(segment), "&")
52+ segment = number.ReplaceAllString(segment, "N")
53+ segment = space.ReplaceAllString(strings.TrimSpace(segment), " ")
54+ if segment != "" {
55+ kept = append(kept, segment)
56+ }
57+ }
58+ return strings.Join(kept, " ; ")
59+}
60+
61+// outputShape is an output with its long numbers and its spacing evened out.
62+//
63+// outputShape("took 0.52s, pid 48213\n\n") // "took Ns, pid N"
64+func outputShape(output string) string {
65+ return space.ReplaceAllString(strings.TrimSpace(longNumber.ReplaceAllString(output, "N")), " ")
66+}
67+
68+// bashShape is the detector's Shape for a bash call; "" when the command
69+// is only waits and kills, which is no test.
70+func bashShape(command, output string) string {
71+ shape := commandShape(command)
72+ if shape == "" {
73+ return ""
74+ }
75+ return shape + "\x00" + outputShape(output)
76+}
77+
78+// similarNote follows the result of the n-th run of the same test with the
79+// same result, no file changed since. It is advice, never a refusal.
80+func similarNote(n int) string {
81+ return fmt.Sprintf("[mm: this is the same test, with the same result, for the %s time since the last file change — "+
82+ "sleeps, timeouts and kills aside. Running it again will not tell you more. Read the code it exercises "+
83+ "(or show the error the command hides: curl -sS, 2>&1) and change something before running it again.]", ordinal(n))
84+}
85+
86+// ordinal is n in words: 3 → "3rd".
87+func ordinal(n int) string {
88+ switch {
89+ case n%100 >= 11 && n%100 <= 13:
90+ return fmt.Sprintf("%dth", n)
91+ case n%10 == 1:
92+ return fmt.Sprintf("%dst", n)
93+ case n%10 == 2:
94+ return fmt.Sprintf("%dnd", n)
95+ case n%10 == 3:
96+ return fmt.Sprintf("%drd", n)
97+ }
98+ return fmt.Sprintf("%dth", n)
99+}
100+
101+// recordBash records a bash call with its shape.
102+func recordBash(d *detector.LoopDetector, command, out string, failed bool) (string, error) {
103+ return recordAction(d, detector.Action{ToolName: "bash", Input: command, Output: out, Failed: failed, Shape: bashShape(command, out)})
104+}
new file mode 100644
@@ -0,0 +1,104 @@
1+package tools
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "strings"
7+
8+ "mm/internal/detector"
9+)
10+
11+// The shape of a bash call (ticket 297): what stays when the details a model
12+// changes while re-running the same test are removed. Two commands of the
13+// same shape, with outputs of the same shape and no file changed in between,
14+// are the same test run again — the loop detector counts them (WithSimilar)
15+// and, from the third, the result carries similarNote.
16+
17+// segmentSplit cuts a command line into its commands: `;`, `&&`, `||` and
18+// new lines. A pipe stays inside its command: `curl … | jq` is one test.
19+var segmentSplit = regexp.MustCompile(`;|&&|\|\||\n`)
20+
21+// waitCommands only kill, wait or say nothing: a model adds and removes them
22+// around the same test (`pkill app; sleep 2; ./test.sh`).
23+var waitCommands = map[string]bool{"pkill": true, "kill": true, "killall": true, "sleep": true, "wait": true, "true": true, ":": true}
24+
25+var (
26+ timeoutPrefix = regexp.MustCompile(`^timeout(\s+-\S+)*\s+\S+\s+`)
27+ redirection = regexp.MustCompile(`\s*\d*(>>|>|<)\s*&?\s*\S+`)
28+ number = regexp.MustCompile(`\d+(\.\d+)?`)
29+ space = regexp.MustCompile(`\s+`)
30+ // longNumber is a pid, a timing, a byte count: noise in an output. A
31+ // short number ("000", "404") is kept: it is often the result itself.
32+ longNumber = regexp.MustCompile(`\d+\.\d+|\d{4,}`)
33+)
34+
35+// commandShape reduces a command line to its tests: the wait commands
36+// dropped, `timeout N` and the redirections removed, every number written N,
37+// a trailing `&` and extra spaces gone.
38+//
39+// commandShape("pkill app; sleep 2; timeout 5 ./test.sh 2>&1") // "./test.sh"
40+// commandShape("curl -s localhost:8080/labels") // "curl -s localhost:N/labels"
41+func commandShape(command string) string {
42+ var kept []string
43+ for _, segment := range segmentSplit.Split(command, -1) {
44+ segment = strings.TrimSpace(segment)
45+ fields := strings.Fields(segment)
46+ if len(fields) == 0 || waitCommands[fields[0]] {
47+ continue
48+ }
49+ segment = timeoutPrefix.ReplaceAllString(segment, "")
50+ segment = redirection.ReplaceAllString(segment, "")
51+ segment = strings.TrimSuffix(strings.TrimSpace(segment), "&")
52+ segment = number.ReplaceAllString(segment, "N")
53+ segment = space.ReplaceAllString(strings.TrimSpace(segment), " ")
54+ if segment != "" {
55+ kept = append(kept, segment)
56+ }
57+ }
58+ return strings.Join(kept, " ; ")
59+}
60+
61+// outputShape is an output with its long numbers and its spacing evened out.
62+//
63+// outputShape("took 0.52s, pid 48213\n\n") // "took Ns, pid N"
64+func outputShape(output string) string {
65+ return space.ReplaceAllString(strings.TrimSpace(longNumber.ReplaceAllString(output, "N")), " ")
66+}
67+
68+// bashShape is the detector's Shape for a bash call; "" when the command
69+// is only waits and kills, which is no test.
70+func bashShape(command, output string) string {
71+ shape := commandShape(command)
72+ if shape == "" {
73+ return ""
74+ }
75+ return shape + "\x00" + outputShape(output)
76+}
77+
78+// similarNote follows the result of the n-th run of the same test with the
79+// same result, no file changed since. It is advice, never a refusal.
80+func similarNote(n int) string {
81+ return fmt.Sprintf("[mm: this is the same test, with the same result, for the %s time since the last file change — "+
82+ "sleeps, timeouts and kills aside. Running it again will not tell you more. Read the code it exercises "+
83+ "(or show the error the command hides: curl -sS, 2>&1) and change something before running it again.]", ordinal(n))
84+}
85+
86+// ordinal is n in words: 3 → "3rd".
87+func ordinal(n int) string {
88+ switch {
89+ case n%100 >= 11 && n%100 <= 13:
90+ return fmt.Sprintf("%dth", n)
91+ case n%10 == 1:
92+ return fmt.Sprintf("%dst", n)
93+ case n%10 == 2:
94+ return fmt.Sprintf("%dnd", n)
95+ case n%10 == 3:
96+ return fmt.Sprintf("%drd", n)
97+ }
98+ return fmt.Sprintf("%dth", n)
99+}
100+
101+// recordBash records a bash call with its shape.
102+func recordBash(d *detector.LoopDetector, command, out string, failed bool) (string, error) {
103+ return recordAction(d, detector.Action{ToolName: "bash", Input: command, Output: out, Failed: failed, Shape: bashShape(command, out)})
104+}
added internal/tools/bashshape_test.go +70 -0
new file mode 100644
@@ -0,0 +1,70 @@
1+package tools
2+
3+import (
4+ "strings"
5+ "testing"
6+
7+ "mm/internal/detector"
8+)
9+
10+func TestCommandShape(t *testing.T) {
11+ cases := map[string]string{
12+ "pkill app; sleep 2; timeout 5 ./test.sh 2>&1": "./test.sh",
13+ "pkill -f app || true; sleep 1 && ./test.sh > /dev/null": "./test.sh",
14+ "curl -s localhost:8080/labels": "curl -s localhost:N/labels",
15+ "curl -sS localhost:8081/labels 2>/dev/null": "curl -sS localhost:N/labels",
16+ "./app &\nsleep 3\ncurl -s :8080/x | jq .": "./app ; curl -s :N/x | jq .",
17+ "sleep 2; pkill app": "",
18+ "go test ./...": "go test ./...",
19+ }
20+ for in, want := range cases {
21+ if got := commandShape(in); got != want {
22+ t.Errorf("commandShape(%q) = %q, want %q", in, got, want)
23+ }
24+ }
25+}
26+
27+func TestOutputShape(t *testing.T) {
28+ if got := outputShape("took 0.52s, pid 48213\n\nHTTP Status: 000\n"); got != "took Ns, pid N HTTP Status: 000" {
29+ t.Errorf("outputShape = %q", got)
30+ }
31+ if outputShape("HTTP Status: 000") == outputShape("HTTP Status: 200") {
32+ t.Error("a status code is the result itself: it must not be evened out")
33+ }
34+}
35+
36+// The sequence of ticket 297: the same full test, re-run with other sleeps,
37+// timeouts and kills, between single GETs — the third run of each gets the
38+// note; a real file change starts the count again. Nothing is ever stopped.
39+func TestSimilarBashRunsGetTheNote(t *testing.T) {
40+ d := detector.NewLoopDetector(10, 3).WithStop(3).WithSimilar(3)
41+ full := "\nHTTP Status: 000\n"
42+ get := `[{"name":"bug"}]`
43+ steps := []struct {
44+ command, out string
45+ noted bool
46+ }{
47+ {"pkill app; sleep 1; ./test.sh", full, false},
48+ {"curl -s localhost:8080/labels", get, false},
49+ {"pkill -f app; sleep 2; timeout 10 ./test.sh", full, false},
50+ {"sleep 1; curl -s localhost:8080/labels", get, false},
51+ {"pkill app; sleep 3; ./test.sh 2>/dev/null", full, true},
52+ {"curl -s localhost:8080/labels 2>&1", get, true},
53+ }
54+ for i, s := range steps {
55+ out, err := recordBash(d, s.command, s.out, false)
56+ if err != nil {
57+ t.Fatalf("step %d stopped the turn: %v", i+1, err)
58+ }
59+ if noted := strings.Contains(out, "this is the same test, with the same result, for the 3rd time"); noted != s.noted {
60+ t.Errorf("step %d (%s): noted = %v, want %v\n%s", i+1, s.command, noted, s.noted, out)
61+ }
62+ }
63+ // A real change: the next run is a check of that change.
64+ if _, err := recordAction(d, detector.Action{ToolName: "edit_file", Input: "main.go", Output: "main.go: 1 edit(s) applied", Changed: true}); err != nil {
65+ t.Fatal(err)
66+ }
67+ if out, _ := recordBash(d, "./test.sh", full, false); strings.Contains(out, "[mm: this is the same test") {
68+ t.Errorf("after an edit: %s", out)
69+ }
70+}
new file mode 100644
@@ -0,0 +1,70 @@
1+package tools
2+
3+import (
4+ "strings"
5+ "testing"
6+
7+ "mm/internal/detector"
8+)
9+
10+func TestCommandShape(t *testing.T) {
11+ cases := map[string]string{
12+ "pkill app; sleep 2; timeout 5 ./test.sh 2>&1": "./test.sh",
13+ "pkill -f app || true; sleep 1 && ./test.sh > /dev/null": "./test.sh",
14+ "curl -s localhost:8080/labels": "curl -s localhost:N/labels",
15+ "curl -sS localhost:8081/labels 2>/dev/null": "curl -sS localhost:N/labels",
16+ "./app &\nsleep 3\ncurl -s :8080/x | jq .": "./app ; curl -s :N/x | jq .",
17+ "sleep 2; pkill app": "",
18+ "go test ./...": "go test ./...",
19+ }
20+ for in, want := range cases {
21+ if got := commandShape(in); got != want {
22+ t.Errorf("commandShape(%q) = %q, want %q", in, got, want)
23+ }
24+ }
25+}
26+
27+func TestOutputShape(t *testing.T) {
28+ if got := outputShape("took 0.52s, pid 48213\n\nHTTP Status: 000\n"); got != "took Ns, pid N HTTP Status: 000" {
29+ t.Errorf("outputShape = %q", got)
30+ }
31+ if outputShape("HTTP Status: 000") == outputShape("HTTP Status: 200") {
32+ t.Error("a status code is the result itself: it must not be evened out")
33+ }
34+}
35+
36+// The sequence of ticket 297: the same full test, re-run with other sleeps,
37+// timeouts and kills, between single GETs — the third run of each gets the
38+// note; a real file change starts the count again. Nothing is ever stopped.
39+func TestSimilarBashRunsGetTheNote(t *testing.T) {
40+ d := detector.NewLoopDetector(10, 3).WithStop(3).WithSimilar(3)
41+ full := "\nHTTP Status: 000\n"
42+ get := `[{"name":"bug"}]`
43+ steps := []struct {
44+ command, out string
45+ noted bool
46+ }{
47+ {"pkill app; sleep 1; ./test.sh", full, false},
48+ {"curl -s localhost:8080/labels", get, false},
49+ {"pkill -f app; sleep 2; timeout 10 ./test.sh", full, false},
50+ {"sleep 1; curl -s localhost:8080/labels", get, false},
51+ {"pkill app; sleep 3; ./test.sh 2>/dev/null", full, true},
52+ {"curl -s localhost:8080/labels 2>&1", get, true},
53+ }
54+ for i, s := range steps {
55+ out, err := recordBash(d, s.command, s.out, false)
56+ if err != nil {
57+ t.Fatalf("step %d stopped the turn: %v", i+1, err)
58+ }
59+ if noted := strings.Contains(out, "this is the same test, with the same result, for the 3rd time"); noted != s.noted {
60+ t.Errorf("step %d (%s): noted = %v, want %v\n%s", i+1, s.command, noted, s.noted, out)
61+ }
62+ }
63+ // A real change: the next run is a check of that change.
64+ if _, err := recordAction(d, detector.Action{ToolName: "edit_file", Input: "main.go", Output: "main.go: 1 edit(s) applied", Changed: true}); err != nil {
65+ t.Fatal(err)
66+ }
67+ if out, _ := recordBash(d, "./test.sh", full, false); strings.Contains(out, "[mm: this is the same test") {
68+ t.Errorf("after an edit: %s", out)
69+ }
70+}
modified internal/tools/editdiag.go +105 -22
@@ -2,6 +2,7 @@ package tools
22
33 import (
44 "context"
5+ "fmt"
56 "os"
67 "path/filepath"
78 "strings"
@@ -10,6 +11,7 @@ import (
1011
1112 "mm/internal/config"
1213 "mm/internal/fileedit"
14+ "mm/internal/lsp"
1315 )
1416
1517 // Small models do not check their own edits: demos/gemma-coder asked in its
@@ -30,15 +32,33 @@ var editDiag struct {
3032 client LSPClient
3133 servers []config.LSPServer
3234 // seen: the version (modification time and size) of each file whose
33- // diagnostics the model already got, by absolute path. Reading the same
34- // unchanged file again does not ask the server again (ticket 245).
35- seen map[string]fileStamp
35+ // diagnostics the model already got, by absolute path, and the errors
36+ // they held. Reading the same unchanged file again does not ask the
37+ // server again (ticket 245); its errors are recalled (ticket 295).
38+ seen map[string]diagnosed
39+ // root: the project root the language servers were started on (the
40+ // working directory), where the workspace files are looked up.
41+ root string
3642 }
3743
38-// fileStamp identifies one version of a file.
44+// diagnosed is what the model was told about one version of a file.
45+type diagnosed struct {
46+ stamp fileStamp
47+ errors []string // the "error …" lines, in the server's order
48+ // recalls counts the reads of this version answered by errorsRecall
49+ // (ticket 307): a model reading a broken file in circles.
50+ recalls int
51+}
52+
53+// fileStamp identifies one version of a file, in one state of its
54+// workspace: the diagnostics of an unchanged file change when its go.mod
55+// does (a bash `go get`, ticket 308), so a recall must not outlive it.
3956 type fileStamp struct {
4057 mod time.Time
4158 size int64
59+ // workspace: the stamps of the workspace files that concern the file
60+ // (lsp.WorkspaceFilesFor), as one comparable string.
61+ workspace string
4262 }
4363
4464 // SetEditDiagnostics gives the file tools the language servers to ask after
@@ -51,7 +71,8 @@ func SetEditDiagnostics(client LSPClient, servers []config.LSPServer) {
5171 editDiag.mu.Lock()
5272 defer editDiag.mu.Unlock()
5373 editDiag.client, editDiag.servers = client, servers
54- editDiag.seen = map[string]fileStamp{}
74+ editDiag.seen = map[string]diagnosed{}
75+ editDiag.root, _ = os.Getwd()
5576 }
5677
5778 // diagnosticsAfter returns the note to append to a successful write or edit:
@@ -72,9 +93,11 @@ func diagnosticsAfter(r fileedit.Result) string {
7293
7394 // diagnosticsAfterRead returns the note to append to a successful read_file:
7495 // the server's diagnostics for the whole file, "" when
75-// `lsp.diagnosticsAfterRead` is off, no server handles the extension, or the
76-// model already got the diagnostics of this version of the file (after an
77-// earlier read or edit). Ticket 245: asked to "analyse @script.js", a model
96+// `lsp.diagnosticsAfterRead` is off, or no server handles the extension.
97+// When the model already got the diagnostics of this version of the file
98+// (after an earlier read or edit), the server is not asked again: the note
99+// is then empty for a clean file, and a short recall of the errors for a
100+// file that still has some (errorsRecall, ticket 295). Ticket 245: asked to "analyse @script.js", a model
78101 // reads the file and answers without ever calling the lsp tool.
79102 //
80103 // out := truncate(content) + diagnosticsAfterRead(path)
@@ -88,8 +111,8 @@ func diagnosticsAfterRead(path string) string {
88111 if client == nil || !served(servers, path) {
89112 return ""
90113 }
91- if alreadyDiagnosed(path) {
92- return ""
114+ if errs, recalls, seen := alreadyDiagnosed(path); seen {
115+ return errorsRecall(errs) + fixNudge(path, errs, recalls)
93116 }
94117 // The label says the note is not the file: seen 2026-11-20, a model took
95118 // "[lsp diagnostics for this file]" for part of the content it had read.
@@ -105,10 +128,46 @@ func askDiagnostics(client LSPClient, path, when string) string {
105128 if err != nil {
106129 return "\n[lsp diagnostics " + when + ": not available — " + err.Error() + "]"
107130 }
108- markDiagnosed(path)
131+ markDiagnosed(path, out)
109132 return "\n[lsp diagnostics " + when + "]\n" + strings.TrimSpace(out)
110133 }
111134
135+// recallErrors is how many error lines a recall repeats: enough to point at
136+// the lines to fix, short enough to read again on every read.
137+const recallErrors = 3
138+
139+// errorsRecall is the note for a re-read of a file whose diagnostics the
140+// model already got: nothing for a clean file or one with warnings only,
141+// a short reminder when it still has errors (ticket 295). Seen with Mellum2:
142+// `undefined: ioutil` was shown once, then the model read the file twelve
143+// times between no-op edits, each read without a word about line 38.
144+//
145+// errorsRecall([]string{"error main.go:38:9 undefined: ioutil"})
146+// // "\n[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still 1 error(s)]\nerror main.go:38:9 undefined: ioutil"
147+func errorsRecall(errs []string) string {
148+ if len(errs) == 0 {
149+ return ""
150+ }
151+ shown := errs[:min(len(errs), recallErrors)]
152+ note := fmt.Sprintf("\n[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still %d error(s)]\n%s",
153+ len(errs), strings.Join(shown, "\n"))
154+ if more := len(errs) - len(shown); more > 0 {
155+ note += fmt.Sprintf("\n… and %d more", more)
156+ }
157+ return note
158+}
159+
160+// errorLines are the "error …" lines of a Diagnostics answer.
161+func errorLines(out string) []string {
162+ var errs []string
163+ for _, line := range strings.Split(out, "\n") {
164+ if strings.HasPrefix(line, "error ") {
165+ errs = append(errs, line)
166+ }
167+ }
168+ return errs
169+}
170+
112171 // stampOf returns the file's absolute path and current version; ok is false
113172 // when the file cannot be read.
114173 func stampOf(path string) (string, fileStamp, bool) {
@@ -120,25 +179,49 @@ func stampOf(path string) (string, fileStamp, bool) {
120179 if err != nil {
121180 return "", fileStamp{}, false
122181 }
123- return abs, fileStamp{mod: info.ModTime(), size: info.Size()}, true
182+ editDiag.mu.Lock()
183+ root := editDiag.root
184+ editDiag.mu.Unlock()
185+ return abs, fileStamp{mod: info.ModTime(), size: info.Size(), workspace: workspaceStamp(root, abs)}, true
186+}
187+
188+// workspaceStamp sums up the workspace files of a file (go.mod, go.sum…)
189+// that exist: path, modification time and size of each.
190+func workspaceStamp(root, abs string) string {
191+ var b strings.Builder
192+ for _, f := range lsp.WorkspaceFilesFor(root, abs) {
193+ if st := lsp.StampOf(f); st.Exists {
194+ fmt.Fprintf(&b, "%s %d %d\n", f, st.Mod.UnixNano(), st.Size)
195+ }
196+ }
197+ return b.String()
124198 }
125199
126200 // alreadyDiagnosed reports whether the model got the diagnostics of the
127-// file's current version.
128-func alreadyDiagnosed(path string) bool {
201+// file's current version, and the errors they held; when it did, this read
202+// counts as one more recall, and recalls is how many there were so far,
203+// this one included (only a version with errors is counted).
204+func alreadyDiagnosed(path string) (errs []string, recalls int, seen bool) {
129205 abs, stamp, ok := stampOf(path)
130206 if !ok {
131- return false
207+ return nil, 0, false
132208 }
133209 editDiag.mu.Lock()
134210 defer editDiag.mu.Unlock()
135- last, seen := editDiag.seen[abs]
136- return seen && last == stamp
211+ last, known := editDiag.seen[abs]
212+ if !known || last.stamp != stamp {
213+ return nil, 0, false
214+ }
215+ if len(last.errors) > 0 {
216+ last.recalls++
217+ editDiag.seen[abs] = last
218+ }
219+ return last.errors, last.recalls, true
137220 }
138221
139-// markDiagnosed records that the model got the diagnostics of the file's
140-// current version.
141-func markDiagnosed(path string) {
222+// markDiagnosed records that the model got out, the diagnostics of the
223+// file's current version.
224+func markDiagnosed(path, out string) {
142225 abs, stamp, ok := stampOf(path)
143226 if !ok {
144227 return
@@ -146,9 +229,9 @@ func markDiagnosed(path string) {
146229 editDiag.mu.Lock()
147230 defer editDiag.mu.Unlock()
148231 if editDiag.seen == nil {
149- editDiag.seen = map[string]fileStamp{}
232+ editDiag.seen = map[string]diagnosed{}
150233 }
151- editDiag.seen[abs] = stamp
234+ editDiag.seen[abs] = diagnosed{stamp: stamp, errors: errorLines(out)}
152235 }
153236
154237 // served reports whether one of the servers handles the file's extension.
@@ -2,6 +2,7 @@ package tools
2 2
3 import (3 import (
4 "context"4 "context"
5+ "fmt"
5 "os"6 "os"
6 "path/filepath"7 "path/filepath"
7 "strings"8 "strings"
@@ -10,6 +11,7 @@ import (
10 11
11 "mm/internal/config"12 "mm/internal/config"
12 "mm/internal/fileedit"13 "mm/internal/fileedit"
14+ "mm/internal/lsp"
13 )15 )
14 16
15 // Small models do not check their own edits: demos/gemma-coder asked in its17 // Small models do not check their own edits: demos/gemma-coder asked in its
@@ -30,15 +32,33 @@ var editDiag struct {
30 client LSPClient32 client LSPClient
31 servers []config.LSPServer33 servers []config.LSPServer
32 // seen: the version (modification time and size) of each file whose34 // seen: the version (modification time and size) of each file whose
33- // diagnostics the model already got, by absolute path. Reading the same35+ // diagnostics the model already got, by absolute path, and the errors
34- // unchanged file again does not ask the server again (ticket 245).36+ // they held. Reading the same unchanged file again does not ask the
35- seen map[string]fileStamp37+ // server again (ticket 245); its errors are recalled (ticket 295).
38+ seen map[string]diagnosed
39+ // root: the project root the language servers were started on (the
40+ // working directory), where the workspace files are looked up.
41+ root string
36 }42 }
37 43
38-// fileStamp identifies one version of a file.44+// diagnosed is what the model was told about one version of a file.
45+type diagnosed struct {
46+ stamp fileStamp
47+ errors []string // the "error …" lines, in the server's order
48+ // recalls counts the reads of this version answered by errorsRecall
49+ // (ticket 307): a model reading a broken file in circles.
50+ recalls int
51+}
52+
53+// fileStamp identifies one version of a file, in one state of its
54+// workspace: the diagnostics of an unchanged file change when its go.mod
55+// does (a bash `go get`, ticket 308), so a recall must not outlive it.
39 type fileStamp struct {56 type fileStamp struct {
40 mod time.Time57 mod time.Time
41 size int6458 size int64
59+ // workspace: the stamps of the workspace files that concern the file
60+ // (lsp.WorkspaceFilesFor), as one comparable string.
61+ workspace string
42 }62 }
43 63
44 // SetEditDiagnostics gives the file tools the language servers to ask after64 // SetEditDiagnostics gives the file tools the language servers to ask after
@@ -51,7 +71,8 @@ func SetEditDiagnostics(client LSPClient, servers []config.LSPServer) {
51 editDiag.mu.Lock()71 editDiag.mu.Lock()
52 defer editDiag.mu.Unlock()72 defer editDiag.mu.Unlock()
53 editDiag.client, editDiag.servers = client, servers73 editDiag.client, editDiag.servers = client, servers
54- editDiag.seen = map[string]fileStamp{}74+ editDiag.seen = map[string]diagnosed{}
75+ editDiag.root, _ = os.Getwd()
55 }76 }
56 77
57 // diagnosticsAfter returns the note to append to a successful write or edit:78 // diagnosticsAfter returns the note to append to a successful write or edit:
@@ -72,9 +93,11 @@ func diagnosticsAfter(r fileedit.Result) string {
72 93
73 // diagnosticsAfterRead returns the note to append to a successful read_file:94 // diagnosticsAfterRead returns the note to append to a successful read_file:
74 // the server's diagnostics for the whole file, "" when95 // the server's diagnostics for the whole file, "" when
75-// `lsp.diagnosticsAfterRead` is off, no server handles the extension, or the96+// `lsp.diagnosticsAfterRead` is off, or no server handles the extension.
76-// model already got the diagnostics of this version of the file (after an97+// When the model already got the diagnostics of this version of the file
77-// earlier read or edit). Ticket 245: asked to "analyse @script.js", a model98+// (after an earlier read or edit), the server is not asked again: the note
99+// is then empty for a clean file, and a short recall of the errors for a
100+// file that still has some (errorsRecall, ticket 295). Ticket 245: asked to "analyse @script.js", a model
78 // reads the file and answers without ever calling the lsp tool.101 // reads the file and answers without ever calling the lsp tool.
79 //102 //
80 // out := truncate(content) + diagnosticsAfterRead(path)103 // out := truncate(content) + diagnosticsAfterRead(path)
@@ -88,8 +111,8 @@ func diagnosticsAfterRead(path string) string {
88 if client == nil || !served(servers, path) {111 if client == nil || !served(servers, path) {
89 return ""112 return ""
90 }113 }
91- if alreadyDiagnosed(path) {114+ if errs, recalls, seen := alreadyDiagnosed(path); seen {
92- return ""115+ return errorsRecall(errs) + fixNudge(path, errs, recalls)
93 }116 }
94 // The label says the note is not the file: seen 2026-11-20, a model took117 // The label says the note is not the file: seen 2026-11-20, a model took
95 // "[lsp diagnostics for this file]" for part of the content it had read.118 // "[lsp diagnostics for this file]" for part of the content it had read.
@@ -105,10 +128,46 @@ func askDiagnostics(client LSPClient, path, when string) string {
105 if err != nil {128 if err != nil {
106 return "\n[lsp diagnostics " + when + ": not available — " + err.Error() + "]"129 return "\n[lsp diagnostics " + when + ": not available — " + err.Error() + "]"
107 }130 }
108- markDiagnosed(path)131+ markDiagnosed(path, out)
109 return "\n[lsp diagnostics " + when + "]\n" + strings.TrimSpace(out)132 return "\n[lsp diagnostics " + when + "]\n" + strings.TrimSpace(out)
110 }133 }
111 134
135+// recallErrors is how many error lines a recall repeats: enough to point at
136+// the lines to fix, short enough to read again on every read.
137+const recallErrors = 3
138+
139+// errorsRecall is the note for a re-read of a file whose diagnostics the
140+// model already got: nothing for a clean file or one with warnings only,
141+// a short reminder when it still has errors (ticket 295). Seen with Mellum2:
142+// `undefined: ioutil` was shown once, then the model read the file twelve
143+// times between no-op edits, each read without a word about line 38.
144+//
145+// errorsRecall([]string{"error main.go:38:9 undefined: ioutil"})
146+// // "\n[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still 1 error(s)]\nerror main.go:38:9 undefined: ioutil"
147+func errorsRecall(errs []string) string {
148+ if len(errs) == 0 {
149+ return ""
150+ }
151+ shown := errs[:min(len(errs), recallErrors)]
152+ note := fmt.Sprintf("\n[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still %d error(s)]\n%s",
153+ len(errs), strings.Join(shown, "\n"))
154+ if more := len(errs) - len(shown); more > 0 {
155+ note += fmt.Sprintf("\n… and %d more", more)
156+ }
157+ return note
158+}
159+
160+// errorLines are the "error …" lines of a Diagnostics answer.
161+func errorLines(out string) []string {
162+ var errs []string
163+ for _, line := range strings.Split(out, "\n") {
164+ if strings.HasPrefix(line, "error ") {
165+ errs = append(errs, line)
166+ }
167+ }
168+ return errs
169+}
170+
112 // stampOf returns the file's absolute path and current version; ok is false171 // stampOf returns the file's absolute path and current version; ok is false
113 // when the file cannot be read.172 // when the file cannot be read.
114 func stampOf(path string) (string, fileStamp, bool) {173 func stampOf(path string) (string, fileStamp, bool) {
@@ -120,25 +179,49 @@ func stampOf(path string) (string, fileStamp, bool) {
120 if err != nil {179 if err != nil {
121 return "", fileStamp{}, false180 return "", fileStamp{}, false
122 }181 }
123- return abs, fileStamp{mod: info.ModTime(), size: info.Size()}, true182+ editDiag.mu.Lock()
183+ root := editDiag.root
184+ editDiag.mu.Unlock()
185+ return abs, fileStamp{mod: info.ModTime(), size: info.Size(), workspace: workspaceStamp(root, abs)}, true
186+}
187+
188+// workspaceStamp sums up the workspace files of a file (go.mod, go.sum…)
189+// that exist: path, modification time and size of each.
190+func workspaceStamp(root, abs string) string {
191+ var b strings.Builder
192+ for _, f := range lsp.WorkspaceFilesFor(root, abs) {
193+ if st := lsp.StampOf(f); st.Exists {
194+ fmt.Fprintf(&b, "%s %d %d\n", f, st.Mod.UnixNano(), st.Size)
195+ }
196+ }
197+ return b.String()
124 }198 }
125 199
126 // alreadyDiagnosed reports whether the model got the diagnostics of the200 // alreadyDiagnosed reports whether the model got the diagnostics of the
127-// file's current version.201+// file's current version, and the errors they held; when it did, this read
128-func alreadyDiagnosed(path string) bool {202+// counts as one more recall, and recalls is how many there were so far,
203+// this one included (only a version with errors is counted).
204+func alreadyDiagnosed(path string) (errs []string, recalls int, seen bool) {
129 abs, stamp, ok := stampOf(path)205 abs, stamp, ok := stampOf(path)
130 if !ok {206 if !ok {
131- return false207+ return nil, 0, false
132 }208 }
133 editDiag.mu.Lock()209 editDiag.mu.Lock()
134 defer editDiag.mu.Unlock()210 defer editDiag.mu.Unlock()
135- last, seen := editDiag.seen[abs]211+ last, known := editDiag.seen[abs]
136- return seen && last == stamp212+ if !known || last.stamp != stamp {
213+ return nil, 0, false
214+ }
215+ if len(last.errors) > 0 {
216+ last.recalls++
217+ editDiag.seen[abs] = last
218+ }
219+ return last.errors, last.recalls, true
137 }220 }
138 221
139-// markDiagnosed records that the model got the diagnostics of the file's222+// markDiagnosed records that the model got out, the diagnostics of the
140-// current version.223+// file's current version.
141-func markDiagnosed(path string) {224+func markDiagnosed(path, out string) {
142 abs, stamp, ok := stampOf(path)225 abs, stamp, ok := stampOf(path)
143 if !ok {226 if !ok {
144 return227 return
@@ -146,9 +229,9 @@ func markDiagnosed(path string) {
146 editDiag.mu.Lock()229 editDiag.mu.Lock()
147 defer editDiag.mu.Unlock()230 defer editDiag.mu.Unlock()
148 if editDiag.seen == nil {231 if editDiag.seen == nil {
149- editDiag.seen = map[string]fileStamp{}232+ editDiag.seen = map[string]diagnosed{}
150 }233 }
151- editDiag.seen[abs] = stamp234+ editDiag.seen[abs] = diagnosed{stamp: stamp, errors: errorLines(out)}
152 }235 }
153 236
154 // served reports whether one of the servers handles the file's extension.237 // served reports whether one of the servers handles the file's extension.
modified internal/tools/files.go +81 -41
@@ -89,13 +89,25 @@ func recordFailure(d *detector.LoopDetector, tool, input, out string) (string, e
8989
9090 // recordOutcome is record with the call's outcome.
9191 func recordOutcome(d *detector.LoopDetector, tool, input, out string, failed bool) (string, error) {
92- if !d.Record(detector.Action{ToolName: tool, Input: input, Output: out, Failed: failed}) {
93- return out, nil
94- }
95- if d.Stuck() {
96- return "", d.StuckError(tool)
92+ return recordAction(d, detector.Action{ToolName: tool, Input: input, Output: out, Failed: failed})
93+}
94+
95+// recordAction records a call and returns what the model reads: its output,
96+// with the loop instruction when the detector flagged it, or with
97+// similarNote when it closes a cycle of similar calls (ticket 297) — or the
98+// detector's stop.
99+func recordAction(d *detector.LoopDetector, action detector.Action) (string, error) {
100+ out := action.Output
101+ flagged, similar := d.Check(action)
102+ switch {
103+ case flagged && d.Stuck():
104+ return "", d.StuckError(action.ToolName)
105+ case flagged:
106+ return fmt.Sprintf("%s\n\n%s", out, d.LoopError()), nil
107+ case similar > 0:
108+ return fmt.Sprintf("%s\n\n%s", out, similarNote(similar)), nil
97109 }
98- return fmt.Sprintf("%s\n\n%s", out, d.LoopError()), nil
110+ return out, nil
99111 }
100112
101113 type readFileInput struct {
@@ -155,26 +167,46 @@ Returns a one-line summary and the diff against the previous content. Writing id
155167 return genkit.DefineTool(g, "write_file", description,
156168 func(tctx *ai.ToolContext, in writeFileInput) (string, error) {
157169 return guardPath(d, "write_file", &in.Path, func() (string, error) {
158- if s := ui.ActiveSink(); s != nil {
159- return writeFileEvented(tctx, s, d, in)
160- }
161- title := fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content))
162- announce("💾 " + title)
163- if !confirmed(tctx, "write_file", title) {
164- return refuse(d, "write_file", in.Path, "[write_file rejected by the user]")
165- }
166-
167- r, err := fileedit.Write(in.Path, in.Content)
168- if err != nil {
169- out := err.Error()
170- spinner.Suspend(func() { echoOutput(out) })
171- return recordFailure(d, "write_file", in.Path, out)
172- }
173- return report(d, "write_file", in.Path, r)
170+ repaired := repairWrite(ui.Resolve(in.Path), &in.Content)
171+ return withRepairNote(writeFile(tctx, d, in), repaired)
174172 })
175173 })
176174 }
177175
176+// writeFile runs write_file once its path and content are settled.
177+func writeFile(tctx *ai.ToolContext, d *detector.LoopDetector, in writeFileInput) func() (string, error) {
178+ return func() (string, error) {
179+ if s := ui.ActiveSink(); s != nil {
180+ return writeFileEvented(tctx, s, d, in)
181+ }
182+ title := fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content))
183+ announce("💾 " + title)
184+ if !confirmed(tctx, "write_file", title) {
185+ return refuse(d, "write_file", in.Path, "[write_file rejected by the user]")
186+ }
187+
188+ r, err := fileedit.Write(in.Path, in.Content)
189+ if err != nil {
190+ out := err.Error()
191+ spinner.Suspend(func() { echoOutput(out) })
192+ return recordFailure(d, "write_file", in.Path, out)
193+ }
194+ return report(d, "write_file", in.Path, r)
195+ }
196+}
197+
198+// withRepairNote runs the tool and appends the form-feed repair note
199+// (formfeed.go, ticket 300) to a result that came back — at the END: the
200+// first line is the tool's own headline, which the engine reads.
201+func withRepairNote(run func() (string, error), note string) (string, error) {
202+ out, err := run()
203+ if err != nil || note == "" {
204+ return out, err
205+ }
206+ ui.Notice("🩹 " + strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(note), "[mm: "), "]"))
207+ return out + note, nil
208+}
209+
178210 type editFileInput struct {
179211 Path string `json:"path" jsonschema_description:"Path of an EXISTING file, relative to the working directory"`
180212 Edits []fileedit.Edit `json:"edits" jsonschema_description:"The replacements, all resolved against the ORIGINAL file; two edits must not overlap"`
@@ -196,29 +228,37 @@ Nothing is written when any edit fails. Returns a one-line summary and the diff
196228 return genkit.DefineTool(g, "edit_file", description,
197229 func(tctx *ai.ToolContext, in editFileInput) (string, error) {
198230 return guardPath(d, "edit_file", &in.Path, func() (string, error) {
199- what := fmt.Sprintf("%s (%d edit(s))", in.Path, len(in.Edits))
200- if in.DryRun {
201- what += " dry-run"
202- }
203- if s := ui.ActiveSink(); s != nil {
204- return editFileEvented(tctx, s, d, in, what)
205- }
206- announce("📝 edit_file: " + what)
207- if !confirmed(tctx, "edit_file", "edit_file: "+what) {
208- return refuse(d, "edit_file", editKey(in), "[edit_file rejected by the user]")
209- }
210-
211- r, err := fileedit.Replace(in.Path, in.Edits, in.DryRun)
212- if err != nil {
213- out := err.Error()
214- spinner.Suspend(func() { echoOutput(out) })
215- return recordFailure(d, "edit_file", editKey(in), out)
216- }
217- return report(d, "edit_file", editKey(in), r)
231+ repaired := repairEdits(ui.Resolve(in.Path), in.Edits)
232+ return withRepairNote(editFile(tctx, d, in), repaired)
218233 })
219234 })
220235 }
221236
237+// editFile runs edit_file once its path and edits are settled.
238+func editFile(tctx *ai.ToolContext, d *detector.LoopDetector, in editFileInput) func() (string, error) {
239+ return func() (string, error) {
240+ what := fmt.Sprintf("%s (%d edit(s))", in.Path, len(in.Edits))
241+ if in.DryRun {
242+ what += " dry-run"
243+ }
244+ if s := ui.ActiveSink(); s != nil {
245+ return editFileEvented(tctx, s, d, in, what)
246+ }
247+ announce("📝 edit_file: " + what)
248+ if !confirmed(tctx, "edit_file", "edit_file: "+what) {
249+ return refuse(d, "edit_file", editKey(in), "[edit_file rejected by the user]")
250+ }
251+
252+ r, err := fileedit.Replace(in.Path, in.Edits, in.DryRun)
253+ if err != nil {
254+ out := err.Error()
255+ spinner.Suspend(func() { echoOutput(out) })
256+ return recordFailure(d, "edit_file", editKey(in), out)
257+ }
258+ return report(d, "edit_file", editKey(in), r)
259+ }
260+}
261+
222262 // editKey is what the loop detector compares for edit_file: the path AND the
223263 // edits. Two calls with the same path but different old texts are the model
224264 // correcting itself, not looping.
@@ -89,13 +89,25 @@ func recordFailure(d *detector.LoopDetector, tool, input, out string) (string, e
89 89
90 // recordOutcome is record with the call's outcome.90 // recordOutcome is record with the call's outcome.
91 func recordOutcome(d *detector.LoopDetector, tool, input, out string, failed bool) (string, error) {91 func recordOutcome(d *detector.LoopDetector, tool, input, out string, failed bool) (string, error) {
92- if !d.Record(detector.Action{ToolName: tool, Input: input, Output: out, Failed: failed}) {92+ return recordAction(d, detector.Action{ToolName: tool, Input: input, Output: out, Failed: failed})
93- return out, nil93+}
94- }94+
95- if d.Stuck() {95+// recordAction records a call and returns what the model reads: its output,
96- return "", d.StuckError(tool)96+// with the loop instruction when the detector flagged it, or with
97+// similarNote when it closes a cycle of similar calls (ticket 297) — or the
98+// detector's stop.
99+func recordAction(d *detector.LoopDetector, action detector.Action) (string, error) {
100+ out := action.Output
101+ flagged, similar := d.Check(action)
102+ switch {
103+ case flagged && d.Stuck():
104+ return "", d.StuckError(action.ToolName)
105+ case flagged:
106+ return fmt.Sprintf("%s\n\n%s", out, d.LoopError()), nil
107+ case similar > 0:
108+ return fmt.Sprintf("%s\n\n%s", out, similarNote(similar)), nil
97 }109 }
98- return fmt.Sprintf("%s\n\n%s", out, d.LoopError()), nil110+ return out, nil
99 }111 }
100 112
101 type readFileInput struct {113 type readFileInput struct {
@@ -155,26 +167,46 @@ Returns a one-line summary and the diff against the previous content. Writing id
155 return genkit.DefineTool(g, "write_file", description,167 return genkit.DefineTool(g, "write_file", description,
156 func(tctx *ai.ToolContext, in writeFileInput) (string, error) {168 func(tctx *ai.ToolContext, in writeFileInput) (string, error) {
157 return guardPath(d, "write_file", &in.Path, func() (string, error) {169 return guardPath(d, "write_file", &in.Path, func() (string, error) {
158- if s := ui.ActiveSink(); s != nil {170+ repaired := repairWrite(ui.Resolve(in.Path), &in.Content)
159- return writeFileEvented(tctx, s, d, in)171+ return withRepairNote(writeFile(tctx, d, in), repaired)
160- }
161- title := fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content))
162- announce("💾 " + title)
163- if !confirmed(tctx, "write_file", title) {
164- return refuse(d, "write_file", in.Path, "[write_file rejected by the user]")
165- }
166-
167- r, err := fileedit.Write(in.Path, in.Content)
168- if err != nil {
169- out := err.Error()
170- spinner.Suspend(func() { echoOutput(out) })
171- return recordFailure(d, "write_file", in.Path, out)
172- }
173- return report(d, "write_file", in.Path, r)
174 })172 })
175 })173 })
176 }174 }
177 175
176+// writeFile runs write_file once its path and content are settled.
177+func writeFile(tctx *ai.ToolContext, d *detector.LoopDetector, in writeFileInput) func() (string, error) {
178+ return func() (string, error) {
179+ if s := ui.ActiveSink(); s != nil {
180+ return writeFileEvented(tctx, s, d, in)
181+ }
182+ title := fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content))
183+ announce("💾 " + title)
184+ if !confirmed(tctx, "write_file", title) {
185+ return refuse(d, "write_file", in.Path, "[write_file rejected by the user]")
186+ }
187+
188+ r, err := fileedit.Write(in.Path, in.Content)
189+ if err != nil {
190+ out := err.Error()
191+ spinner.Suspend(func() { echoOutput(out) })
192+ return recordFailure(d, "write_file", in.Path, out)
193+ }
194+ return report(d, "write_file", in.Path, r)
195+ }
196+}
197+
198+// withRepairNote runs the tool and appends the form-feed repair note
199+// (formfeed.go, ticket 300) to a result that came back — at the END: the
200+// first line is the tool's own headline, which the engine reads.
201+func withRepairNote(run func() (string, error), note string) (string, error) {
202+ out, err := run()
203+ if err != nil || note == "" {
204+ return out, err
205+ }
206+ ui.Notice("🩹 " + strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(note), "[mm: "), "]"))
207+ return out + note, nil
208+}
209+
178 type editFileInput struct {210 type editFileInput struct {
179 Path string `json:"path" jsonschema_description:"Path of an EXISTING file, relative to the working directory"`211 Path string `json:"path" jsonschema_description:"Path of an EXISTING file, relative to the working directory"`
180 Edits []fileedit.Edit `json:"edits" jsonschema_description:"The replacements, all resolved against the ORIGINAL file; two edits must not overlap"`212 Edits []fileedit.Edit `json:"edits" jsonschema_description:"The replacements, all resolved against the ORIGINAL file; two edits must not overlap"`
@@ -196,29 +228,37 @@ Nothing is written when any edit fails. Returns a one-line summary and the diff
196 return genkit.DefineTool(g, "edit_file", description,228 return genkit.DefineTool(g, "edit_file", description,
197 func(tctx *ai.ToolContext, in editFileInput) (string, error) {229 func(tctx *ai.ToolContext, in editFileInput) (string, error) {
198 return guardPath(d, "edit_file", &in.Path, func() (string, error) {230 return guardPath(d, "edit_file", &in.Path, func() (string, error) {
199- what := fmt.Sprintf("%s (%d edit(s))", in.Path, len(in.Edits))231+ repaired := repairEdits(ui.Resolve(in.Path), in.Edits)
200- if in.DryRun {232+ return withRepairNote(editFile(tctx, d, in), repaired)
201- what += " dry-run"
202- }
203- if s := ui.ActiveSink(); s != nil {
204- return editFileEvented(tctx, s, d, in, what)
205- }
206- announce("📝 edit_file: " + what)
207- if !confirmed(tctx, "edit_file", "edit_file: "+what) {
208- return refuse(d, "edit_file", editKey(in), "[edit_file rejected by the user]")
209- }
210-
211- r, err := fileedit.Replace(in.Path, in.Edits, in.DryRun)
212- if err != nil {
213- out := err.Error()
214- spinner.Suspend(func() { echoOutput(out) })
215- return recordFailure(d, "edit_file", editKey(in), out)
216- }
217- return report(d, "edit_file", editKey(in), r)
218 })233 })
219 })234 })
220 }235 }
221 236
237+// editFile runs edit_file once its path and edits are settled.
238+func editFile(tctx *ai.ToolContext, d *detector.LoopDetector, in editFileInput) func() (string, error) {
239+ return func() (string, error) {
240+ what := fmt.Sprintf("%s (%d edit(s))", in.Path, len(in.Edits))
241+ if in.DryRun {
242+ what += " dry-run"
243+ }
244+ if s := ui.ActiveSink(); s != nil {
245+ return editFileEvented(tctx, s, d, in, what)
246+ }
247+ announce("📝 edit_file: " + what)
248+ if !confirmed(tctx, "edit_file", "edit_file: "+what) {
249+ return refuse(d, "edit_file", editKey(in), "[edit_file rejected by the user]")
250+ }
251+
252+ r, err := fileedit.Replace(in.Path, in.Edits, in.DryRun)
253+ if err != nil {
254+ out := err.Error()
255+ spinner.Suspend(func() { echoOutput(out) })
256+ return recordFailure(d, "edit_file", editKey(in), out)
257+ }
258+ return report(d, "edit_file", editKey(in), r)
259+ }
260+}
261+
222 // editKey is what the loop detector compares for edit_file: the path AND the262 // editKey is what the loop detector compares for edit_file: the path AND the
223 // edits. Two calls with the same path but different old texts are the model263 // edits. Two calls with the same path but different old texts are the model
224 // correcting itself, not looping.264 // correcting itself, not looping.
modified internal/tools/files_evented.go +18 -3
@@ -92,7 +92,7 @@ func writeFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector,
9292 res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}
9393 }
9494 s.ToolEnd(ev.ID, res)
95- return record(d, "write_file", in.Path, truncate(out))
95+ return recordChange(d, "write_file", in.Path, r, truncate(out))
9696 }
9797
9898 func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {
@@ -133,7 +133,7 @@ func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, i
133133 }
134134 }
135135 s.ToolEnd(ev.ID, res)
136- return record(d, "edit_file", editKey(in), truncate(out))
136+ return recordChange(d, "edit_file", editKey(in), r, truncate(out))
137137 }
138138
139139 // resultText is what report() builds for the model, without the echo: the
@@ -154,5 +154,20 @@ func resultText(r fileedit.Result) string {
154154 func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {
155155 out := resultText(r) + diagnosticsAfter(r)
156156 spinner.Suspend(func() { echoOutput(out) })
157- return record(d, tool, key, truncate(out))
157+ return recordChange(d, tool, key, r, truncate(out))
158+}
159+
160+// recordChange records a write_file / edit_file result. One that changed
161+// nothing — identical content, every edit already as asked — is a FAILURE
162+// for the loop detector (ticket 295), though the model still reads it as
163+// the plain fact it is: Mellum2 sent the same old == new edit twelve times,
164+// a read_file between each, and only the rule for failed calls repeated
165+// between others (ticket 240) sees that. A dry run changes nothing on
166+// purpose and stays a success.
167+//
168+// A real change is marked Changed: the detector counts similar commands
169+// again from there (ticket 297).
170+func recordChange(d *detector.LoopDetector, tool, key string, r fileedit.Result, out string) (string, error) {
171+ wrote := r.Changed && !r.DryRun
172+ return recordAction(d, detector.Action{ToolName: tool, Input: key, Output: out, Failed: !r.Changed && !r.DryRun, Changed: wrote})
158173 }
@@ -92,7 +92,7 @@ func writeFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector,
92 res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}92 res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}
93 }93 }
94 s.ToolEnd(ev.ID, res)94 s.ToolEnd(ev.ID, res)
95- return record(d, "write_file", in.Path, truncate(out))95+ return recordChange(d, "write_file", in.Path, r, truncate(out))
96 }96 }
97 97
98 func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {98 func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {
@@ -133,7 +133,7 @@ func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, i
133 }133 }
134 }134 }
135 s.ToolEnd(ev.ID, res)135 s.ToolEnd(ev.ID, res)
136- return record(d, "edit_file", editKey(in), truncate(out))136+ return recordChange(d, "edit_file", editKey(in), r, truncate(out))
137 }137 }
138 138
139 // resultText is what report() builds for the model, without the echo: the139 // resultText is what report() builds for the model, without the echo: the
@@ -154,5 +154,20 @@ func resultText(r fileedit.Result) string {
154 func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {154 func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {
155 out := resultText(r) + diagnosticsAfter(r)155 out := resultText(r) + diagnosticsAfter(r)
156 spinner.Suspend(func() { echoOutput(out) })156 spinner.Suspend(func() { echoOutput(out) })
157- return record(d, tool, key, truncate(out))157+ return recordChange(d, tool, key, r, truncate(out))
158+}
159+
160+// recordChange records a write_file / edit_file result. One that changed
161+// nothing — identical content, every edit already as asked — is a FAILURE
162+// for the loop detector (ticket 295), though the model still reads it as
163+// the plain fact it is: Mellum2 sent the same old == new edit twelve times,
164+// a read_file between each, and only the rule for failed calls repeated
165+// between others (ticket 240) sees that. A dry run changes nothing on
166+// purpose and stays a success.
167+//
168+// A real change is marked Changed: the detector counts similar commands
169+// again from there (ticket 297).
170+func recordChange(d *detector.LoopDetector, tool, key string, r fileedit.Result, out string) (string, error) {
171+ wrote := r.Changed && !r.DryRun
172+ return recordAction(d, detector.Action{ToolName: tool, Input: key, Output: out, Failed: !r.Changed && !r.DryRun, Changed: wrote})
158 }173 }
added internal/tools/formfeed.go +166 -0
new file mode 100644
@@ -0,0 +1,166 @@
1+package tools
2+
3+import (
4+ "fmt"
5+ "os"
6+ "path/filepath"
7+ "strings"
8+
9+ "mm/internal/fileedit"
10+)
11+
12+// Form feeds that stood for "\f" + a letter (ticket 300).
13+//
14+// Mellum models write a backslash before `func` in the JSON arguments of
15+// write_file: `"…)\n\func load()…"`. JSON reads `\f` as U+000C, a form feed,
16+// so the file gets `<FF>unc load()` and Go answers "invalid character
17+// U+000C". The study of the traces of 2026-12-02/03 (validation/mellum*,
18+// recorded in the ticket):
19+//
20+// - 8 form feeds in write_file / edit_file arguments, from Mellum2 Instruct
21+// Q8_0 and Mellum2.1 Thinking Q4_K_M and Q8_0 — none from Mellum2.1
22+// Instruct, Qwen3-Coder or the other agents; so not the quant, and not
23+// the provider (all on llmman) but the model.
24+// - EVERY ONE at the start of a line, before "unc ": the model meant a
25+// blank line then `func` ("\n\nfunc"), and lost the n of the second \n.
26+// - one was in an edit_file `old`, written on purpose to match the form
27+// feed already in the file: an old text is never repaired.
28+// - the models could not repair it themselves: the character is invisible
29+// (ticket 294), and their own `perl -pi -e 's/\x0c//g'` left `unc`.
30+//
31+// Legitimate form feeds never change: a page break (^L alone on its line,
32+// in C, Python, Lisp or Emacs sources, RFC texts, Makefiles) is not followed
33+// by a letter; a form feed inside a line is left alone; a file that already
34+// holds a form feed is left alone whole; only the source files of known
35+// languages are looked at, never data or text files; and only the new text
36+// of a call — write_file's content, edit_file's new — never an old text nor
37+// the rest of an existing file. The model is told every repair.
38+
39+// sourceExtensions are the files the repair looks at: source code, where a
40+// form feed starting a line before a word is never meant.
41+var sourceExtensions = map[string]bool{
42+ ".go": true, ".js": true, ".mjs": true, ".cjs": true, ".jsx": true, ".ts": true, ".tsx": true,
43+ ".py": true, ".rs": true, ".java": true, ".kt": true, ".swift": true, ".c": true, ".h": true,
44+ ".cc": true, ".cpp": true, ".hpp": true, ".cs": true, ".rb": true, ".php": true, ".lua": true,
45+ ".zig": true, ".scala": true, ".dart": true, ".sh": true,
46+}
47+
48+const formFeed = '\f'
49+
50+// repairFormFeeds returns text with every form feed that starts a line
51+// before a lowercase letter replaced by what the model meant, and the
52+// 1-based lines of text where it did. A form feed right after a new line
53+// becomes a new line and an f (the blank line before `func`); one after an
54+// indentation, or at the very start, becomes an f.
55+//
56+// repairFormFeeds(")\n\fmain()") // ")\n\nfmain()", [3]
57+// repairFormFeeds("x := \"\fa\"") // unchanged: inside a line
58+func repairFormFeeds(text string) (string, []int) {
59+ if !strings.ContainsRune(text, formFeed) {
60+ return text, nil
61+ }
62+ var b strings.Builder
63+ var lines []int
64+ line := 1
65+ for i := 0; i < len(text); i++ {
66+ c := text[i]
67+ if c == formFeed && startsLine(text, i) && i+1 < len(text) && isLower(text[i+1]) {
68+ if i > 0 && text[i-1] == '\n' {
69+ b.WriteString("\nf")
70+ line++
71+ } else {
72+ b.WriteByte('f')
73+ }
74+ lines = append(lines, line)
75+ continue
76+ }
77+ if c == '\n' {
78+ line++
79+ }
80+ b.WriteByte(c)
81+ }
82+ return b.String(), lines
83+}
84+
85+// startsLine reports whether only spaces and tabs stand between text[i]
86+// and the start of its line.
87+func startsLine(text string, i int) bool {
88+ for j := i - 1; j >= 0; j-- {
89+ switch text[j] {
90+ case '\n':
91+ return true
92+ case ' ', '\t':
93+ continue
94+ default:
95+ return false
96+ }
97+ }
98+ return true
99+}
100+
101+func isLower(c byte) bool { return c >= 'a' && c <= 'z' }
102+
103+// mayRepair reports whether the repair applies to path: a source file whose
104+// current content (if any) holds no form feed.
105+func mayRepair(path string) bool {
106+ if !sourceExtensions[strings.ToLower(filepath.Ext(path))] {
107+ return false
108+ }
109+ current, err := os.ReadFile(path)
110+ if err != nil {
111+ return true // a new file: nothing in it to keep
112+ }
113+ return !strings.ContainsRune(string(current), formFeed)
114+}
115+
116+// repairWrite applies the repair to write_file's content; note is what the
117+// model is told, "" when nothing was repaired.
118+func repairWrite(path string, content *string) (note string) {
119+ if !strings.ContainsRune(*content, formFeed) || !mayRepair(path) {
120+ return ""
121+ }
122+ fixed, lines := repairFormFeeds(*content)
123+ if len(lines) == 0 {
124+ return ""
125+ }
126+ *content = fixed
127+ return formFeedNote(len(lines), "line(s) "+joinInts(lines)+" of the file")
128+}
129+
130+// repairEdits applies the repair to the new text of each edit — never to
131+// the old one, which must match the file as it is.
132+func repairEdits(path string, edits []fileedit.Edit) (note string) {
133+ if !mayRepair(path) {
134+ return ""
135+ }
136+ count := 0
137+ var where []string
138+ for i := range edits {
139+ fixed, lines := repairFormFeeds(edits[i].New)
140+ if len(lines) == 0 {
141+ continue
142+ }
143+ edits[i].New = fixed
144+ count += len(lines)
145+ where = append(where, fmt.Sprintf("edit #%d new text, line(s) %s", i+1, joinInts(lines)))
146+ }
147+ if count == 0 {
148+ return ""
149+ }
150+ return formFeedNote(count, strings.Join(where, "; "))
151+}
152+
153+// formFeedNote tells the model what mm changed in what it asked to write.
154+func formFeedNote(count int, where string) string {
155+ return fmt.Sprintf("\n[mm: repaired %d form feed(s) (U+000C) at the start of a line, in %s: each stood for \"\\f\" + a word, and now reads as a new line then \"f…\" (\"\\n\\func\" → a blank line, then \"func\"). In JSON, \"\\f\" IS a form feed: write \"\\n\" for a new line, never a backslash before a letter.]",
156+ count, where)
157+}
158+
159+// joinInts is 3, 8, 21.
160+func joinInts(ns []int) string {
161+ parts := make([]string, len(ns))
162+ for i, n := range ns {
163+ parts[i] = fmt.Sprint(n)
164+ }
165+ return strings.Join(parts, ", ")
166+}
new file mode 100644
@@ -0,0 +1,166 @@
1+package tools
2+
3+import (
4+ "fmt"
5+ "os"
6+ "path/filepath"
7+ "strings"
8+
9+ "mm/internal/fileedit"
10+)
11+
12+// Form feeds that stood for "\f" + a letter (ticket 300).
13+//
14+// Mellum models write a backslash before `func` in the JSON arguments of
15+// write_file: `"…)\n\func load()…"`. JSON reads `\f` as U+000C, a form feed,
16+// so the file gets `<FF>unc load()` and Go answers "invalid character
17+// U+000C". The study of the traces of 2026-12-02/03 (validation/mellum*,
18+// recorded in the ticket):
19+//
20+// - 8 form feeds in write_file / edit_file arguments, from Mellum2 Instruct
21+// Q8_0 and Mellum2.1 Thinking Q4_K_M and Q8_0 — none from Mellum2.1
22+// Instruct, Qwen3-Coder or the other agents; so not the quant, and not
23+// the provider (all on llmman) but the model.
24+// - EVERY ONE at the start of a line, before "unc ": the model meant a
25+// blank line then `func` ("\n\nfunc"), and lost the n of the second \n.
26+// - one was in an edit_file `old`, written on purpose to match the form
27+// feed already in the file: an old text is never repaired.
28+// - the models could not repair it themselves: the character is invisible
29+// (ticket 294), and their own `perl -pi -e 's/\x0c//g'` left `unc`.
30+//
31+// Legitimate form feeds never change: a page break (^L alone on its line,
32+// in C, Python, Lisp or Emacs sources, RFC texts, Makefiles) is not followed
33+// by a letter; a form feed inside a line is left alone; a file that already
34+// holds a form feed is left alone whole; only the source files of known
35+// languages are looked at, never data or text files; and only the new text
36+// of a call — write_file's content, edit_file's new — never an old text nor
37+// the rest of an existing file. The model is told every repair.
38+
39+// sourceExtensions are the files the repair looks at: source code, where a
40+// form feed starting a line before a word is never meant.
41+var sourceExtensions = map[string]bool{
42+ ".go": true, ".js": true, ".mjs": true, ".cjs": true, ".jsx": true, ".ts": true, ".tsx": true,
43+ ".py": true, ".rs": true, ".java": true, ".kt": true, ".swift": true, ".c": true, ".h": true,
44+ ".cc": true, ".cpp": true, ".hpp": true, ".cs": true, ".rb": true, ".php": true, ".lua": true,
45+ ".zig": true, ".scala": true, ".dart": true, ".sh": true,
46+}
47+
48+const formFeed = '\f'
49+
50+// repairFormFeeds returns text with every form feed that starts a line
51+// before a lowercase letter replaced by what the model meant, and the
52+// 1-based lines of text where it did. A form feed right after a new line
53+// becomes a new line and an f (the blank line before `func`); one after an
54+// indentation, or at the very start, becomes an f.
55+//
56+// repairFormFeeds(")\n\fmain()") // ")\n\nfmain()", [3]
57+// repairFormFeeds("x := \"\fa\"") // unchanged: inside a line
58+func repairFormFeeds(text string) (string, []int) {
59+ if !strings.ContainsRune(text, formFeed) {
60+ return text, nil
61+ }
62+ var b strings.Builder
63+ var lines []int
64+ line := 1
65+ for i := 0; i < len(text); i++ {
66+ c := text[i]
67+ if c == formFeed && startsLine(text, i) && i+1 < len(text) && isLower(text[i+1]) {
68+ if i > 0 && text[i-1] == '\n' {
69+ b.WriteString("\nf")
70+ line++
71+ } else {
72+ b.WriteByte('f')
73+ }
74+ lines = append(lines, line)
75+ continue
76+ }
77+ if c == '\n' {
78+ line++
79+ }
80+ b.WriteByte(c)
81+ }
82+ return b.String(), lines
83+}
84+
85+// startsLine reports whether only spaces and tabs stand between text[i]
86+// and the start of its line.
87+func startsLine(text string, i int) bool {
88+ for j := i - 1; j >= 0; j-- {
89+ switch text[j] {
90+ case '\n':
91+ return true
92+ case ' ', '\t':
93+ continue
94+ default:
95+ return false
96+ }
97+ }
98+ return true
99+}
100+
101+func isLower(c byte) bool { return c >= 'a' && c <= 'z' }
102+
103+// mayRepair reports whether the repair applies to path: a source file whose
104+// current content (if any) holds no form feed.
105+func mayRepair(path string) bool {
106+ if !sourceExtensions[strings.ToLower(filepath.Ext(path))] {
107+ return false
108+ }
109+ current, err := os.ReadFile(path)
110+ if err != nil {
111+ return true // a new file: nothing in it to keep
112+ }
113+ return !strings.ContainsRune(string(current), formFeed)
114+}
115+
116+// repairWrite applies the repair to write_file's content; note is what the
117+// model is told, "" when nothing was repaired.
118+func repairWrite(path string, content *string) (note string) {
119+ if !strings.ContainsRune(*content, formFeed) || !mayRepair(path) {
120+ return ""
121+ }
122+ fixed, lines := repairFormFeeds(*content)
123+ if len(lines) == 0 {
124+ return ""
125+ }
126+ *content = fixed
127+ return formFeedNote(len(lines), "line(s) "+joinInts(lines)+" of the file")
128+}
129+
130+// repairEdits applies the repair to the new text of each edit — never to
131+// the old one, which must match the file as it is.
132+func repairEdits(path string, edits []fileedit.Edit) (note string) {
133+ if !mayRepair(path) {
134+ return ""
135+ }
136+ count := 0
137+ var where []string
138+ for i := range edits {
139+ fixed, lines := repairFormFeeds(edits[i].New)
140+ if len(lines) == 0 {
141+ continue
142+ }
143+ edits[i].New = fixed
144+ count += len(lines)
145+ where = append(where, fmt.Sprintf("edit #%d new text, line(s) %s", i+1, joinInts(lines)))
146+ }
147+ if count == 0 {
148+ return ""
149+ }
150+ return formFeedNote(count, strings.Join(where, "; "))
151+}
152+
153+// formFeedNote tells the model what mm changed in what it asked to write.
154+func formFeedNote(count int, where string) string {
155+ return fmt.Sprintf("\n[mm: repaired %d form feed(s) (U+000C) at the start of a line, in %s: each stood for \"\\f\" + a word, and now reads as a new line then \"f…\" (\"\\n\\func\" → a blank line, then \"func\"). In JSON, \"\\f\" IS a form feed: write \"\\n\" for a new line, never a backslash before a letter.]",
156+ count, where)
157+}
158+
159+// joinInts is 3, 8, 21.
160+func joinInts(ns []int) string {
161+ parts := make([]string, len(ns))
162+ for i, n := range ns {
163+ parts[i] = fmt.Sprint(n)
164+ }
165+ return strings.Join(parts, ", ")
166+}
added internal/tools/formfeed_test.go +132 -0
new file mode 100644
@@ -0,0 +1,132 @@
1+package tools
2+
3+import (
4+ "os"
5+ "path/filepath"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/fileedit"
10+)
11+
12+// The shapes of the traces (ticket 300): "\n\func" → a blank line then func.
13+func TestRepairFormFeedsShapesFromTheTraces(t *testing.T) {
14+ cases := []struct {
15+ in, want string
16+ lines []int
17+ }{
18+ {"package main\n\nvar labels []Label\n\fumc", "package main\n\nvar labels []Label\n\nfumc", []int{5}},
19+ {")\n\func loadLabels() {", ")\n\nfunc loadLabels() {", []int{3}},
20+ {"}\n\func saveLabels() {}\n}\n\func main() {}", "}\n\nfunc saveLabels() {}\n}\n\nfunc main() {}", []int{3, 6}},
21+ {"\func main() {}", "func main() {}", []int{1}}, // at the very start
22+ {"if x {\n\t\fmt.Println(x)\n}", "if x {\n\tfmt.Println(x)\n}", []int{2}}, // indented: the f only
23+ }
24+ for _, c := range cases {
25+ got, lines := repairFormFeeds(c.in)
26+ if got != c.want || !equalInts(lines, c.lines) {
27+ t.Errorf("repairFormFeeds(%q) = %q, %v; want %q, %v", c.in, got, lines, c.want, c.lines)
28+ }
29+ }
30+}
31+
32+// Legitimate form feeds never change.
33+func TestRepairFormFeedsLeavesLegitimateOnesAlone(t *testing.T) {
34+ for _, text := range []string{
35+ "int a;\n\f\nint b;\n", // a page break: alone on its line
36+ "\f\n/* page 2 */\n", // a page break at the start
37+ "s := \"\fabc\"\n", // inside a line
38+ "x\fy", // inside a line, no letter rule needed
39+ "\n\fFunc\n", // an upper-case letter: not the shape
40+ "\n\f1\n", // a digit: not the shape
41+ "no form feed at all\n", // nothing to do
42+ } {
43+ if got, lines := repairFormFeeds(text); got != text || lines != nil {
44+ t.Errorf("repairFormFeeds(%q) = %q, %v — it must not change", text, got, lines)
45+ }
46+ }
47+}
48+
49+// write_file: only source files, only when the file holds no form feed yet.
50+func TestRepairWriteScope(t *testing.T) {
51+ dir := t.TempDir()
52+ broken := ")\n\func main() {}\n"
53+
54+ content := broken
55+ if note := repairWrite(filepath.Join(dir, "main.go"), &content); content != ")\n\nfunc main() {}\n" || !strings.Contains(note, "repaired 1 form feed(s)") || !strings.Contains(note, "line(s) 3 of the file") {
56+ t.Errorf("new main.go: %q, note %q", content, note)
57+ }
58+
59+ for _, name := range []string{"notes.txt", "data.json", "rfc.md", "Makefile"} {
60+ content := broken
61+ if note := repairWrite(filepath.Join(dir, name), &content); content != broken || note != "" {
62+ t.Errorf("%s: %q, note %q — not a source file, must not change", name, content, note)
63+ }
64+ }
65+
66+ paged := filepath.Join(dir, "paged.c")
67+ if err := os.WriteFile(paged, []byte("int a;\n\f\nint b;\n"), 0o644); err != nil {
68+ t.Fatal(err)
69+ }
70+ content = broken
71+ if note := repairWrite(paged, &content); content != broken || note != "" {
72+ t.Errorf("a file that already holds a form feed: %q, note %q", content, note)
73+ }
74+}
75+
76+// edit_file: the new texts are repaired, the old ones never — an old text
77+// with a form feed is how a model fixes the one already in the file.
78+func TestRepairEditsNeverTouchesOld(t *testing.T) {
79+ dir := t.TempDir()
80+ path := filepath.Join(dir, "main.go")
81+ if err := os.WriteFile(path, []byte("package main\n"), 0o644); err != nil {
82+ t.Fatal(err)
83+ }
84+ edits := []fileedit.Edit{
85+ {Old: "\func save() {", New: "func save() {"},
86+ {Old: "package main\n", New: "package main\n\n\func main() {}\n"},
87+ }
88+ note := repairEdits(path, edits)
89+ if edits[0].Old != "\func save() {" || edits[0].New != "func save() {" {
90+ t.Errorf("edit 1 changed: %+v", edits[0])
91+ }
92+ if edits[1].New != "package main\n\n\nfunc main() {}\n" {
93+ t.Errorf("edit 2 new = %q", edits[1].New)
94+ }
95+ if !strings.Contains(note, "edit #2 new text, line(s) 4") || strings.Contains(note, "edit #1") {
96+ t.Errorf("note = %q", note)
97+ }
98+}
99+
100+// End to end on disk: the repaired content is what gets written, and the
101+// note comes after the headline, which stays the first line.
102+func TestRepairedWriteBuildsTheIntendedFile(t *testing.T) {
103+ path := filepath.Join(t.TempDir(), "main.go")
104+ content := "package main\n\nimport \"fmt\"\n\func main() { fmt.Println(1) }\n"
105+ note := repairWrite(path, &content)
106+ out, err := withRepairNote(func() (string, error) {
107+ r, err := fileedit.Write(path, content)
108+ return r.Headline, err
109+ }, note)
110+ if err != nil {
111+ t.Fatal(err)
112+ }
113+ written, _ := os.ReadFile(path)
114+ if strings.ContainsRune(string(written), '\f') || !strings.Contains(string(written), "\n\nfunc main()") {
115+ t.Errorf("written = %q", written)
116+ }
117+ if !strings.HasPrefix(out, path+": created") || !strings.Contains(out, "[mm: repaired 1 form feed(s)") {
118+ t.Errorf("out = %q", out)
119+ }
120+}
121+
122+func equalInts(a, b []int) bool {
123+ if len(a) != len(b) {
124+ return false
125+ }
126+ for i := range a {
127+ if a[i] != b[i] {
128+ return false
129+ }
130+ }
131+ return true
132+}
new file mode 100644
@@ -0,0 +1,132 @@
1+package tools
2+
3+import (
4+ "os"
5+ "path/filepath"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/fileedit"
10+)
11+
12+// The shapes of the traces (ticket 300): "\n\func" → a blank line then func.
13+func TestRepairFormFeedsShapesFromTheTraces(t *testing.T) {
14+ cases := []struct {
15+ in, want string
16+ lines []int
17+ }{
18+ {"package main\n\nvar labels []Label\n\fumc", "package main\n\nvar labels []Label\n\nfumc", []int{5}},
19+ {")\n\func loadLabels() {", ")\n\nfunc loadLabels() {", []int{3}},
20+ {"}\n\func saveLabels() {}\n}\n\func main() {}", "}\n\nfunc saveLabels() {}\n}\n\nfunc main() {}", []int{3, 6}},
21+ {"\func main() {}", "func main() {}", []int{1}}, // at the very start
22+ {"if x {\n\t\fmt.Println(x)\n}", "if x {\n\tfmt.Println(x)\n}", []int{2}}, // indented: the f only
23+ }
24+ for _, c := range cases {
25+ got, lines := repairFormFeeds(c.in)
26+ if got != c.want || !equalInts(lines, c.lines) {
27+ t.Errorf("repairFormFeeds(%q) = %q, %v; want %q, %v", c.in, got, lines, c.want, c.lines)
28+ }
29+ }
30+}
31+
32+// Legitimate form feeds never change.
33+func TestRepairFormFeedsLeavesLegitimateOnesAlone(t *testing.T) {
34+ for _, text := range []string{
35+ "int a;\n\f\nint b;\n", // a page break: alone on its line
36+ "\f\n/* page 2 */\n", // a page break at the start
37+ "s := \"\fabc\"\n", // inside a line
38+ "x\fy", // inside a line, no letter rule needed
39+ "\n\fFunc\n", // an upper-case letter: not the shape
40+ "\n\f1\n", // a digit: not the shape
41+ "no form feed at all\n", // nothing to do
42+ } {
43+ if got, lines := repairFormFeeds(text); got != text || lines != nil {
44+ t.Errorf("repairFormFeeds(%q) = %q, %v — it must not change", text, got, lines)
45+ }
46+ }
47+}
48+
49+// write_file: only source files, only when the file holds no form feed yet.
50+func TestRepairWriteScope(t *testing.T) {
51+ dir := t.TempDir()
52+ broken := ")\n\func main() {}\n"
53+
54+ content := broken
55+ if note := repairWrite(filepath.Join(dir, "main.go"), &content); content != ")\n\nfunc main() {}\n" || !strings.Contains(note, "repaired 1 form feed(s)") || !strings.Contains(note, "line(s) 3 of the file") {
56+ t.Errorf("new main.go: %q, note %q", content, note)
57+ }
58+
59+ for _, name := range []string{"notes.txt", "data.json", "rfc.md", "Makefile"} {
60+ content := broken
61+ if note := repairWrite(filepath.Join(dir, name), &content); content != broken || note != "" {
62+ t.Errorf("%s: %q, note %q — not a source file, must not change", name, content, note)
63+ }
64+ }
65+
66+ paged := filepath.Join(dir, "paged.c")
67+ if err := os.WriteFile(paged, []byte("int a;\n\f\nint b;\n"), 0o644); err != nil {
68+ t.Fatal(err)
69+ }
70+ content = broken
71+ if note := repairWrite(paged, &content); content != broken || note != "" {
72+ t.Errorf("a file that already holds a form feed: %q, note %q", content, note)
73+ }
74+}
75+
76+// edit_file: the new texts are repaired, the old ones never — an old text
77+// with a form feed is how a model fixes the one already in the file.
78+func TestRepairEditsNeverTouchesOld(t *testing.T) {
79+ dir := t.TempDir()
80+ path := filepath.Join(dir, "main.go")
81+ if err := os.WriteFile(path, []byte("package main\n"), 0o644); err != nil {
82+ t.Fatal(err)
83+ }
84+ edits := []fileedit.Edit{
85+ {Old: "\func save() {", New: "func save() {"},
86+ {Old: "package main\n", New: "package main\n\n\func main() {}\n"},
87+ }
88+ note := repairEdits(path, edits)
89+ if edits[0].Old != "\func save() {" || edits[0].New != "func save() {" {
90+ t.Errorf("edit 1 changed: %+v", edits[0])
91+ }
92+ if edits[1].New != "package main\n\n\nfunc main() {}\n" {
93+ t.Errorf("edit 2 new = %q", edits[1].New)
94+ }
95+ if !strings.Contains(note, "edit #2 new text, line(s) 4") || strings.Contains(note, "edit #1") {
96+ t.Errorf("note = %q", note)
97+ }
98+}
99+
100+// End to end on disk: the repaired content is what gets written, and the
101+// note comes after the headline, which stays the first line.
102+func TestRepairedWriteBuildsTheIntendedFile(t *testing.T) {
103+ path := filepath.Join(t.TempDir(), "main.go")
104+ content := "package main\n\nimport \"fmt\"\n\func main() { fmt.Println(1) }\n"
105+ note := repairWrite(path, &content)
106+ out, err := withRepairNote(func() (string, error) {
107+ r, err := fileedit.Write(path, content)
108+ return r.Headline, err
109+ }, note)
110+ if err != nil {
111+ t.Fatal(err)
112+ }
113+ written, _ := os.ReadFile(path)
114+ if strings.ContainsRune(string(written), '\f') || !strings.Contains(string(written), "\n\nfunc main()") {
115+ t.Errorf("written = %q", written)
116+ }
117+ if !strings.HasPrefix(out, path+": created") || !strings.Contains(out, "[mm: repaired 1 form feed(s)") {
118+ t.Errorf("out = %q", out)
119+ }
120+}
121+
122+func equalInts(a, b []int) bool {
123+ if len(a) != len(b) {
124+ return false
125+ }
126+ for i := range a {
127+ if a[i] != b[i] {
128+ return false
129+ }
130+ }
131+ return true
132+}
added internal/tools/noop_test.go +126 -0
new file mode 100644
@@ -0,0 +1,126 @@
1+package tools
2+
3+import (
4+ "context"
5+ "errors"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/detector"
10+ "mm/internal/fileedit"
11+)
12+
13+// Ticket 295: Mellum2 sent the same edit_file with old == new twelve times,
14+// a read_file between each. A no-op edit is a failure for the detector, so
15+// the interleaved-failure rule of ticket 240 flags it once it has occurred
16+// threshold (3) times, whatever comes between, and stops the turn after
17+// stopAfter (3) flagged repeats.
18+func TestNoOpEditsBetweenReadsAreFlaggedThenStopped(t *testing.T) {
19+ path := writeTemp(t, "yaml.go", "package storage\n\nimport (\n\t\"io/ioutil\"\n)\n")
20+ d := detector.NewLoopDetector(10, 3).WithStop(3)
21+ in := editFileInput{Path: path, Edits: []fileedit.Edit{{Old: "\"io/ioutil\"", New: "\"io/ioutil\""}}}
22+
23+ var stuck error
24+ flagged := 0
25+ for call := 1; call <= 12 && stuck == nil; call++ {
26+ r, err := fileedit.Replace(path, in.Edits, false)
27+ if err != nil {
28+ t.Fatal(err)
29+ }
30+ out, err := report(d, "edit_file", editKey(in), r)
31+ switch {
32+ case err != nil:
33+ stuck = err
34+ case strings.Contains(out, "[LOOP_DETECTED"):
35+ flagged++
36+ if flagged == 1 && call != 4 {
37+ t.Errorf("first flag at call %d, want the 4th (3 earlier occurrences)", call)
38+ }
39+ }
40+ if _, err := record(d, "read_file", path, "the file"); err != nil {
41+ t.Fatalf("read_file %d: %v", call, err)
42+ }
43+ }
44+ var s *detector.Stuck
45+ if !errors.As(stuck, &s) || s.Tool != "edit_file" {
46+ t.Fatalf("the no-op edits never stopped the turn (flagged %d times): %v", flagged, stuck)
47+ }
48+ if flagged != 2 {
49+ t.Errorf("flagged %d times before the stop, want 2", flagged)
50+ }
51+}
52+
53+// A real change stays a success: the same call repeated after real changes
54+// is never flagged by the failure rule.
55+func TestRealEditsAreNotFailures(t *testing.T) {
56+ d := detector.NewLoopDetector(10, 3)
57+ path := writeTemp(t, "a.go", "package a\n")
58+ for i := 0; i < 5; i++ {
59+ r, err := fileedit.Write(path, "package a\n"+strings.Repeat("\n", i+1))
60+ if err != nil {
61+ t.Fatal(err)
62+ }
63+ out, err := recordChange(d, "write_file", path, r, resultText(r))
64+ if err != nil || strings.Contains(out, "LOOP_DETECTED") {
65+ t.Fatalf("write %d: %q, %v", i, out, err)
66+ }
67+ _, _ = record(d, "read_file", path, "x")
68+ }
69+ // A dry run changes nothing on purpose: not a failure either.
70+ r, err := fileedit.Replace(path, []fileedit.Edit{{Old: "package a", New: "package b"}}, true)
71+ if err != nil {
72+ t.Fatal(err)
73+ }
74+ for i := 0; i < 5; i++ {
75+ if out, err := recordChange(d, "edit_file", "k", r, resultText(r)); err != nil || strings.Contains(out, "LOOP_DETECTED") {
76+ t.Fatalf("dry run %d between reads: %q, %v", i, out, err)
77+ }
78+ _, _ = record(d, "read_file", path, "x")
79+ }
80+}
81+
82+// brokenLSP answers like gopls on a file that does not build.
83+type brokenLSP struct {
84+ cannedLSP
85+ calls *int
86+}
87+
88+func (b brokenLSP) Diagnostics(context.Context, string) (string, error) {
89+ *b.calls++
90+ return "5 diagnostic(s) in yaml.go:\n" +
91+ "error yaml.go:38:9 undefined: ioutil [compiler]\n" +
92+ "warning yaml.go:40:2 unusedresult [vet]\n" +
93+ "error yaml.go:49:15 undefined: ioutil [compiler]\n" +
94+ "error yaml.go:50:1 missing return [compiler]\n" +
95+ "error yaml.go:51:1 missing return [compiler]", nil
96+}
97+
98+// Ticket 295: a re-read of an unchanged file that still has errors recalls
99+// them in short — without asking the server again.
100+func TestDiagnosticsAfterReadRecallsErrors(t *testing.T) {
101+ calls := 0
102+ withReadDiagnostics(t, true, brokenLSP{calls: &calls})
103+ path := writeTemp(t, "yaml.go", "package storage\n")
104+ if note := diagnosticsAfterRead(path); !strings.Contains(note, "undefined: ioutil") {
105+ t.Fatalf("first read: %q", note)
106+ }
107+ note := diagnosticsAfterRead(path)
108+ want := "\n[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still 4 error(s)]\n" +
109+ "error yaml.go:38:9 undefined: ioutil [compiler]\n" +
110+ "error yaml.go:49:15 undefined: ioutil [compiler]\n" +
111+ "error yaml.go:50:1 missing return [compiler]\n" +
112+ "… and 1 more"
113+ if note != want || calls != 1 {
114+ t.Errorf("second read: note = %q, calls = %d; want the recall, 1", note, calls)
115+ }
116+}
117+
118+func TestErrorsRecall(t *testing.T) {
119+ if got := errorsRecall(nil); got != "" {
120+ t.Errorf("no errors: %q", got)
121+ }
122+ got := errorsRecall([]string{"error main.go:38:9 undefined: ioutil"})
123+ if !strings.HasSuffix(got, "still 1 error(s)]\nerror main.go:38:9 undefined: ioutil") {
124+ t.Errorf("one error: %q", got)
125+ }
126+}
new file mode 100644
@@ -0,0 +1,126 @@
1+package tools
2+
3+import (
4+ "context"
5+ "errors"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/detector"
10+ "mm/internal/fileedit"
11+)
12+
13+// Ticket 295: Mellum2 sent the same edit_file with old == new twelve times,
14+// a read_file between each. A no-op edit is a failure for the detector, so
15+// the interleaved-failure rule of ticket 240 flags it once it has occurred
16+// threshold (3) times, whatever comes between, and stops the turn after
17+// stopAfter (3) flagged repeats.
18+func TestNoOpEditsBetweenReadsAreFlaggedThenStopped(t *testing.T) {
19+ path := writeTemp(t, "yaml.go", "package storage\n\nimport (\n\t\"io/ioutil\"\n)\n")
20+ d := detector.NewLoopDetector(10, 3).WithStop(3)
21+ in := editFileInput{Path: path, Edits: []fileedit.Edit{{Old: "\"io/ioutil\"", New: "\"io/ioutil\""}}}
22+
23+ var stuck error
24+ flagged := 0
25+ for call := 1; call <= 12 && stuck == nil; call++ {
26+ r, err := fileedit.Replace(path, in.Edits, false)
27+ if err != nil {
28+ t.Fatal(err)
29+ }
30+ out, err := report(d, "edit_file", editKey(in), r)
31+ switch {
32+ case err != nil:
33+ stuck = err
34+ case strings.Contains(out, "[LOOP_DETECTED"):
35+ flagged++
36+ if flagged == 1 && call != 4 {
37+ t.Errorf("first flag at call %d, want the 4th (3 earlier occurrences)", call)
38+ }
39+ }
40+ if _, err := record(d, "read_file", path, "the file"); err != nil {
41+ t.Fatalf("read_file %d: %v", call, err)
42+ }
43+ }
44+ var s *detector.Stuck
45+ if !errors.As(stuck, &s) || s.Tool != "edit_file" {
46+ t.Fatalf("the no-op edits never stopped the turn (flagged %d times): %v", flagged, stuck)
47+ }
48+ if flagged != 2 {
49+ t.Errorf("flagged %d times before the stop, want 2", flagged)
50+ }
51+}
52+
53+// A real change stays a success: the same call repeated after real changes
54+// is never flagged by the failure rule.
55+func TestRealEditsAreNotFailures(t *testing.T) {
56+ d := detector.NewLoopDetector(10, 3)
57+ path := writeTemp(t, "a.go", "package a\n")
58+ for i := 0; i < 5; i++ {
59+ r, err := fileedit.Write(path, "package a\n"+strings.Repeat("\n", i+1))
60+ if err != nil {
61+ t.Fatal(err)
62+ }
63+ out, err := recordChange(d, "write_file", path, r, resultText(r))
64+ if err != nil || strings.Contains(out, "LOOP_DETECTED") {
65+ t.Fatalf("write %d: %q, %v", i, out, err)
66+ }
67+ _, _ = record(d, "read_file", path, "x")
68+ }
69+ // A dry run changes nothing on purpose: not a failure either.
70+ r, err := fileedit.Replace(path, []fileedit.Edit{{Old: "package a", New: "package b"}}, true)
71+ if err != nil {
72+ t.Fatal(err)
73+ }
74+ for i := 0; i < 5; i++ {
75+ if out, err := recordChange(d, "edit_file", "k", r, resultText(r)); err != nil || strings.Contains(out, "LOOP_DETECTED") {
76+ t.Fatalf("dry run %d between reads: %q, %v", i, out, err)
77+ }
78+ _, _ = record(d, "read_file", path, "x")
79+ }
80+}
81+
82+// brokenLSP answers like gopls on a file that does not build.
83+type brokenLSP struct {
84+ cannedLSP
85+ calls *int
86+}
87+
88+func (b brokenLSP) Diagnostics(context.Context, string) (string, error) {
89+ *b.calls++
90+ return "5 diagnostic(s) in yaml.go:\n" +
91+ "error yaml.go:38:9 undefined: ioutil [compiler]\n" +
92+ "warning yaml.go:40:2 unusedresult [vet]\n" +
93+ "error yaml.go:49:15 undefined: ioutil [compiler]\n" +
94+ "error yaml.go:50:1 missing return [compiler]\n" +
95+ "error yaml.go:51:1 missing return [compiler]", nil
96+}
97+
98+// Ticket 295: a re-read of an unchanged file that still has errors recalls
99+// them in short — without asking the server again.
100+func TestDiagnosticsAfterReadRecallsErrors(t *testing.T) {
101+ calls := 0
102+ withReadDiagnostics(t, true, brokenLSP{calls: &calls})
103+ path := writeTemp(t, "yaml.go", "package storage\n")
104+ if note := diagnosticsAfterRead(path); !strings.Contains(note, "undefined: ioutil") {
105+ t.Fatalf("first read: %q", note)
106+ }
107+ note := diagnosticsAfterRead(path)
108+ want := "\n[lsp diagnostics for this file, added by mm — not part of its content: unchanged since you were told, still 4 error(s)]\n" +
109+ "error yaml.go:38:9 undefined: ioutil [compiler]\n" +
110+ "error yaml.go:49:15 undefined: ioutil [compiler]\n" +
111+ "error yaml.go:50:1 missing return [compiler]\n" +
112+ "… and 1 more"
113+ if note != want || calls != 1 {
114+ t.Errorf("second read: note = %q, calls = %d; want the recall, 1", note, calls)
115+ }
116+}
117+
118+func TestErrorsRecall(t *testing.T) {
119+ if got := errorsRecall(nil); got != "" {
120+ t.Errorf("no errors: %q", got)
121+ }
122+ got := errorsRecall([]string{"error main.go:38:9 undefined: ioutil"})
123+ if !strings.HasSuffix(got, "still 1 error(s)]\nerror main.go:38:9 undefined: ioutil") {
124+ t.Errorf("one error: %q", got)
125+ }
126+}
modified internal/tools/plan.go +20 -23
@@ -58,8 +58,9 @@ type planInput struct {
5858 Tasks []PlanTaskInput `json:"tasks,omitempty" jsonschema_description:"For create action: list of tasks to add"`
5959 // TaskID identifies which task for update/next actions (1-based)
6060 TaskID int `json:"taskId,omitempty" jsonschema_description:"Task ID (1-based) for update/delete/get actions"`
61- // Status is used with 'update' action: open, in_progress, done, failed
62- Status string `json:"status,omitempty" jsonschema_description:"For update action: one of open, in_progress, done, failed"`
61+ // Status is used with 'update' action: open, in_progress, done, failed;
62+ // absent means done (ticket 296).
63+ Status string `json:"status,omitempty" jsonschema_description:"For update: done (the default), failed, in_progress or open"`
6364 // Message is an optional note (e.g., error message for failed status)
6465 Message string `json:"message,omitempty" jsonschema_description:"Optional note for status updates"`
6566 }
@@ -86,29 +87,25 @@ type PlanOutput struct {
8687
8788 // PlanTool declares the `plan` tool.
8889 func PlanTool(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef {
89- description := `Create and manage multi-step plans. When the user gives you a list of tasks to do (e.g., "Do: 1. X, 2. Y, 3. Z"), use this tool to create a plan and track progress.
90+ // Ticket 296: the old example workflow asked for update in_progress,
91+ // work, update done, next, then status — 3 to 4 calls per task. Small
92+ // models spent their calls on it (10 of 40 for one run) and three runs of
93+ // four died on plan bookkeeping, not on the task. One call per finished
94+ // task is enough: mm shows the user the progress itself (progressLine).
95+ description := `Keep a todo list for a task with several steps. Use it only when the work has 3 or more distinct steps.
9096
9197 Actions:
92-- create: Create a new plan with tasks. Required: tasks (array of {description}). Optional: name.
93-- get: Retrieve a plan by name. Required: name.
94-- update: Update a task's status. Required: name, taskId, status (open/in_progress/done/failed). Optional: message.
95-- next: Move to the next task (marks current as done). Required: name.
96-- list: List all plans for this session.
97-- delete: Delete a plan. Required: name.
98-- status: Get a compact status line for display. Required: name.
99-
100-Every action returns a text summary that you should include in your response to the user.
101-
102-Example workflow:
103-1. User says "Do these: 1. Read file, 2. Analyze, 3. Report"
104-2. You call: plan(action="create", tasks=[{description:"Read file"}, {description:"Analyze"}, {description:"Report"}])
105-3. You call: plan(action="update", name="user-request-1", taskId=1, status="in_progress")
106-4. You do the work
107-5. You call: plan(action="update", name="user-request-1", taskId=1, status="done")
108-6. You call: plan(action="next", name="user-request-1")
109-7. Include the status line from plan(action="status") in your response.
110-
111-Always show the user the current plan status using the status action.`
98+- create: make the list. Required: tasks (array of {description}). Optional: name.
99+- update: mark ONE task. Required: taskId, status (done, failed, in_progress or open). Optional: message. Without status, the task is marked done.
100+- get / status / list: read the plans. delete: remove a plan (name).
101+name is optional everywhere but delete: the most recent plan is used.
102+
103+How to use it:
104+1. plan(action="create", tasks=[{description:"Read file"}, {description:"Fix the bug"}, {description:"Run the tests"}])
105+2. Do the work of task 1, then: plan(action="update", taskId=1, status="done")
106+3. Same for each next task: ONE update with status "done" when it is finished. Nothing else is needed — mm shows the user the progress.
107+
108+Do not call plan between the steps of a task, and do not call it again once every task is done: give your answer.`
112109
113110 return genkit.DefineTool(g, "plan",
114111 description,
@@ -58,8 +58,9 @@ type planInput struct {
58 Tasks []PlanTaskInput `json:"tasks,omitempty" jsonschema_description:"For create action: list of tasks to add"`58 Tasks []PlanTaskInput `json:"tasks,omitempty" jsonschema_description:"For create action: list of tasks to add"`
59 // TaskID identifies which task for update/next actions (1-based)59 // TaskID identifies which task for update/next actions (1-based)
60 TaskID int `json:"taskId,omitempty" jsonschema_description:"Task ID (1-based) for update/delete/get actions"`60 TaskID int `json:"taskId,omitempty" jsonschema_description:"Task ID (1-based) for update/delete/get actions"`
61- // Status is used with 'update' action: open, in_progress, done, failed61+ // Status is used with 'update' action: open, in_progress, done, failed;
62- Status string `json:"status,omitempty" jsonschema_description:"For update action: one of open, in_progress, done, failed"`62+ // absent means done (ticket 296).
63+ Status string `json:"status,omitempty" jsonschema_description:"For update: done (the default), failed, in_progress or open"`
63 // Message is an optional note (e.g., error message for failed status)64 // Message is an optional note (e.g., error message for failed status)
64 Message string `json:"message,omitempty" jsonschema_description:"Optional note for status updates"`65 Message string `json:"message,omitempty" jsonschema_description:"Optional note for status updates"`
65 }66 }
@@ -86,29 +87,25 @@ type PlanOutput struct {
86 87
87 // PlanTool declares the `plan` tool.88 // PlanTool declares the `plan` tool.
88 func PlanTool(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef {89 func PlanTool(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef {
89- description := `Create and manage multi-step plans. When the user gives you a list of tasks to do (e.g., "Do: 1. X, 2. Y, 3. Z"), use this tool to create a plan and track progress.90+ // Ticket 296: the old example workflow asked for update in_progress,
91+ // work, update done, next, then status — 3 to 4 calls per task. Small
92+ // models spent their calls on it (10 of 40 for one run) and three runs of
93+ // four died on plan bookkeeping, not on the task. One call per finished
94+ // task is enough: mm shows the user the progress itself (progressLine).
95+ description := `Keep a todo list for a task with several steps. Use it only when the work has 3 or more distinct steps.
90 96
91 Actions:97 Actions:
92-- create: Create a new plan with tasks. Required: tasks (array of {description}). Optional: name.98+- create: make the list. Required: tasks (array of {description}). Optional: name.
93-- get: Retrieve a plan by name. Required: name.99+- update: mark ONE task. Required: taskId, status (done, failed, in_progress or open). Optional: message. Without status, the task is marked done.
94-- update: Update a task's status. Required: name, taskId, status (open/in_progress/done/failed). Optional: message.100+- get / status / list: read the plans. delete: remove a plan (name).
95-- next: Move to the next task (marks current as done). Required: name.101+name is optional everywhere but delete: the most recent plan is used.
96-- list: List all plans for this session.102+
97-- delete: Delete a plan. Required: name.103+How to use it:
98-- status: Get a compact status line for display. Required: name.104+1. plan(action="create", tasks=[{description:"Read file"}, {description:"Fix the bug"}, {description:"Run the tests"}])
99-105+2. Do the work of task 1, then: plan(action="update", taskId=1, status="done")
100-Every action returns a text summary that you should include in your response to the user.106+3. Same for each next task: ONE update with status "done" when it is finished. Nothing else is needed — mm shows the user the progress.
101-107+
102-Example workflow:108+Do not call plan between the steps of a task, and do not call it again once every task is done: give your answer.`
103-1. User says "Do these: 1. Read file, 2. Analyze, 3. Report"
104-2. You call: plan(action="create", tasks=[{description:"Read file"}, {description:"Analyze"}, {description:"Report"}])
105-3. You call: plan(action="update", name="user-request-1", taskId=1, status="in_progress")
106-4. You do the work
107-5. You call: plan(action="update", name="user-request-1", taskId=1, status="done")
108-6. You call: plan(action="next", name="user-request-1")
109-7. Include the status line from plan(action="status") in your response.
110-
111-Always show the user the current plan status using the status action.`
112 109
113 return genkit.DefineTool(g, "plan",110 return genkit.DefineTool(g, "plan",
114 description,111 description,
modified internal/tools/plan_actions.go +17 -1
@@ -70,7 +70,17 @@ func planGet(in planInput) string {
7070 // to the model.
7171 var planStatuses = []string{"open", "in_progress", "done", "failed"}
7272
73+// defaultUpdateStatus is the status of an update that gives none (ticket
74+// 296). Qwen3-Coder-Next sent {"action":"update","taskId":6} five times in a
75+// row after finishing and verifying the work, and the loop detector ended the
76+// turn in error: the call it meant is plain — the task is finished.
77+const defaultUpdateStatus = "done"
78+
7379 func planUpdate(in planInput) string {
80+ defaulted := false
81+ if in.Status == "" && len(in.Tasks) == 0 {
82+ in.Status, defaulted = defaultUpdateStatus, true
83+ }
7484 if !slices.Contains(planStatuses, in.Status) {
7585 return invalidUpdate(in)
7686 }
@@ -78,11 +88,17 @@ func planUpdate(in planInput) string {
7888 if err != nil {
7989 return planError(err)
8090 }
91+ if defaulted {
92+ msg += " (no status given: taken as done)"
93+ }
8194 statusLine, _, _ := planStore.GetStatus(in.Name)
8295 return fmt.Sprintf(`{"result":"%s","status":"%s"}`, msg, statusLine)
8396 }
8497
85-// invalidUpdate answers an `update` without a valid status (ticket 91).
98+// invalidUpdate answers an `update` without a valid status (ticket 91): a
99+// status that is not one of the four, or none with "tasks" — the model was
100+// trying to edit the tasks, and marking one done would be wrong. Without
101+// status nor tasks, the update means done (defaultUpdateStatus).
86102 //
87103 // The store's own message for a missing status — "invalid status" followed by
88104 // an empty quoted value and the four allowed ones — named neither the missing
@@ -70,7 +70,17 @@ func planGet(in planInput) string {
70 // to the model.70 // to the model.
71 var planStatuses = []string{"open", "in_progress", "done", "failed"}71 var planStatuses = []string{"open", "in_progress", "done", "failed"}
72 72
73+// defaultUpdateStatus is the status of an update that gives none (ticket
74+// 296). Qwen3-Coder-Next sent {"action":"update","taskId":6} five times in a
75+// row after finishing and verifying the work, and the loop detector ended the
76+// turn in error: the call it meant is plain — the task is finished.
77+const defaultUpdateStatus = "done"
78+
73 func planUpdate(in planInput) string {79 func planUpdate(in planInput) string {
80+ defaulted := false
81+ if in.Status == "" && len(in.Tasks) == 0 {
82+ in.Status, defaulted = defaultUpdateStatus, true
83+ }
74 if !slices.Contains(planStatuses, in.Status) {84 if !slices.Contains(planStatuses, in.Status) {
75 return invalidUpdate(in)85 return invalidUpdate(in)
76 }86 }
@@ -78,11 +88,17 @@ func planUpdate(in planInput) string {
78 if err != nil {88 if err != nil {
79 return planError(err)89 return planError(err)
80 }90 }
91+ if defaulted {
92+ msg += " (no status given: taken as done)"
93+ }
81 statusLine, _, _ := planStore.GetStatus(in.Name)94 statusLine, _, _ := planStore.GetStatus(in.Name)
82 return fmt.Sprintf(`{"result":"%s","status":"%s"}`, msg, statusLine)95 return fmt.Sprintf(`{"result":"%s","status":"%s"}`, msg, statusLine)
83 }96 }
84 97
85-// invalidUpdate answers an `update` without a valid status (ticket 91).98+// invalidUpdate answers an `update` without a valid status (ticket 91): a
99+// status that is not one of the four, or none with "tasks" — the model was
100+// trying to edit the tasks, and marking one done would be wrong. Without
101+// status nor tasks, the update means done (defaultUpdateStatus).
86 //102 //
87 // The store's own message for a missing status — "invalid status" followed by103 // The store's own message for a missing status — "invalid status" followed by
88 // an empty quoted value and the four allowed ones — named neither the missing104 // an empty quoted value and the four allowed ones — named neither the missing
modified internal/tools/plan_actions_test.go +40 -0
@@ -2,6 +2,7 @@ package tools
22
33 import (
44 "encoding/json"
5+ "os"
56 "strconv"
67 "strings"
78 "testing"
@@ -139,3 +140,42 @@ func TestPlanActionWithoutANameUsesTheLatestPlan(t *testing.T) {
139140 t.Errorf("status without a name: %s", got)
140141 }
141142 }
143+
144+// Ticket 296: Qwen3-Coder-Next sent {"action":"update","taskId":6} five times
145+// after finishing the work. An update with neither status nor tasks marks
146+// the task done, and says so.
147+func TestPlanUpdateWithoutStatusMeansDone(t *testing.T) {
148+ ClearAllPlansForTesting()
149+ runPlanAction(planInput{Action: "create", Name: "p", Tasks: []PlanTaskInput{{Description: "Build"}, {Description: "Test"}}}, true)
150+
151+ got := runPlanAction(planInput{Action: "update", TaskID: 1}, true)
152+ var out PlanOutput
153+ if err := json.Unmarshal([]byte(got), &out); err != nil {
154+ t.Fatalf("update without status is not JSON: %s (%v)", got, err)
155+ }
156+ if !strings.Contains(out.Result, "Task 1 in plan 'p' updated to 'done' (no status given: taken as done)") {
157+ t.Errorf("update without status: %s", got)
158+ }
159+ // The same call again is not an error either: the task stays done.
160+ if again := runPlanAction(planInput{Action: "update", TaskID: 1}, true); planFailed(again) {
161+ t.Errorf("repeated update without status: %s", again)
162+ }
163+}
164+
165+// The plan tool's description asks for one update per finished task, and no
166+// longer for the in_progress / next / status ritual.
167+func TestPlanDescriptionAsksForOneUpdatePerTask(t *testing.T) {
168+ src, err := os.ReadFile("plan.go")
169+ if err != nil {
170+ t.Fatal(err)
171+ }
172+ text := string(src)
173+ for _, gone := range []string{`status="in_progress")`, `plan(action="next"`, "Always show the user the current plan status"} {
174+ if strings.Contains(text, gone) {
175+ t.Errorf("the description still says %s", gone)
176+ }
177+ }
178+ if !strings.Contains(text, `ONE update with status "done" when it is finished`) {
179+ t.Error("the description does not ask for one update done per task")
180+ }
181+}
@@ -2,6 +2,7 @@ package tools
2 2
3 import (3 import (
4 "encoding/json"4 "encoding/json"
5+ "os"
5 "strconv"6 "strconv"
6 "strings"7 "strings"
7 "testing"8 "testing"
@@ -139,3 +140,42 @@ func TestPlanActionWithoutANameUsesTheLatestPlan(t *testing.T) {
139 t.Errorf("status without a name: %s", got)140 t.Errorf("status without a name: %s", got)
140 }141 }
141 }142 }
143+
144+// Ticket 296: Qwen3-Coder-Next sent {"action":"update","taskId":6} five times
145+// after finishing the work. An update with neither status nor tasks marks
146+// the task done, and says so.
147+func TestPlanUpdateWithoutStatusMeansDone(t *testing.T) {
148+ ClearAllPlansForTesting()
149+ runPlanAction(planInput{Action: "create", Name: "p", Tasks: []PlanTaskInput{{Description: "Build"}, {Description: "Test"}}}, true)
150+
151+ got := runPlanAction(planInput{Action: "update", TaskID: 1}, true)
152+ var out PlanOutput
153+ if err := json.Unmarshal([]byte(got), &out); err != nil {
154+ t.Fatalf("update without status is not JSON: %s (%v)", got, err)
155+ }
156+ if !strings.Contains(out.Result, "Task 1 in plan 'p' updated to 'done' (no status given: taken as done)") {
157+ t.Errorf("update without status: %s", got)
158+ }
159+ // The same call again is not an error either: the task stays done.
160+ if again := runPlanAction(planInput{Action: "update", TaskID: 1}, true); planFailed(again) {
161+ t.Errorf("repeated update without status: %s", again)
162+ }
163+}
164+
165+// The plan tool's description asks for one update per finished task, and no
166+// longer for the in_progress / next / status ritual.
167+func TestPlanDescriptionAsksForOneUpdatePerTask(t *testing.T) {
168+ src, err := os.ReadFile("plan.go")
169+ if err != nil {
170+ t.Fatal(err)
171+ }
172+ text := string(src)
173+ for _, gone := range []string{`status="in_progress")`, `plan(action="next"`, "Always show the user the current plan status"} {
174+ if strings.Contains(text, gone) {
175+ t.Errorf("the description still says %s", gone)
176+ }
177+ }
178+ if !strings.Contains(text, `ONE update with status "done" when it is finished`) {
179+ t.Error("the description does not ask for one update done per task")
180+ }
181+}
added internal/tools/readcircle.go +100 -0
new file mode 100644
@@ -0,0 +1,100 @@
1+package tools
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "os"
7+ "regexp"
8+ "strconv"
9+ "strings"
10+
11+ "mm/internal/fileedit"
12+ "mm/internal/ui"
13+)
14+
15+// A broken file read in circles (ticket 307).
16+//
17+// Seen 2026-12-04 with Mellum2.1 Thinking: the model wrote main.go with one
18+// `}` too many, the diagnostics said `main.go:142:1 expected declaration,
19+// found '}'`, its reasoning said "remove the extra brace at line 142" — and
20+// then it read main.go eight times, in different ranges, and never edited:
21+// `}` is not unique as an edit_file old text, and it did not think of the
22+// `line` argument. The loop detector sees successful reads with different
23+// arguments; the re-read rule (ticket 292) acts only after a compression;
24+// the recall of ticket 295 said "still 1 error(s)", true but not what to do.
25+//
26+// So from the nudgeFromRecall-th read of a version of a file that still has
27+// errors, the recall is followed by a note that says it plainly: the error
28+// has not moved, here is its line as the file has it, here is the edit_file
29+// call — with `line`, so a short old text is enough. The count starts again
30+// when the file changes (a new version is diagnosed again).
31+
32+// nudgeFromRecall is the recall from which the note is added: the first
33+// recall can be a model checking its work; the second is a circle.
34+const nudgeFromRecall = 2
35+
36+// errorPosition reads "error main.go:142:1 …": the line number.
37+var errorPosition = regexp.MustCompile(`^error \S+?:(\d+):\d+ `)
38+
39+// fixNudge is the note that follows the recall of errs on the recalls-th
40+// read of path's unchanged version; "" before nudgeFromRecall or without
41+// errors. It also tells the user (🔁).
42+//
43+// fixNudge("main.go", []string{"error main.go:142:1 expected declaration, found '}' [syntax]"}, 2)
44+// // "\n[mm: you have read main.go 2 times since it last changed … Line 142 reads: \"}\" … {\"path\":\"main.go\",\"edits\":[{\"old\":\"}\",\"new\":\"}\",\"line\":142}]} …]"
45+func fixNudge(path string, errs []string, recalls int) string {
46+ if len(errs) == 0 || recalls < nudgeFromRecall {
47+ return ""
48+ }
49+ ui.Notice(fmt.Sprintf("🔁 %s read %d times with the same error — mm points the model at the line to fix", path, recalls))
50+ note := fmt.Sprintf("\n[mm: you have read %s %d times since it last changed, and the error has not moved: reading it again will not fix it. Change the file now.", path, recalls)
51+ return note + fixHint(path, errs[0]) + "]"
52+}
53+
54+// fixHint is the part of the note naming the first error's line and the
55+// edit_file call that changes it; a plain pointer when the line cannot be
56+// read or is blank.
57+func fixHint(path, firstError string) string {
58+ m := errorPosition.FindStringSubmatch(firstError)
59+ if m == nil {
60+ return " Edit the lines the error names."
61+ }
62+ line, _ := strconv.Atoi(m[1])
63+ text, ok := sourceLine(path, line)
64+ if !ok || strings.TrimSpace(text) == "" {
65+ return fmt.Sprintf(" The error is at line %d: edit it with edit_file and \"line\": %d.", line, line)
66+ }
67+ old := strings.TrimSpace(text)
68+ return fmt.Sprintf(" Line %d reads: %q. edit_file takes the line number, so this short old text is enough even if it appears elsewhere in the file: %s — replace \"new\" with the corrected text (\"\" deletes it). Fix the cause the error names: an import the build cannot find is fixed in go.mod (go get, go mod tidy), not by deleting the import.",
69+ line, old, editCall(path, old, line))
70+}
71+
72+// editCall is the edit_file arguments for the text old at line, with new
73+// equal to old: the model writes the correction in new. Never a ready
74+// deletion — seen 2026-12-05, the error "could not import gopkg.in/yaml.v3"
75+// would have made it `"new": ""` on the import line. Copied as it is, the
76+// call changes nothing and says so. HTML characters stay as they are
77+// (`&labels`, not \u0026).
78+func editCall(path, old string, line int) string {
79+ var b strings.Builder
80+ enc := json.NewEncoder(&b)
81+ enc.SetEscapeHTML(false)
82+ _ = enc.Encode(struct {
83+ Path string `json:"path"`
84+ Edits []fileedit.Edit `json:"edits"`
85+ }{path, []fileedit.Edit{{Old: old, New: old, Line: line}}})
86+ return strings.TrimSpace(b.String())
87+}
88+
89+// sourceLine is the 1-based line n of the file at path, without its end.
90+func sourceLine(path string, n int) (string, bool) {
91+ data, err := os.ReadFile(path)
92+ if err != nil {
93+ return "", false
94+ }
95+ lines := strings.Split(string(data), "\n")
96+ if n < 1 || n > len(lines) {
97+ return "", false
98+ }
99+ return strings.TrimSuffix(lines[n-1], "\r"), true
100+}
new file mode 100644
@@ -0,0 +1,100 @@
1+package tools
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "os"
7+ "regexp"
8+ "strconv"
9+ "strings"
10+
11+ "mm/internal/fileedit"
12+ "mm/internal/ui"
13+)
14+
15+// A broken file read in circles (ticket 307).
16+//
17+// Seen 2026-12-04 with Mellum2.1 Thinking: the model wrote main.go with one
18+// `}` too many, the diagnostics said `main.go:142:1 expected declaration,
19+// found '}'`, its reasoning said "remove the extra brace at line 142" — and
20+// then it read main.go eight times, in different ranges, and never edited:
21+// `}` is not unique as an edit_file old text, and it did not think of the
22+// `line` argument. The loop detector sees successful reads with different
23+// arguments; the re-read rule (ticket 292) acts only after a compression;
24+// the recall of ticket 295 said "still 1 error(s)", true but not what to do.
25+//
26+// So from the nudgeFromRecall-th read of a version of a file that still has
27+// errors, the recall is followed by a note that says it plainly: the error
28+// has not moved, here is its line as the file has it, here is the edit_file
29+// call — with `line`, so a short old text is enough. The count starts again
30+// when the file changes (a new version is diagnosed again).
31+
32+// nudgeFromRecall is the recall from which the note is added: the first
33+// recall can be a model checking its work; the second is a circle.
34+const nudgeFromRecall = 2
35+
36+// errorPosition reads "error main.go:142:1 …": the line number.
37+var errorPosition = regexp.MustCompile(`^error \S+?:(\d+):\d+ `)
38+
39+// fixNudge is the note that follows the recall of errs on the recalls-th
40+// read of path's unchanged version; "" before nudgeFromRecall or without
41+// errors. It also tells the user (🔁).
42+//
43+// fixNudge("main.go", []string{"error main.go:142:1 expected declaration, found '}' [syntax]"}, 2)
44+// // "\n[mm: you have read main.go 2 times since it last changed … Line 142 reads: \"}\" … {\"path\":\"main.go\",\"edits\":[{\"old\":\"}\",\"new\":\"}\",\"line\":142}]} …]"
45+func fixNudge(path string, errs []string, recalls int) string {
46+ if len(errs) == 0 || recalls < nudgeFromRecall {
47+ return ""
48+ }
49+ ui.Notice(fmt.Sprintf("🔁 %s read %d times with the same error — mm points the model at the line to fix", path, recalls))
50+ note := fmt.Sprintf("\n[mm: you have read %s %d times since it last changed, and the error has not moved: reading it again will not fix it. Change the file now.", path, recalls)
51+ return note + fixHint(path, errs[0]) + "]"
52+}
53+
54+// fixHint is the part of the note naming the first error's line and the
55+// edit_file call that changes it; a plain pointer when the line cannot be
56+// read or is blank.
57+func fixHint(path, firstError string) string {
58+ m := errorPosition.FindStringSubmatch(firstError)
59+ if m == nil {
60+ return " Edit the lines the error names."
61+ }
62+ line, _ := strconv.Atoi(m[1])
63+ text, ok := sourceLine(path, line)
64+ if !ok || strings.TrimSpace(text) == "" {
65+ return fmt.Sprintf(" The error is at line %d: edit it with edit_file and \"line\": %d.", line, line)
66+ }
67+ old := strings.TrimSpace(text)
68+ return fmt.Sprintf(" Line %d reads: %q. edit_file takes the line number, so this short old text is enough even if it appears elsewhere in the file: %s — replace \"new\" with the corrected text (\"\" deletes it). Fix the cause the error names: an import the build cannot find is fixed in go.mod (go get, go mod tidy), not by deleting the import.",
69+ line, old, editCall(path, old, line))
70+}
71+
72+// editCall is the edit_file arguments for the text old at line, with new
73+// equal to old: the model writes the correction in new. Never a ready
74+// deletion — seen 2026-12-05, the error "could not import gopkg.in/yaml.v3"
75+// would have made it `"new": ""` on the import line. Copied as it is, the
76+// call changes nothing and says so. HTML characters stay as they are
77+// (`&labels`, not \u0026).
78+func editCall(path, old string, line int) string {
79+ var b strings.Builder
80+ enc := json.NewEncoder(&b)
81+ enc.SetEscapeHTML(false)
82+ _ = enc.Encode(struct {
83+ Path string `json:"path"`
84+ Edits []fileedit.Edit `json:"edits"`
85+ }{path, []fileedit.Edit{{Old: old, New: old, Line: line}}})
86+ return strings.TrimSpace(b.String())
87+}
88+
89+// sourceLine is the 1-based line n of the file at path, without its end.
90+func sourceLine(path string, n int) (string, bool) {
91+ data, err := os.ReadFile(path)
92+ if err != nil {
93+ return "", false
94+ }
95+ lines := strings.Split(string(data), "\n")
96+ if n < 1 || n > len(lines) {
97+ return "", false
98+ }
99+ return strings.TrimSuffix(lines[n-1], "\r"), true
100+}
added internal/tools/readcircle_test.go +108 -0
new file mode 100644
@@ -0,0 +1,108 @@
1+package tools
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "os"
7+ "strings"
8+ "testing"
9+ "time"
10+
11+ "mm/internal/fileedit"
12+)
13+
14+// extraBrace is the main.go of the 2026-12-04 run, shortened: one `}` too many.
15+const extraBrace = "package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n}\n"
16+
17+// braceLSP answers what gopls said about extraBrace.
18+type braceLSP struct{ cannedLSP }
19+
20+func (braceLSP) Diagnostics(context.Context, string) (string, error) {
21+ return "1 diagnostic(s) in main.go:\nerror main.go:6:1 expected declaration, found '}' [syntax]", nil
22+}
23+
24+// Ticket 307: the first recall is only the recall; from the second, the
25+// note names the line and gives an edit_file call that fixes it.
26+func TestReadingABrokenFileInCirclesPointsAtTheFix(t *testing.T) {
27+ withReadDiagnostics(t, true, braceLSP{})
28+ path := writeTemp(t, "main.go", extraBrace)
29+ diagnosticsAfterRead(path) // the diagnostics
30+ if note := diagnosticsAfterRead(path); strings.Contains(note, "[mm:") {
31+ t.Fatalf("first recall carries the note: %q", note)
32+ }
33+ note := diagnosticsAfterRead(path)
34+ for _, want := range []string{"still 1 error(s)", "read " + path + " 2 times", `Line 6 reads: "}"`, `"line":6`} {
35+ if !strings.Contains(note, want) {
36+ t.Errorf("second recall: %q lacks %q", note, want)
37+ }
38+ }
39+ if !strings.Contains(diagnosticsAfterRead(path), "3 times") {
40+ t.Error("third recall: no count of 3")
41+ }
42+}
43+
44+// The call in the note works as it is: `}` appears twice, line picks one.
45+func TestTheSuggestedEditFixesTheFile(t *testing.T) {
46+ path := writeTemp(t, "main.go", extraBrace)
47+ var call struct {
48+ Path string `json:"path"`
49+ Edits []fileedit.Edit `json:"edits"`
50+ }
51+ if err := json.Unmarshal([]byte(editCall(path, "}", 6)), &call); err != nil {
52+ t.Fatal(err)
53+ }
54+ if call.Edits[0].New != "}" {
55+ t.Fatalf("suggested new = %q, want the old text (never a ready deletion)", call.Edits[0].New)
56+ }
57+ call.Edits[0].New = "" // what the model writes for an extra brace
58+ if _, err := fileedit.Replace(call.Path, call.Edits, false); err != nil {
59+ t.Fatalf("edit refused: %v", err)
60+ }
61+ got, _ := os.ReadFile(path)
62+ if want := "package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n\n"; string(got) != want {
63+ t.Errorf("file = %q, want %q", got, want)
64+ }
65+}
66+
67+// A changed file is a new version: the count starts again.
68+func TestTheCountStartsAgainWhenTheFileChanges(t *testing.T) {
69+ withReadDiagnostics(t, true, braceLSP{})
70+ path := writeTemp(t, "main.go", extraBrace)
71+ diagnosticsAfterRead(path)
72+ diagnosticsAfterRead(path)
73+ later := time.Now().Add(time.Second)
74+ if err := os.WriteFile(path, []byte(extraBrace+"\n"), 0o644); err != nil {
75+ t.Fatal(err)
76+ }
77+ _ = os.Chtimes(path, later, later)
78+ diagnosticsAfterRead(path) // the new version is diagnosed
79+ if note := diagnosticsAfterRead(path); strings.Contains(note, "[mm:") {
80+ t.Errorf("first recall of the new version carries the note: %q", note)
81+ }
82+}
83+
84+// A clean file is never counted.
85+func TestNoNoteForACleanFile(t *testing.T) {
86+ withReadDiagnostics(t, true, cannedLSP{})
87+ path := writeTemp(t, "main.go", "package main\n")
88+ for range 4 {
89+ if note := diagnosticsAfterRead(path); strings.Contains(note, "[mm:") {
90+ t.Fatalf("clean file: %q", note)
91+ }
92+ }
93+}
94+
95+func TestFixHint(t *testing.T) {
96+ path := writeTemp(t, "a.go", "package a\n\n\tx := y\n")
97+ cases := []struct{ err, want string }{
98+ {"error a.go:3:2 undefined: y [compiler]", `Line 3 reads: "x := y"`},
99+ {"error a.go:2:1 something [syntax]", "The error is at line 2"},
100+ {"error a.go:99:1 something [syntax]", "The error is at line 99"},
101+ {"error something odd", "Edit the lines the error names."},
102+ }
103+ for _, c := range cases {
104+ if got := fixHint(path, c.err); !strings.Contains(got, c.want) {
105+ t.Errorf("fixHint(%q) = %q, want %q in it", c.err, got, c.want)
106+ }
107+ }
108+}
new file mode 100644
@@ -0,0 +1,108 @@
1+package tools
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "os"
7+ "strings"
8+ "testing"
9+ "time"
10+
11+ "mm/internal/fileedit"
12+)
13+
14+// extraBrace is the main.go of the 2026-12-04 run, shortened: one `}` too many.
15+const extraBrace = "package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n}\n"
16+
17+// braceLSP answers what gopls said about extraBrace.
18+type braceLSP struct{ cannedLSP }
19+
20+func (braceLSP) Diagnostics(context.Context, string) (string, error) {
21+ return "1 diagnostic(s) in main.go:\nerror main.go:6:1 expected declaration, found '}' [syntax]", nil
22+}
23+
24+// Ticket 307: the first recall is only the recall; from the second, the
25+// note names the line and gives an edit_file call that fixes it.
26+func TestReadingABrokenFileInCirclesPointsAtTheFix(t *testing.T) {
27+ withReadDiagnostics(t, true, braceLSP{})
28+ path := writeTemp(t, "main.go", extraBrace)
29+ diagnosticsAfterRead(path) // the diagnostics
30+ if note := diagnosticsAfterRead(path); strings.Contains(note, "[mm:") {
31+ t.Fatalf("first recall carries the note: %q", note)
32+ }
33+ note := diagnosticsAfterRead(path)
34+ for _, want := range []string{"still 1 error(s)", "read " + path + " 2 times", `Line 6 reads: "}"`, `"line":6`} {
35+ if !strings.Contains(note, want) {
36+ t.Errorf("second recall: %q lacks %q", note, want)
37+ }
38+ }
39+ if !strings.Contains(diagnosticsAfterRead(path), "3 times") {
40+ t.Error("third recall: no count of 3")
41+ }
42+}
43+
44+// The call in the note works as it is: `}` appears twice, line picks one.
45+func TestTheSuggestedEditFixesTheFile(t *testing.T) {
46+ path := writeTemp(t, "main.go", extraBrace)
47+ var call struct {
48+ Path string `json:"path"`
49+ Edits []fileedit.Edit `json:"edits"`
50+ }
51+ if err := json.Unmarshal([]byte(editCall(path, "}", 6)), &call); err != nil {
52+ t.Fatal(err)
53+ }
54+ if call.Edits[0].New != "}" {
55+ t.Fatalf("suggested new = %q, want the old text (never a ready deletion)", call.Edits[0].New)
56+ }
57+ call.Edits[0].New = "" // what the model writes for an extra brace
58+ if _, err := fileedit.Replace(call.Path, call.Edits, false); err != nil {
59+ t.Fatalf("edit refused: %v", err)
60+ }
61+ got, _ := os.ReadFile(path)
62+ if want := "package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n\n"; string(got) != want {
63+ t.Errorf("file = %q, want %q", got, want)
64+ }
65+}
66+
67+// A changed file is a new version: the count starts again.
68+func TestTheCountStartsAgainWhenTheFileChanges(t *testing.T) {
69+ withReadDiagnostics(t, true, braceLSP{})
70+ path := writeTemp(t, "main.go", extraBrace)
71+ diagnosticsAfterRead(path)
72+ diagnosticsAfterRead(path)
73+ later := time.Now().Add(time.Second)
74+ if err := os.WriteFile(path, []byte(extraBrace+"\n"), 0o644); err != nil {
75+ t.Fatal(err)
76+ }
77+ _ = os.Chtimes(path, later, later)
78+ diagnosticsAfterRead(path) // the new version is diagnosed
79+ if note := diagnosticsAfterRead(path); strings.Contains(note, "[mm:") {
80+ t.Errorf("first recall of the new version carries the note: %q", note)
81+ }
82+}
83+
84+// A clean file is never counted.
85+func TestNoNoteForACleanFile(t *testing.T) {
86+ withReadDiagnostics(t, true, cannedLSP{})
87+ path := writeTemp(t, "main.go", "package main\n")
88+ for range 4 {
89+ if note := diagnosticsAfterRead(path); strings.Contains(note, "[mm:") {
90+ t.Fatalf("clean file: %q", note)
91+ }
92+ }
93+}
94+
95+func TestFixHint(t *testing.T) {
96+ path := writeTemp(t, "a.go", "package a\n\n\tx := y\n")
97+ cases := []struct{ err, want string }{
98+ {"error a.go:3:2 undefined: y [compiler]", `Line 3 reads: "x := y"`},
99+ {"error a.go:2:1 something [syntax]", "The error is at line 2"},
100+ {"error a.go:99:1 something [syntax]", "The error is at line 99"},
101+ {"error something odd", "Edit the lines the error names."},
102+ }
103+ for _, c := range cases {
104+ if got := fixHint(path, c.err); !strings.Contains(got, c.want) {
105+ t.Errorf("fixHint(%q) = %q, want %q in it", c.err, got, c.want)
106+ }
107+ }
108+}
modified internal/tools/readdiag_test.go +26 -0
@@ -93,6 +93,32 @@ func TestDiagnosticsAfterReadOncePerVersion(t *testing.T) {
9393 }
9494 }
9595
96+// Ticket 308: main.go unchanged, but its go.mod changed behind mm's back (a
97+// bash `go get`): the next read asks the server again instead of recalling
98+// diagnostics that may be gone.
99+func TestDiagnosticsAfterReadAskAgainWhenGoModChanged(t *testing.T) {
100+ calls := 0
101+ withReadDiagnostics(t, true, countingLSP{calls: &calls})
102+ path := writeTemp(t, "main.go", "package main\n")
103+ gomod := filepath.Join(filepath.Dir(path), "go.mod")
104+ if err := os.WriteFile(gomod, []byte("module app\n"), 0o644); err != nil {
105+ t.Fatal(err)
106+ }
107+ diagnosticsAfterRead(path)
108+ diagnosticsAfterRead(path)
109+ if calls != 1 {
110+ t.Fatalf("unchanged file and go.mod: calls = %d, want 1", calls)
111+ }
112+ later := time.Now().Add(2 * time.Second)
113+ if err := os.WriteFile(gomod, []byte("module app\n\nrequire gopkg.in/yaml.v3 v3.0.1\n"), 0o644); err != nil {
114+ t.Fatal(err)
115+ }
116+ _ = os.Chtimes(gomod, later, later)
117+ if note := diagnosticsAfterRead(path); note == "" || calls != 2 {
118+ t.Errorf("after go.mod changed: note = %q, calls = %d; want the diagnostics, 2", note, calls)
119+ }
120+}
121+
96122 // A read right after an edit that already brought the diagnostics does not
97123 // repeat them.
98124 func TestNoDiagnosticsAfterReadOfAnEditedFile(t *testing.T) {
@@ -93,6 +93,32 @@ func TestDiagnosticsAfterReadOncePerVersion(t *testing.T) {
93 }93 }
94 }94 }
95 95
96+// Ticket 308: main.go unchanged, but its go.mod changed behind mm's back (a
97+// bash `go get`): the next read asks the server again instead of recalling
98+// diagnostics that may be gone.
99+func TestDiagnosticsAfterReadAskAgainWhenGoModChanged(t *testing.T) {
100+ calls := 0
101+ withReadDiagnostics(t, true, countingLSP{calls: &calls})
102+ path := writeTemp(t, "main.go", "package main\n")
103+ gomod := filepath.Join(filepath.Dir(path), "go.mod")
104+ if err := os.WriteFile(gomod, []byte("module app\n"), 0o644); err != nil {
105+ t.Fatal(err)
106+ }
107+ diagnosticsAfterRead(path)
108+ diagnosticsAfterRead(path)
109+ if calls != 1 {
110+ t.Fatalf("unchanged file and go.mod: calls = %d, want 1", calls)
111+ }
112+ later := time.Now().Add(2 * time.Second)
113+ if err := os.WriteFile(gomod, []byte("module app\n\nrequire gopkg.in/yaml.v3 v3.0.1\n"), 0o644); err != nil {
114+ t.Fatal(err)
115+ }
116+ _ = os.Chtimes(gomod, later, later)
117+ if note := diagnosticsAfterRead(path); note == "" || calls != 2 {
118+ t.Errorf("after go.mod changed: note = %q, calls = %d; want the diagnostics, 2", note, calls)
119+ }
120+}
121+
96 // A read right after an edit that already brought the diagnostics does not122 // A read right after an edit that already brought the diagnostics does not
97 // repeat them.123 // repeat them.
98 func TestNoDiagnosticsAfterReadOfAnEditedFile(t *testing.T) {124 func TestNoDiagnosticsAfterReadOfAnEditedFile(t *testing.T) {
modified internal/tools/tools.go +2 -2
@@ -267,7 +267,7 @@ Read before you write: if you do not know a path or the content of a file, run a
267267 // twice in a row, and it hands the model back an instruction to
268268 // change its approach; ignored for too long, it ends the turn
269269 // (see internal/detector and record).
270- return recordOutcome(d, "bash", in.Command, cdNote+out, failed)
270+ return recordBash(d, in.Command, cdNote+out, failed)
271271 })
272272 }
273273
@@ -305,7 +305,7 @@ func bashEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in ba
305305 out, failed := runBash(ctx, s.WorkDir(), in.Command)
306306 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed})
307307
308- return recordOutcome(d, "bash", in.Command, out, failed)
308+ return recordBash(d, in.Command, out, failed)
309309 }
310310
311311 // --- read_skill --------------------------------------------------------------
@@ -267,7 +267,7 @@ Read before you write: if you do not know a path or the content of a file, run a
267 // twice in a row, and it hands the model back an instruction to267 // twice in a row, and it hands the model back an instruction to
268 // change its approach; ignored for too long, it ends the turn268 // change its approach; ignored for too long, it ends the turn
269 // (see internal/detector and record).269 // (see internal/detector and record).
270- return recordOutcome(d, "bash", in.Command, cdNote+out, failed)270+ return recordBash(d, in.Command, cdNote+out, failed)
271 })271 })
272 }272 }
273 273
@@ -305,7 +305,7 @@ func bashEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in ba
305 out, failed := runBash(ctx, s.WorkDir(), in.Command)305 out, failed := runBash(ctx, s.WorkDir(), in.Command)
306 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed})306 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed})
307 307
308- return recordOutcome(d, "bash", in.Command, out, failed)308+ return recordBash(d, in.Command, out, failed)
309 }309 }
310 310
311 // --- read_skill --------------------------------------------------------------311 // --- read_skill --------------------------------------------------------------
modified main.go +1 -1
@@ -158,7 +158,7 @@ func startEngine(ctx context.Context, acpMode bool, asker *ask.Pool) *engine.Eng
158158 // Every flagged repeat is also shown to the user (ticket 153), and so is a
159159 // run of three failed calls or more with different inputs (ticket 160).
160160 func newLoopDetector() *detector.LoopDetector {
161- return detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithReport(reportLoop)
161+ return detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithSimilar(3).WithReport(reportLoop)
162162 }
163163
164164 // agentSession is what every front end runs on: the engine, the tools, the loop
@@ -158,7 +158,7 @@ func startEngine(ctx context.Context, acpMode bool, asker *ask.Pool) *engine.Eng
158 // Every flagged repeat is also shown to the user (ticket 153), and so is a158 // Every flagged repeat is also shown to the user (ticket 153), and so is a
159 // run of three failed calls or more with different inputs (ticket 160).159 // run of three failed calls or more with different inputs (ticket 160).
160 func newLoopDetector() *detector.LoopDetector {160 func newLoopDetector() *detector.LoopDetector {
161- return detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithReport(reportLoop)161+ return detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithSimilar(3).WithReport(reportLoop)
162 }162 }
163 163
164 // agentSession is what every front end runs on: the engine, the tools, the loop164 // agentSession is what every front end runs on: the engine, the tools, the loop
added sbxenv.sonnet.yaml +27 -0
new file mode 100644
@@ -0,0 +1,27 @@
1+schemaVersion: "1"
2+
3+name: mini-me
4+
5+agent: claude
6+
7+# Primary workspace: this folder (relative paths resolve against this file).
8+workspace: .
9+
10+additionalWorkspaces:
11+ #- path: /Users/k33g/Documents
12+ - path: /Users/k33g/kDrive/Rickub/bots-garden/mini-me-kit
13+ #- path: /Users/k33g/kDrive/Rickub/bots-garden/pov-ray-go
14+ - path: /Users/k33g/kDrive/Rickub/bots-garden/razorbill
15+
16+kits:
17+ - docker.io/k33g/go-toolchain-kit:0.2.0
18+ #- docker.io/k33g/python-toolchain-kit:0.1.6
19+
20+env:
21+ # Claude Code default model
22+ #ANTHROPIC_MODEL: claude-opus-5-5
23+ ANTHROPIC_MODEL: claude-sonnet-5-5
24+
25+# sbx env create # shows the plan and asks for confirmation (--force to skip)
26+# sbx env run # re-attach (creates the sandbox first if it does not exist)
27+# sbx env rm # delete the sandbox
new file mode 100644
@@ -0,0 +1,27 @@
1+schemaVersion: "1"
2+
3+name: mini-me
4+
5+agent: claude
6+
7+# Primary workspace: this folder (relative paths resolve against this file).
8+workspace: .
9+
10+additionalWorkspaces:
11+ #- path: /Users/k33g/Documents
12+ - path: /Users/k33g/kDrive/Rickub/bots-garden/mini-me-kit
13+ #- path: /Users/k33g/kDrive/Rickub/bots-garden/pov-ray-go
14+ - path: /Users/k33g/kDrive/Rickub/bots-garden/razorbill
15+
16+kits:
17+ - docker.io/k33g/go-toolchain-kit:0.2.0
18+ #- docker.io/k33g/python-toolchain-kit:0.1.6
19+
20+env:
21+ # Claude Code default model
22+ #ANTHROPIC_MODEL: claude-opus-5-5
23+ ANTHROPIC_MODEL: claude-sonnet-5-5
24+
25+# sbx env create # shows the plan and asks for confirmation (--force to skip)
26+# sbx env run # re-attach (creates the sandbox first if it does not exist)
27+# sbx env rm # delete the sandbox
modified sbxenv.yaml +1 -0
@@ -20,6 +20,7 @@ kits:
2020 env:
2121 # Claude Code default model
2222 ANTHROPIC_MODEL: claude-opus-5-5
23+ #ANTHROPIC_MODEL: claude-sonnet-5-5
2324
2425 # sbx env create # shows the plan and asks for confirmation (--force to skip)
2526 # sbx env run # re-attach (creates the sandbox first if it does not exist)
@@ -20,6 +20,7 @@ kits:
20 env:20 env:
21 # Claude Code default model21 # Claude Code default model
22 ANTHROPIC_MODEL: claude-opus-5-522 ANTHROPIC_MODEL: claude-opus-5-5
23+ #ANTHROPIC_MODEL: claude-sonnet-5-5
23 24
24 # sbx env create # shows the plan and asks for confirmation (--force to skip)25 # sbx env create # shows the plan and asks for confirmation (--force to skip)
25 # sbx env run # re-attach (creates the sandbox first if it does not exist)26 # sbx env run # re-attach (creates the sandbox first if it does not exist)
modified skills/plan-manager/SKILL.md +46 -439
@@ -1,472 +1,79 @@
11 ---
22 name: plan-manager
3-description: Manage multi-step work as a plan. When the user gives you a list of tasks to do, or you decide to break work into steps, use the plan tool to create and track a todo list. This ensures the user can see your progress and you don't lose track of what remains to be done.
3+description: Manage multi-step work as a plan. When the user gives you a list of tasks to do, or the work has 3 or more distinct steps, use the plan tool to keep a todo list — one create, then one update per finished task. mm shows the user the progress.
44 keywords: plan, todo, tasks, steps, first, second, third, then, after that, next, do this, do these, i need, i want, following, steps are, task list, to do
55 ---
66 # Plan Manager
77
8-## What This Skill Does
8+## What this skill does
99
10-This skill teaches you how to **detect, create, and manage plans** when users give you multi-step requests.
10+It tells you **when** to keep a plan and **how few calls** it takes. A plan is a todo list kept by the `plan` tool. mm shows the user where the plan is after every plan call: you do not have to report it.
1111
12-A **plan** is a structured way to track progress through multiple tasks. When you create a plan, you:
13-1. Store the list of tasks the user wants done
14-2. Track which task you're currently working on
15-3. Update the status of each task as you complete it
16-4. Report progress to the user with clear status messages
12+## When to make a plan
1713
18-## When to Use This Skill
14+Make a plan when:
1915
20-**ALWAYS** create and use a plan when:
16+- the user gives a numbered list: "1. Fix A, 2. Update B, 3. Test C";
17+- the user lists several actions: "fix A, then update B, and finally test C";
18+- the user says "here's my plan", "do these things";
19+- the work has **3 or more distinct steps**.
2120
22-1. **User gives you a numbered list:**
23- - "Do these 3 things: 1. X, 2. Y, 3. Z"
24- - "Please: 1. First, 2. Second, 3. Third"
25- - "My plan is: 1. Step one, 2. Step two"
21+Do **not** make a plan for:
2622
27-2. **User gives you a comma-separated or bullet list of actions:**
28- - "I need you to fix A, then update B, and finally test C"
29- - "Please handle: - A, - B, - C"
23+- a single request ("write a function that sorts an array") — just do it;
24+- a question, a greeting, a conversation.
3025
31-3. **User explicitly says they have a plan:**
32- - "Here's my plan: ..."
33- - "My plan is to..."
34- - "I want to do X, Y, and Z"
26+## How to use it: one create, one update per task
3527
36-4. **You decide to break complex work into steps:**
37- - When a single request requires multiple distinct actions
38- - When you need to track progress for a multi-part task
28+1. Create the list, one task per thing the user asked for (do not invent tasks):
3929
40-**NEVER** use the plan tool for:
41-- Single, simple requests (just do it directly)
42-- Conversational questions with no action required
43-- Greetings or social interactions
44-- Requests that don't involve doing something
45-
46-## The Plan Tool
47-
48-The `plan` tool is a builtin tool available to you. It supports these **actions**:
49-
50-### Action: create
51-
52-**Purpose:** Create a new plan with a list of tasks.
53-
54-**Required parameters:**
55-- `tasks`: Array of task objects, each with `description` (string)
56-
57-**Optional parameters:**
58-- `name`: Plan name (string). If not provided, auto-generated as "user-request-N"
59-
60-**Example:**
61-```json
62-{
63- "action": "create",
64- "name": "setup-project",
65- "tasks": [
66- {"description": "Initialize the repository"},
67- {"description": "Create the main file"},
68- {"description": "Add configuration"}
69- ]
70-}
71-```
72-
73-**What happens:**
74-- A new plan is created with the given tasks
75-- Each task gets an auto-incrementing ID (1, 2, 3...)
76-- All tasks start with status "open"
77-- The plan is stored for this session
78-
79-**What you should do:**
80-- Call `plan` with `action: "create"` as soon as you detect a multi-step request
81-- Then immediately call `plan` with `action: "update"` to mark the first task as "in_progress"
82-- Tell the user: "I'll handle this in N steps. Starting with: [first task description]"
83-
84----
85-
86-### Action: update
87-
88-**Purpose:** Update the status of a specific task.
89-
90-**Required parameters:**
91-- `name`: Plan name
92-- `taskId`: The task ID to update (1-based)
93-- `status`: New status. One of: `open`, `in_progress`, `done`, `failed`
94-
95-**Optional parameters:**
96-- `message`: A note about this status change (e.g., error message for failed)
97-
98-**Example:**
99-```json
100-{
101- "action": "update",
102- "name": "setup-project",
103- "taskId": 1,
104- "status": "in_progress"
105-}
106-```
107-
108-**When to use each status:**
109-- `in_progress`: When you start working on a task
110-- `done`: When you successfully complete a task
111-- `failed`: When a task cannot be completed (include error in message)
112-- `open`: To reset a task to not-started (rarely needed)
113-
114----
115-
116-### Action: next
117-
118-**Purpose:** Move to the next task, automatically marking the current task as done.
119-
120-**Required parameters:**
121-- `name`: Plan name
122-
123-**Example:**
124-```json
125-{
126- "action": "next",
127- "name": "setup-project"
128-}
129-```
130-
131-**What happens:**
132-- Current task is marked as "done" with completion timestamp
133-- Plan's current pointer moves to the next task
134-- Next task is automatically set to "in_progress"
135-- Returns info about the next task
136-
137-**What you should do:**
138-- Call `next` after completing a task
139-- Use the returned next task info to continue your work
140-- Include the status line in your response to the user
141-
142----
143-
144-### Action: get
145-
146-**Purpose:** Retrieve the full details of a plan.
147-
148-**Required parameters:**
149-- `name`: Plan name
150-
151-**Example:**
152-```json
153-{
154- "action": "get",
155- "name": "setup-project"
156-}
157-```
158-
159-**What you should do:**
160-- Use this when you need to see all tasks in a plan
161-- Rarely needed in normal workflow
162-
163----
164-
165-### Action: list
166-
167-**Purpose:** List all active plans for this session.
168-
169-**Example:**
170-```json
171-{
172- "action": "list"
173-}
174-```
175-
176-**What you should do:**
177-- Use this when the user asks "What plans do I have?"
178-- Returns names of all active plans
179-
180----
181-
182-### Action: delete
183-
184-**Purpose:** Delete a plan.
185-
186-**Required parameters:**
187-- `name`: Plan name
188-
189-**Example:**
190-```json
191-{
192- "action": "delete",
193- "name": "old-plan"
194-}
195-```
196-
197-**What you should do:**
198-- Use when user asks to abandon a plan
199-- Confirm with user before deleting
200-
201----
202-
203-### Action: status
204-
205-**Purpose:** Get a compact status line for display.
206-
207-**Required parameters:**
208-- `name`: Plan name
209-
210-**Example:**
211-```json
212-{
213- "action": "status",
214- "name": "setup-project"
215-}
216-```
217-
218-**What it returns:**
219-```
220-[2/5] Task 2: Create the main file (in_progress)
221-```
222-
223-**What you should do:**
224-- **ALWAYS** call `plan(action="status")` at the end of your response when a plan is active
225-- Include the status line in your response so the user can see progress
226-- The status line format: `[current/total] icon Task N: description (status)`
227-
228----
229-
230-## Complete Workflow Example
231-
232-**User:** "I need you to set up a new project. Do these 3 things: 1. Create the directory structure, 2. Initialize git, 3. Create a README file"
233-
234-**Your internal process:**
235-
236-1. **Detect the plan:** User gave a numbered list
237-
238-2. **Create the plan:**
239- ```json
240- plan(action="create", name="setup-project", tasks=[
241- {description: "Create the directory structure"},
242- {description: "Initialize git"},
243- {description: "Create a README file"}
244- ])
245- ```
246- Tool returns: `{"result":"Plan 'setup-project' created with 3 tasks. Current: Task 1", ...}`
247-
248-3. **Start first task:**
249- ```json
250- plan(action="update", name="setup-project", taskId=1, status="in_progress")
251- ```
252- Tool returns: `{"result":"Task 1 in plan 'setup-project' updated to 'in_progress'"}`
253-
254-4. **Do the work:** Use bash or other tools to create directory structure
255- ```json
256- bash(command: "mkdir -p project/src project/tests project/docs")
257- ```
258-
259-5. **Mark first task done:**
26030 ```json
261- plan(action="update", name="setup-project", taskId=1, status="done")
31+ {"action": "create", "tasks": [
32+ {"description": "Create the directory structure"},
33+ {"description": "Initialize git"},
34+ {"description": "Create a README file"}
35+ ]}
26236 ```
26337
264-6. **Move to next task:**
265- ```json
266- plan(action="next", name="setup-project")
267- ```
268- Tool returns: `{"result":"Task 1 done. Next: Task 2 - Initialize git", ...}`
38+2. Do the work of task 1 with your other tools. When it is finished:
26939
270-7. **Get status for display:**
27140 ```json
272- plan(action="status", name="setup-project")
273- ```
274- Tool returns: `{"result":"Plan 'setup-project': 1/3 tasks complete", "status":"[2/3] Task 2: Initialize git (in_progress)"}`
275-
276-8. **Respond to user:**
41+ {"action": "update", "taskId": 1, "status": "done"}
27742 ```
278- Directory structure created.
279-
280- 📋 [2/3] Task 2: Initialize git (in_progress)
281- ```
282-
283-9. **Continue with task 2:** Initialize git, then call `next` again
284-
285-10. **Continue with task 3:** Create README, then call `next` again
286-
287-11. **Plan complete:**
288- ```
289- All done! Project set up with:
290- - Directory structure created
291- - Git initialized
292- - README file created
293-
294- 📋 [3/3] All tasks complete! ✅
295- ```
296-
297----
298-
299-## Handling User Interruptions
300-
301-### User asks about the plan
302-
303-**User:** "What's the status of my plan?"
304-
305-**You:**
306-1. Call: `plan(action="status", name="setup-project")`
307-2. Use the returned status line in your response
308-
309-**Response:**
310-```
311-Current plan: [2/3] Task 2: Initialize git (in_progress). Next: Create a README file
312-```
313-
314----
315-
316-### User wants to skip a task
317-
318-**User:** "Skip the git initialization, just do the README"
319-
320-**You:**
321-1. Mark current task as done: `plan(action="update", name="setup-project", taskId=2, status="done")`
322-2. Call next: `plan(action="next", name="setup-project")`
323-3. Confirm to user: "Skipping git initialization. Creating README file..."
324-
325----
326-
327-### User wants to abandon the plan
328-
329-**User:** "Never mind, I don't need this anymore"
330-
331-**You:**
332-1. Ask for confirmation: "Are you sure you want to abandon the plan? We've completed 1 of 3 tasks."
333-2. If user confirms: `plan(action="delete", name="setup-project")`
334-3. Respond: "Plan abandoned. All progress is lost."
335-
336----
337-
338-## Multiple Plans
339-
340-A session can have multiple active plans. Use different names for each.
341-
342-**Example:**
343-- User: "First, fix the bug in the auth module. Then, update the documentation."
344-- You: Create plan "fix-auth-bug" with 3 tasks
345-- User (later): "Also, refactor the API"
346-- You: Create plan "refactor-api" with 2 tasks
347-
348-To list all plans: `plan(action="list")`
349-
350----
35143
352-## Status Line Format
44+3. Same for each next task: do the work, then **ONE** update with `"status": "done"`.
35345
354-Always show the plan status in this exact format:
46+4. When every task is done, **give your answer**. Do not call `plan` again.
35547
356-```
357-📋 [current/total] icon Task N: description (status)
358-```
48+That is all. `name` is optional: the most recent plan is used.
35949
360-**Icons:**
361-- ✅ = done
362-- 🔄 = in_progress
363-- ❌ = failed
364-- ⏳ = open (not started)
50+## Rules
36551
366-**Examples:**
367-- `📋 [1/5] ⏳ Task 1: Analyze code (open)`
368-- `📋 [2/5] 🔄 Task 2: Fix the bugs (in_progress)`
369-- `📋 [5/5] ✅ All tasks complete!`
370-- `📋 [3/5] ❌ Task 3: Run tests (failed: connection timeout)`
52+- **One plan call per finished task.** Do not call `plan` before starting a task, between the steps of a task, or to read the status: mm shows the progress itself.
53+- **Always give `status`** in an update: `done`, or `failed` when the task cannot be done.
54+- **A task failed**: mark it, with the reason in `message`, then go on with the next task or ask the user:
37155
372----
373-
374-## Important Rules
375-
376-1. **Always create a plan for multi-step requests** - Don't just say "I'll do it" and then forget what was requested
377-
378-2. **Always show the status line** - Include `plan(action="status")` result in every response when a plan is active
379-
380-3. **Always update task status** - Call `update` when starting and completing each task
381-
382-4. **Use meaningful plan names** - Auto-generated names are fine, but if the user gives a clear purpose, use it
383-
384-5. **Keep plans focused** - One plan per distinct request. Don't mix unrelated tasks in one plan
385-
386-6. **Handle errors gracefully** - If a task fails, mark it as failed with a note, then continue or ask the user
387-
388-7. **Clean up on /new** - Plans are automatically cleared when the user starts a new session
389-
390----
391-
392-## Common Patterns
393-
394-### Pattern: Sequential tasks with tool calls
395-
396-```
397-User: "Fix these issues: 1. Add error handling, 2. Write tests"
398-
399-You:
400-1. plan(create, tasks=[...])
401-2. plan(update, taskId=1, status=in_progress)
402-3. edit_file(...) // or bash or other tools
403-4. plan(update, taskId=1, status=done)
404-5. plan(next)
405-6. plan(update, taskId=2, status=in_progress)
406-7. write_file(...)
407-8. plan(update, taskId=2, status=done)
408-9. plan(next) // Triggers completion message
409-10. Respond with status line
410-```
411-
412----
56+ ```json
57+ {"action": "update", "taskId": 2, "status": "failed", "message": "git is not installed"}
58+ ```
41359
414-### Pattern: User gives unordered list
60+- `update` changes the status of ONE task. It cannot change the list of tasks.
41561
416-**User:** "I need A, B, and C done"
62+## When the user asks about the plan
41763
418-**You:** Convert to ordered tasks:
419-```json
420-{
421- "action": "create",
422- "tasks": [
423- {"description": "Do A"},
424- {"description": "Do B"},
425- {"description": "Do C"}
426- ]
427-}
428-```
64+| The user says | You do |
65+| --- | --- |
66+| "Where are we?" / "What's the status?" | `{"action": "status"}`, then answer with what it returns. |
67+| "Skip the tests and go on." | `{"action": "update", "taskId": 3, "status": "done", "message": "skipped by the user"}`, then the next task. |
68+| "Never mind, drop it." | Ask for confirmation, then `{"action": "delete", "name": "<plan name>"}`. |
69+| "What plans do I have?" | `{"action": "list"}` |
42970
430----
431-
432-### Pattern: Complex task requiring subtasks
433-
434-If a single task from the user's list requires multiple steps, you can:
435-- Option A: Add it as a single task and just do it
436-- Option B: Create a nested plan (advanced, not required for v1)
71+## Examples: plan or not?
43772
438-For v1, use Option A - keep it simple.
439-
440----
441-
442-## What NOT to Do
443-
444-❌ **Don't ignore numbered lists** - Always create a plan
445-❌ **Don't forget to update status** - Track progress accurately
446-❌ **Don't create plans for single tasks** - Overkill for simple requests
447-❌ **Don't make up tasks** - Only create tasks the user actually requested
448-❌ **Don't delete plans without asking** - Always confirm with user
449-
450----
451-
452-## Testing Your Understanding
453-
454-Read these user messages and decide if you should create a plan:
455-
456-| User Message | Create Plan? | Why |
457-|--------------|-------------|-----|
458-| "Write a function to sort an array" | No | Single task |
459-| "Fix these 3 bugs in the code" | Yes | Multi-step, but needs clarification |
460-| "1. Fix bug A, 2. Fix bug B, 3. Test both" | Yes | Explicit numbered list |
73+| User message | Plan? | Why |
74+| --- | --- | --- |
75+| "Write a function to sort an array" | No | One task |
76+| "1. Fix bug A, 2. Fix bug B, 3. Test both" | Yes | Numbered list |
77+| "Set up the project: create dirs, init git, add README" | Yes | Three actions |
46178 | "Hello, how are you?" | No | Not a task |
462-| "What's the capital of France?" | No | Question, not a task |
463-| "Set up the project: create dirs, init git, add README" | Yes | Comma-separated tasks |
464-| "I need the documentation updated and the tests fixed" | Yes | Multiple distinct tasks |
465-
466----
467-
468-## Summary
469-
470-**Remember:** When the user gives you a list of things to do, **CREATE A PLAN**. Then **TRACK PROGRESS**. Then **REPORT STATUS** to the user.
471-
472-This makes you more reliable, transparent, and easier to work with.
79+| "What's the capital of France?" | No | A question |
@@ -1,472 +1,79 @@
1 ---1 ---
2 name: plan-manager2 name: plan-manager
3-description: Manage multi-step work as a plan. When the user gives you a list of tasks to do, or you decide to break work into steps, use the plan tool to create and track a todo list. This ensures the user can see your progress and you don't lose track of what remains to be done.3+description: Manage multi-step work as a plan. When the user gives you a list of tasks to do, or the work has 3 or more distinct steps, use the plan tool to keep a todo list — one create, then one update per finished task. mm shows the user the progress.
4 keywords: plan, todo, tasks, steps, first, second, third, then, after that, next, do this, do these, i need, i want, following, steps are, task list, to do4 keywords: plan, todo, tasks, steps, first, second, third, then, after that, next, do this, do these, i need, i want, following, steps are, task list, to do
5 ---5 ---
6 # Plan Manager6 # Plan Manager
7 7
8-## What This Skill Does8+## What this skill does
9 9
10-This skill teaches you how to **detect, create, and manage plans** when users give you multi-step requests.10+It tells you **when** to keep a plan and **how few calls** it takes. A plan is a todo list kept by the `plan` tool. mm shows the user where the plan is after every plan call: you do not have to report it.
11 11
12-A **plan** is a structured way to track progress through multiple tasks. When you create a plan, you:12+## When to make a plan
13-1. Store the list of tasks the user wants done
14-2. Track which task you're currently working on
15-3. Update the status of each task as you complete it
16-4. Report progress to the user with clear status messages
17 13
18-## When to Use This Skill14+Make a plan when:
19 15
20-**ALWAYS** create and use a plan when:16+- the user gives a numbered list: "1. Fix A, 2. Update B, 3. Test C";
17+- the user lists several actions: "fix A, then update B, and finally test C";
18+- the user says "here's my plan", "do these things";
19+- the work has **3 or more distinct steps**.
21 20
22-1. **User gives you a numbered list:**21+Do **not** make a plan for:
23- - "Do these 3 things: 1. X, 2. Y, 3. Z"
24- - "Please: 1. First, 2. Second, 3. Third"
25- - "My plan is: 1. Step one, 2. Step two"
26 22
27-2. **User gives you a comma-separated or bullet list of actions:**23+- a single request ("write a function that sorts an array") — just do it;
28- - "I need you to fix A, then update B, and finally test C"24+- a question, a greeting, a conversation.
29- - "Please handle: - A, - B, - C"
30 25
31-3. **User explicitly says they have a plan:**26+## How to use it: one create, one update per task
32- - "Here's my plan: ..."
33- - "My plan is to..."
34- - "I want to do X, Y, and Z"
35 27
36-4. **You decide to break complex work into steps:**28+1. Create the list, one task per thing the user asked for (do not invent tasks):
37- - When a single request requires multiple distinct actions
38- - When you need to track progress for a multi-part task
39 29
40-**NEVER** use the plan tool for:
41-- Single, simple requests (just do it directly)
42-- Conversational questions with no action required
43-- Greetings or social interactions
44-- Requests that don't involve doing something
45-
46-## The Plan Tool
47-
48-The `plan` tool is a builtin tool available to you. It supports these **actions**:
49-
50-### Action: create
51-
52-**Purpose:** Create a new plan with a list of tasks.
53-
54-**Required parameters:**
55-- `tasks`: Array of task objects, each with `description` (string)
56-
57-**Optional parameters:**
58-- `name`: Plan name (string). If not provided, auto-generated as "user-request-N"
59-
60-**Example:**
61-```json
62-{
63- "action": "create",
64- "name": "setup-project",
65- "tasks": [
66- {"description": "Initialize the repository"},
67- {"description": "Create the main file"},
68- {"description": "Add configuration"}
69- ]
70-}
71-```
72-
73-**What happens:**
74-- A new plan is created with the given tasks
75-- Each task gets an auto-incrementing ID (1, 2, 3...)
76-- All tasks start with status "open"
77-- The plan is stored for this session
78-
79-**What you should do:**
80-- Call `plan` with `action: "create"` as soon as you detect a multi-step request
81-- Then immediately call `plan` with `action: "update"` to mark the first task as "in_progress"
82-- Tell the user: "I'll handle this in N steps. Starting with: [first task description]"
83-
84----
85-
86-### Action: update
87-
88-**Purpose:** Update the status of a specific task.
89-
90-**Required parameters:**
91-- `name`: Plan name
92-- `taskId`: The task ID to update (1-based)
93-- `status`: New status. One of: `open`, `in_progress`, `done`, `failed`
94-
95-**Optional parameters:**
96-- `message`: A note about this status change (e.g., error message for failed)
97-
98-**Example:**
99-```json
100-{
101- "action": "update",
102- "name": "setup-project",
103- "taskId": 1,
104- "status": "in_progress"
105-}
106-```
107-
108-**When to use each status:**
109-- `in_progress`: When you start working on a task
110-- `done`: When you successfully complete a task
111-- `failed`: When a task cannot be completed (include error in message)
112-- `open`: To reset a task to not-started (rarely needed)
113-
114----
115-
116-### Action: next
117-
118-**Purpose:** Move to the next task, automatically marking the current task as done.
119-
120-**Required parameters:**
121-- `name`: Plan name
122-
123-**Example:**
124-```json
125-{
126- "action": "next",
127- "name": "setup-project"
128-}
129-```
130-
131-**What happens:**
132-- Current task is marked as "done" with completion timestamp
133-- Plan's current pointer moves to the next task
134-- Next task is automatically set to "in_progress"
135-- Returns info about the next task
136-
137-**What you should do:**
138-- Call `next` after completing a task
139-- Use the returned next task info to continue your work
140-- Include the status line in your response to the user
141-
142----
143-
144-### Action: get
145-
146-**Purpose:** Retrieve the full details of a plan.
147-
148-**Required parameters:**
149-- `name`: Plan name
150-
151-**Example:**
152-```json
153-{
154- "action": "get",
155- "name": "setup-project"
156-}
157-```
158-
159-**What you should do:**
160-- Use this when you need to see all tasks in a plan
161-- Rarely needed in normal workflow
162-
163----
164-
165-### Action: list
166-
167-**Purpose:** List all active plans for this session.
168-
169-**Example:**
170-```json
171-{
172- "action": "list"
173-}
174-```
175-
176-**What you should do:**
177-- Use this when the user asks "What plans do I have?"
178-- Returns names of all active plans
179-
180----
181-
182-### Action: delete
183-
184-**Purpose:** Delete a plan.
185-
186-**Required parameters:**
187-- `name`: Plan name
188-
189-**Example:**
190-```json
191-{
192- "action": "delete",
193- "name": "old-plan"
194-}
195-```
196-
197-**What you should do:**
198-- Use when user asks to abandon a plan
199-- Confirm with user before deleting
200-
201----
202-
203-### Action: status
204-
205-**Purpose:** Get a compact status line for display.
206-
207-**Required parameters:**
208-- `name`: Plan name
209-
210-**Example:**
211-```json
212-{
213- "action": "status",
214- "name": "setup-project"
215-}
216-```
217-
218-**What it returns:**
219-```
220-[2/5] Task 2: Create the main file (in_progress)
221-```
222-
223-**What you should do:**
224-- **ALWAYS** call `plan(action="status")` at the end of your response when a plan is active
225-- Include the status line in your response so the user can see progress
226-- The status line format: `[current/total] icon Task N: description (status)`
227-
228----
229-
230-## Complete Workflow Example
231-
232-**User:** "I need you to set up a new project. Do these 3 things: 1. Create the directory structure, 2. Initialize git, 3. Create a README file"
233-
234-**Your internal process:**
235-
236-1. **Detect the plan:** User gave a numbered list
237-
238-2. **Create the plan:**
239- ```json
240- plan(action="create", name="setup-project", tasks=[
241- {description: "Create the directory structure"},
242- {description: "Initialize git"},
243- {description: "Create a README file"}
244- ])
245- ```
246- Tool returns: `{"result":"Plan 'setup-project' created with 3 tasks. Current: Task 1", ...}`
247-
248-3. **Start first task:**
249- ```json
250- plan(action="update", name="setup-project", taskId=1, status="in_progress")
251- ```
252- Tool returns: `{"result":"Task 1 in plan 'setup-project' updated to 'in_progress'"}`
253-
254-4. **Do the work:** Use bash or other tools to create directory structure
255- ```json
256- bash(command: "mkdir -p project/src project/tests project/docs")
257- ```
258-
259-5. **Mark first task done:**
260 ```json30 ```json
261- plan(action="update", name="setup-project", taskId=1, status="done")31+ {"action": "create", "tasks": [
32+ {"description": "Create the directory structure"},
33+ {"description": "Initialize git"},
34+ {"description": "Create a README file"}
35+ ]}
262 ```36 ```
263 37
264-6. **Move to next task:**38+2. Do the work of task 1 with your other tools. When it is finished:
265- ```json
266- plan(action="next", name="setup-project")
267- ```
268- Tool returns: `{"result":"Task 1 done. Next: Task 2 - Initialize git", ...}`
269 39
270-7. **Get status for display:**
271 ```json40 ```json
272- plan(action="status", name="setup-project")41+ {"action": "update", "taskId": 1, "status": "done"}
273- ```
274- Tool returns: `{"result":"Plan 'setup-project': 1/3 tasks complete", "status":"[2/3] Task 2: Initialize git (in_progress)"}`
275-
276-8. **Respond to user:**
277 ```42 ```
278- Directory structure created.
279-
280- 📋 [2/3] Task 2: Initialize git (in_progress)
281- ```
282-
283-9. **Continue with task 2:** Initialize git, then call `next` again
284-
285-10. **Continue with task 3:** Create README, then call `next` again
286-
287-11. **Plan complete:**
288- ```
289- All done! Project set up with:
290- - Directory structure created
291- - Git initialized
292- - README file created
293-
294- 📋 [3/3] All tasks complete! ✅
295- ```
296-
297----
298-
299-## Handling User Interruptions
300-
301-### User asks about the plan
302-
303-**User:** "What's the status of my plan?"
304-
305-**You:**
306-1. Call: `plan(action="status", name="setup-project")`
307-2. Use the returned status line in your response
308-
309-**Response:**
310-```
311-Current plan: [2/3] Task 2: Initialize git (in_progress). Next: Create a README file
312-```
313-
314----
315-
316-### User wants to skip a task
317-
318-**User:** "Skip the git initialization, just do the README"
319-
320-**You:**
321-1. Mark current task as done: `plan(action="update", name="setup-project", taskId=2, status="done")`
322-2. Call next: `plan(action="next", name="setup-project")`
323-3. Confirm to user: "Skipping git initialization. Creating README file..."
324-
325----
326-
327-### User wants to abandon the plan
328-
329-**User:** "Never mind, I don't need this anymore"
330-
331-**You:**
332-1. Ask for confirmation: "Are you sure you want to abandon the plan? We've completed 1 of 3 tasks."
333-2. If user confirms: `plan(action="delete", name="setup-project")`
334-3. Respond: "Plan abandoned. All progress is lost."
335-
336----
337-
338-## Multiple Plans
339-
340-A session can have multiple active plans. Use different names for each.
341-
342-**Example:**
343-- User: "First, fix the bug in the auth module. Then, update the documentation."
344-- You: Create plan "fix-auth-bug" with 3 tasks
345-- User (later): "Also, refactor the API"
346-- You: Create plan "refactor-api" with 2 tasks
347-
348-To list all plans: `plan(action="list")`
349-
350----
351 43
352-## Status Line Format44+3. Same for each next task: do the work, then **ONE** update with `"status": "done"`.
353 45
354-Always show the plan status in this exact format:46+4. When every task is done, **give your answer**. Do not call `plan` again.
355 47
356-```48+That is all. `name` is optional: the most recent plan is used.
357-📋 [current/total] icon Task N: description (status)
358-```
359 49
360-**Icons:**50+## Rules
361-- ✅ = done
362-- 🔄 = in_progress
363-- ❌ = failed
364-- ⏳ = open (not started)
365 51
366-**Examples:**52+- **One plan call per finished task.** Do not call `plan` before starting a task, between the steps of a task, or to read the status: mm shows the progress itself.
367-- `📋 [1/5] ⏳ Task 1: Analyze code (open)`53+- **Always give `status`** in an update: `done`, or `failed` when the task cannot be done.
368-- `📋 [2/5] 🔄 Task 2: Fix the bugs (in_progress)`54+- **A task failed**: mark it, with the reason in `message`, then go on with the next task or ask the user:
369-- `📋 [5/5] ✅ All tasks complete!`
370-- `📋 [3/5] ❌ Task 3: Run tests (failed: connection timeout)`
371 55
372----56+ ```json
373-57+ {"action": "update", "taskId": 2, "status": "failed", "message": "git is not installed"}
374-## Important Rules58+ ```
375-
376-1. **Always create a plan for multi-step requests** - Don't just say "I'll do it" and then forget what was requested
377-
378-2. **Always show the status line** - Include `plan(action="status")` result in every response when a plan is active
379-
380-3. **Always update task status** - Call `update` when starting and completing each task
381-
382-4. **Use meaningful plan names** - Auto-generated names are fine, but if the user gives a clear purpose, use it
383-
384-5. **Keep plans focused** - One plan per distinct request. Don't mix unrelated tasks in one plan
385-
386-6. **Handle errors gracefully** - If a task fails, mark it as failed with a note, then continue or ask the user
387-
388-7. **Clean up on /new** - Plans are automatically cleared when the user starts a new session
389-
390----
391-
392-## Common Patterns
393-
394-### Pattern: Sequential tasks with tool calls
395-
396-```
397-User: "Fix these issues: 1. Add error handling, 2. Write tests"
398-
399-You:
400-1. plan(create, tasks=[...])
401-2. plan(update, taskId=1, status=in_progress)
402-3. edit_file(...) // or bash or other tools
403-4. plan(update, taskId=1, status=done)
404-5. plan(next)
405-6. plan(update, taskId=2, status=in_progress)
406-7. write_file(...)
407-8. plan(update, taskId=2, status=done)
408-9. plan(next) // Triggers completion message
409-10. Respond with status line
410-```
411-
412----
413 59
414-### Pattern: User gives unordered list60+- `update` changes the status of ONE task. It cannot change the list of tasks.
415 61
416-**User:** "I need A, B, and C done"62+## When the user asks about the plan
417 63
418-**You:** Convert to ordered tasks:64+| The user says | You do |
419-```json65+| --- | --- |
420-{66+| "Where are we?" / "What's the status?" | `{"action": "status"}`, then answer with what it returns. |
421- "action": "create",67+| "Skip the tests and go on." | `{"action": "update", "taskId": 3, "status": "done", "message": "skipped by the user"}`, then the next task. |
422- "tasks": [68+| "Never mind, drop it." | Ask for confirmation, then `{"action": "delete", "name": "<plan name>"}`. |
423- {"description": "Do A"},69+| "What plans do I have?" | `{"action": "list"}` |
424- {"description": "Do B"},
425- {"description": "Do C"}
426- ]
427-}
428-```
429 70
430----71+## Examples: plan or not?
431-
432-### Pattern: Complex task requiring subtasks
433-
434-If a single task from the user's list requires multiple steps, you can:
435-- Option A: Add it as a single task and just do it
436-- Option B: Create a nested plan (advanced, not required for v1)
437 72
438-For v1, use Option A - keep it simple.73+| User message | Plan? | Why |
439-74+| --- | --- | --- |
440----75+| "Write a function to sort an array" | No | One task |
441-76+| "1. Fix bug A, 2. Fix bug B, 3. Test both" | Yes | Numbered list |
442-## What NOT to Do77+| "Set up the project: create dirs, init git, add README" | Yes | Three actions |
443-
444-❌ **Don't ignore numbered lists** - Always create a plan
445-❌ **Don't forget to update status** - Track progress accurately
446-❌ **Don't create plans for single tasks** - Overkill for simple requests
447-❌ **Don't make up tasks** - Only create tasks the user actually requested
448-❌ **Don't delete plans without asking** - Always confirm with user
449-
450----
451-
452-## Testing Your Understanding
453-
454-Read these user messages and decide if you should create a plan:
455-
456-| User Message | Create Plan? | Why |
457-|--------------|-------------|-----|
458-| "Write a function to sort an array" | No | Single task |
459-| "Fix these 3 bugs in the code" | Yes | Multi-step, but needs clarification |
460-| "1. Fix bug A, 2. Fix bug B, 3. Test both" | Yes | Explicit numbered list |
461 | "Hello, how are you?" | No | Not a task |78 | "Hello, how are you?" | No | Not a task |
462-| "What's the capital of France?" | No | Question, not a task |79+| "What's the capital of France?" | No | A question |
463-| "Set up the project: create dirs, init git, add README" | Yes | Comma-separated tasks |
464-| "I need the documentation updated and the tests fixed" | Yes | Multiple distinct tasks |
465-
466----
467-
468-## Summary
469-
470-**Remember:** When the user gives you a list of things to do, **CREATE A PLAN**. Then **TRACK PROGRESS**. Then **REPORT STATUS** to the user.
471-
472-This makes you more reliable, transparent, and easier to work with.
modified struggle_wiring.go +4 -0
@@ -15,6 +15,7 @@ import (
1515 // reportLoop(detector.Loop{Tool: "bash", Repeats: 4}) // ⚠ loop: bash ×4
1616 // reportLoop(detector.Loop{Tool: "bash", Repeats: 6, Stuck: true}) // ✖ stuck: bash ×6
1717 // reportLoop(detector.Loop{Tool: "bash", Repeats: 3, Failing: true}) // ⚠ failing: 3 tool calls in a row
18+// reportLoop(detector.Loop{Tool: "bash", Repeats: 3, Similar: true}) // ⚠ same test again: bash ×3 …
1819 func reportLoop(l detector.Loop) {
1920 ui.ReportStruggle(loopStruggle(l))
2021 }
@@ -22,6 +23,9 @@ func reportLoop(l detector.Loop) {
2223 // loopStruggle is reportLoop's struggle, kept apart so it can be tested
2324 // without a front end.
2425 func loopStruggle(l detector.Loop) ui.Struggle {
26+ if l.Similar {
27+ return ui.Struggle{Label: fmt.Sprintf("same test again: %s ×%d with the same result, no file changed", l.Tool, l.Repeats)}
28+ }
2529 if l.Failing {
2630 return ui.Struggle{Label: fmt.Sprintf("failing: %d tool calls in a row", l.Repeats)}
2731 }
@@ -15,6 +15,7 @@ import (
15 // reportLoop(detector.Loop{Tool: "bash", Repeats: 4}) // ⚠ loop: bash ×415 // reportLoop(detector.Loop{Tool: "bash", Repeats: 4}) // ⚠ loop: bash ×4
16 // reportLoop(detector.Loop{Tool: "bash", Repeats: 6, Stuck: true}) // ✖ stuck: bash ×616 // reportLoop(detector.Loop{Tool: "bash", Repeats: 6, Stuck: true}) // ✖ stuck: bash ×6
17 // reportLoop(detector.Loop{Tool: "bash", Repeats: 3, Failing: true}) // ⚠ failing: 3 tool calls in a row17 // reportLoop(detector.Loop{Tool: "bash", Repeats: 3, Failing: true}) // ⚠ failing: 3 tool calls in a row
18+// reportLoop(detector.Loop{Tool: "bash", Repeats: 3, Similar: true}) // ⚠ same test again: bash ×3 …
18 func reportLoop(l detector.Loop) {19 func reportLoop(l detector.Loop) {
19 ui.ReportStruggle(loopStruggle(l))20 ui.ReportStruggle(loopStruggle(l))
20 }21 }
@@ -22,6 +23,9 @@ func reportLoop(l detector.Loop) {
22 // loopStruggle is reportLoop's struggle, kept apart so it can be tested23 // loopStruggle is reportLoop's struggle, kept apart so it can be tested
23 // without a front end.24 // without a front end.
24 func loopStruggle(l detector.Loop) ui.Struggle {25 func loopStruggle(l detector.Loop) ui.Struggle {
26+ if l.Similar {
27+ return ui.Struggle{Label: fmt.Sprintf("same test again: %s ×%d with the same result, no file changed", l.Tool, l.Repeats)}
28+ }
25 if l.Failing {29 if l.Failing {
26 return ui.Struggle{Label: fmt.Sprintf("failing: %d tool calls in a row", l.Repeats)}30 return ui.Struggle{Label: fmt.Sprintf("failing: %d tool calls in a row", l.Repeats)}
27 }31 }
modified struggle_wiring_test.go +1 -0
@@ -12,6 +12,7 @@ func TestLoopStruggleWarnsThenStops(t *testing.T) {
1212 {Tool: "bash", Repeats: 4}: {Label: "loop: bash ×4"},
1313 {Tool: "edit_file", Repeats: 6, Stuck: true}: {Severe: true, Label: "stuck: edit_file ×6"},
1414 {Tool: "bash", Repeats: 3, Failing: true}: {Label: "failing: 3 tool calls in a row"},
15+ {Tool: "bash", Repeats: 3, Similar: true}: {Label: "same test again: bash ×3 with the same result, no file changed"},
1516 }
1617 for loop, want := range cases {
1718 if got := loopStruggle(loop); got != want {
@@ -12,6 +12,7 @@ func TestLoopStruggleWarnsThenStops(t *testing.T) {
12 {Tool: "bash", Repeats: 4}: {Label: "loop: bash ×4"},12 {Tool: "bash", Repeats: 4}: {Label: "loop: bash ×4"},
13 {Tool: "edit_file", Repeats: 6, Stuck: true}: {Severe: true, Label: "stuck: edit_file ×6"},13 {Tool: "edit_file", Repeats: 6, Stuck: true}: {Severe: true, Label: "stuck: edit_file ×6"},
14 {Tool: "bash", Repeats: 3, Failing: true}: {Label: "failing: 3 tool calls in a row"},14 {Tool: "bash", Repeats: 3, Failing: true}: {Label: "failing: 3 tool calls in a row"},
15+ {Tool: "bash", Repeats: 3, Similar: true}: {Label: "same test again: bash ×3 with the same result, no file changed"},
15 }16 }
16 for loop, want := range cases {17 for loop, want := range cases {
17 if got := loopStruggle(loop); got != want {18 if got := loopStruggle(loop); got != want {