diff --git a/DECISIONS.md b/DECISIONS.md index 8a8553c9..55960870 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -22347,6 +22347,121 @@ fault; showing both runs on their own, in both views, says what is known. --- +## 2026-12-01 — TD-5428: following through on a reply that says it will continue (Class B) + +**One protocol, one parser.** The nudge asks with the progress check's +label lines (`FOLLOW_THROUGH_INSTRUCTION` and `PROGRESS_CHECK_INSTRUCTION` +share them) and `interpret_check` reads the answer. The step itself is in +`follow_through_turn.py`; detection is `follow_through.py`, text in and +phrase or `None` out. + +**The nudge is a user-role message from TST Desk,** as the progress check +is, not a second system message: strict local chat templates accept one +system message, first (TD-5142), and a request must end on a user turn +(TD-5177). It is kept in the conversation only with an answer to it, marked +`check`, so it is not one of the window's user turns and roles still +alternate. + +**No per-turn limit (the owner, 2026-12-01).** "Why can't it just +automatically continue? If there is work still to do then it should not stop +and just do it." So every stop that announces a step is nudged, and the nudge +does not spend the guard's `MAX_AUTO_CONTINUES` (`note_follow_through` only +records the step). What still stops it: a `CONTINUE` that repeats the last +step (pauses, marked), and the model-call, spend, time and iteration caps. +This replaces the earlier "once a turn, shared with the guard's three". + +**What counts as still stopping.** An empty or step-less answer, a +`CONTINUE` repeating the guard's last step, a failed call (the reply stays, +marked), or an answer whose text, shown in place of the reply or under it, +still announces a step. A second announcement later in the turn is nudged +again. + +**Marked without a nudge** when the three windows are spent, the nudge was +already used, or the iteration, clock or spend cap is reached: the reply +still says it will continue, and a nudge past a cap would be a call the cap +forbids. Autonomy and delegate children are not looked at at all, so they +get no nudge, log or marker: they have their own breakers. Skip-all is +checked like any interactive turn (the manager's correction to the first +spec: the owner runs with approvals off, and the nudge asks the model to +keep its word, which is not a cap, so the progress guard's skip-all +precedent does not apply). + +**A tool call in the nudge's answer is not run.** The request offered no +tools; the turn goes on and the next request offers them. + +**Before the done-check.** The follow-through runs when the model ends the +turn, then the done-check and stop hooks (TD-5124) judge the reply the turn +really ends on, once. A progress check's answer with no label is a final +reply too and is followed through; a labelled one is taken as it is. + +**Continue is TD-5417's:** an ordinary "Continue" message. The marked turn +has ended (the story ends it), so the work resumes in the same chat as a new +turn on the wire, with fresh per-turn counters. Reopening a sealed turn +would need a new client message and daemon state that nothing else uses. + +**The mark rides on `turn_complete`** (`stopped_after_continue`, additive), +logged and replayed with the turn; the window puts it on the turn's last +reply. It is part of the persisted `turn_complete` event (events.jsonl), so it +survives a daemon restart with no schema change (test in +`test_follow_through_loop.py`); a reply rebuilt from saved history after the +log was trimmed has no mark. + +**Detection reads only the end of the reply, and is narrower than the +first spec (review round 1 of 3bbf63f0).** The manager's rule was "the last +sentence is future tense with no tool call". That fired on ordinary replies +("Understood. I'll use tabs.", "I'll answer any follow-up questions.", +drafted emails) and on hand-backs ("Reply \"yes\" and I'll run it." was +nudged, answered CONTINUE, and the tool ran with no yes). The manager asked +for "on no other reply", so precision wins and the rule is cut to two +triggers: a still-working or next-step phrase in the last two sentences of +the last paragraph, or a last sentence that is first-person future or says +the work is under way ("Running the tests now."). **The time cue was +dropped again (product owner):** requiring one un-triggered genuine stops +("The test hangs. I'll fix the call that is waiting on the lock.", "Encontré +el error. Voy a corregirlo en el paginador."), and a false nudge costs one +tool-free call that answers DONE while a missed stop costs the owner's turn. +The narrowing comes from the exclusions instead, including one for an +acknowledgement opener ("Understood", "Got it", "Sure", "Perfecto", ...) +followed by a habit or preference verb (use, keep, skip, avoid, stick to, +remember, do that; usaré, así lo haré, tendré en cuenta, ...), as the product +owner asked ("an acknowledgement opener and a habit verb rather than a blanket +time-cue gate"): "Understood. I'll use tabs." does not count, "Understood. +I'll fix the paginator." does. A heading line is not +a sentence of the reply. + +Never matched: a question; a request, permission ask or condition on the +person in the last four sentences (reply, send, pick, tell me, let me know, +once you, if you, after your, with your permission, go-ahead, say so, +approve; Spanish pásame, dime, avísame, cuando me, si me…), with "when +you're offline" kept as a description; bare acknowledgements; offers and +sign-offs; standing habits and other days; talk the reply delivers itself; +text in quotes, inline code or code blocks; and drafted messages. "...and +let you know the results" / "y te aviso" does not cancel a step. A miss ends the turn as before and a false match costs a call, so the +exclusions lean to missing. The table in `tests/test_follow_through.py` is +the source of truth; Known limit: a first-person future that is the +content itself (the last line of a poem) matches. + +**One bubble.** A `DONE` answer replaces the reply (one that only repeats the +reply leaves it alone). A text answer with no label never replaces the reply +or sits under it: the check was not answered, so the reply stays, marked, and +Continue is one click away (review round 2 found "I'll use tabs." replaced by +"Nothing else to do."; a length threshold was tried and dropped as an +invented number). A check cut off at the +token limit (`finish_reason: length`) never replaces or joins the reply: it +stays and the marker shows. +the loop sends `assistant_retract` for the reply's response id with reason +`follow_through_replaced`, then the answer as the next `assistant_delta`, +and puts it in the saved conversation in the reply's place (the nudge is not +kept). The window drops the reply's text but keeps its thinking and shows no +Working line (the reason is a free string; no schema field is added). A +`BLOCKED` answer is a question, not the reply, so it is added under it, unless +it says the reply again, when it replaces it. The turn is marked only when the text now shown still announces a step. + +**Continue stays on the marked reply** while only notices follow it: the +button is offered on the last row that is somebody's message. + +- **The manager confirmed both** (2026-12-01): the narrowed rule ("Yes, narrow it exactly as you propose. A hand-back or permission ask must never trigger, in either language, and the future-tense rule needs a time cue or a still-working phrase"), and Continue as a new turn for 0.5.14; the same-turn resume is TD-5430. A loop test proves "Reply 'yes' and I'll run it" ends the turn with no nudge and no tool run. + ### TD-5427: a web view that cannot draw **The whole app is replaced, not the web view.** WebKitGTK reads diff --git a/core/scripts/generate_protocol_fixtures.py b/core/scripts/generate_protocol_fixtures.py index c36ad118..92387c19 100644 --- a/core/scripts/generate_protocol_fixtures.py +++ b/core/scripts/generate_protocol_fixtures.py @@ -1070,6 +1070,7 @@ cost=0.03, tier="worker", duration=2.5, + stopped_after_continue=True, seq=12, ), "turn_complete_failed": TurnComplete( diff --git a/core/tests/test_follow_through.py b/core/tests/test_follow_through.py new file mode 100644 index 00000000..ac91ad6a --- /dev/null +++ b/core/tests/test_follow_through.py @@ -0,0 +1,701 @@ +"""The follow-through detector (TD-5428): which final replies say they go on. + +This table is the rule. Each row is a whole reply as a model writes one. +""" + +from __future__ import annotations + +import pytest + +from tstd.follow_through import PHRASES, announced_next_step + +MUST_TRIGGER = [ + # ── A still-working or next-step phrase ───────────────────────────── + # The reported reply. + ( + "Yes \u2014 I'm still working on it. I've read the meeting notes so far. " + "Next I'll extract the unfinished actions and group them by owner.", + "next i'll", + ), + ("Yes \u2014 I\u2019m still working on this.", "i'm still working"), + ( + "I've mapped the module layout.\n\nNext, I'll read the tests that cover the parser.", + "next, i'll", + ), + ("The config loads cleanly. Now I will update the migration script.", "now i will"), + ("That confirms the cause. Let me now fix the off-by-one in the pager.", "let me now"), + ( + "Two files are done. I'll continue with the remaining four.", + "i'll continue with the remaining", + ), + ("I found the failing test. Now I'm going to bisect the last ten commits.", "now i'm going to"), + ("Good, the build is green. I'll now write the release notes.", "i'll now"), + ( + "Step 1 is complete.\n\n**Next I will** wire the new endpoint into the router.", + "next i will", + ), + ( + "Here's where things stand: the export works.\n\nNext I'll:\n- add the date filter\n" + "- update the docs", + "next i'll", + ), + ( + "The export works.\n\nNext I'll:\n\n- add the date filter\n- update the docs", + "next i'll", + ), + ("Moving on to the settings page.", "moving on to"), + ("Still working on the report. I'll have the totals computed shortly.", "still working on"), + ( + "Next I'll extract the unfinished actions from each file.\n\nThis will take a moment.", + "next i'll", + ), + ("I'll now run the tests. This takes a few minutes. Hang tight.", "i'll now"), + ("Give me a moment. Next I'll rebuild the index.", "next i'll"), + ("The rename is done. Next I'll check if there are other callers.", "next i'll"), + ("Next I'll run:\n\n```bash\nnpm test\n```", "next i'll"), + ("Next I'll update `config.py` to read the new key.", "next i'll"), + # A report-back tail does not take the step back. + ("Next I'll run the tests and let you know the results.", "next i'll"), + ("The patch is in. Next I'll run the suite, and I'll let you know.", "next i'll"), + # "when you're offline" describes the thing being built. + ("Next I'll make the app save drafts for when you're offline.", "next i'll"), + ("Now I will add a retry that fires when you're back online.", "now i will"), + ("My plan is set. I will now apply it.", "i will now"), + ("I'm still working through the remaining logs.", "i'm still working"), + ("The schema is in place. Now, I'll seed the table.", "now, i'll"), + ("I'll keep working on the failing cases.", "i'll keep working"), + ("Half the pages are converted. I'll keep going.", "i'll keep going"), + ("Hi! Next I'll read the changelog.", "next i'll"), + # ── First person and future, with a time cue ──────────────────────── + ("I'll check the logs now.", "i'll"), + ("The directory has 40 files. Let me look at the largest ones next.", "let me"), + ("I have what I need, and I'm going to draft the summary now.", "i'm going to"), + ("I'll read these three modules, then I'll propose a split.", "i'll"), + ("After that I will inventory the open pull requests.", "i will"), + ("The schema is clear, so I'm about to run the migration now.", "i'm about to"), + ("Sure, I'll run the tests now.", "i'll"), + ("The branch is clean. Then I shall tag the release.", "i shall"), + ("I'm going to bisect the history next.", "i'm going to"), + ("I'll then compare the two outputs line by line.", "i'll"), + ("Both parsers are read. I am going to merge them now.", "i am going to"), + ("I'll run the migration now and let you know the results.", "i'll"), + # ── Work under way ────────────────────────────────────────────────── + ("Running the tests now.", "running"), + ("Checking the second log now\u2026", "checking"), + ("The fix is in. Now running the full suite.", "running"), + ("I'm updating the docs now.", "updating"), + ("Okay, searching the repository now.", "searching"), + ("Looking into the stack trace now.", "looking into"), + ("I'm now reading the migration files.", "reading"), + ("Re-running the failed job now and watching its output.", "re-running"), + # ── Spanish ───────────────────────────────────────────────────────── + ("S\u00ed, sigo trabajando en ello.", "sigo trabajando"), + ("Ya le\u00ed las notas. Ahora voy a extraer las acciones pendientes.", "ahora voy a"), + ( + "La configuraci\u00f3n est\u00e1 lista. A continuaci\u00f3n, voy a revisar las pruebas.", + "a continuaci\u00f3n, voy a", + ), + ( + "Dos archivos listos. Continuar\u00e9 con los dem\u00e1s.", + "continuar\u00e9 con los dem\u00e1s", + ), + ("Tengo los datos. Despu\u00e9s generar\u00e9 la tabla resumen.", "generar\u00e9"), + ( + "El registro es largo. Ahora d\u00e9jame revisar las \u00faltimas entradas.", + "ahora d\u00e9jame", + ), + ("Perfecto. Ahora procedo a actualizar el esquema.", "ahora procedo a"), + ("Ahora mismo voy a revisarlo.", "ahora mismo voy a"), + ("He visto el fallo. Luego voy a corregir el paginador.", "luego voy a"), + ("La copia termin\u00f3. Lo siguiente es verificar las sumas.", "lo siguiente es"), + ("Todav\u00eda estoy trabajando en el informe.", "todav\u00eda estoy trabajando"), + ("Ahora voy a ejecutar las pruebas y te aviso del resultado.", "ahora voy a"), + ("Luego revisar\u00e9 los registros y te aviso del resultado.", "revisar\u00e9"), + ("Primero compilo; despu\u00e9s voy a probarlo.", "despu\u00e9s voy a"), + ("A continuaci\u00f3n revisar\u00e9 las dependencias.", "revisar\u00e9"), + ("Ya est\u00e1 el esquema, y ahora vamos a poblar la tabla.", "vamos a"), + ("Ejecutando las pruebas ahora.", "ejecutando"), + ("Ahora estoy revisando los registros.", "revisando"), + ("Analizando el segundo archivo ahora mismo.", "analizando"), + ("Quedan tres. Sigo en ello.", "sigo en ello"), + # ── A future with no time cue is a stop too (product owner's table) ── + ("The test hangs. I'll fix the call that is waiting on the lock.", "i'll"), + ("The body is written. I'll add the footer at the end.", "i'll"), + ("Encontr\u00e9 el error. Voy a corregirlo en el paginador.", "voy a"), + ("El registro es largo. D\u00e9jame revisar las \u00faltimas entradas.", "d\u00e9jame"), + ("I'll check the logs and see why the worker restarted.", "i'll"), + ("I have what I need. I'm going to draft the summary.", "i'm going to"), + ("Understood. I'll fix the paginator now.", "i'll"), + ("Understood. I'll fix the paginator.", "i'll"), + ("Got it. I'll update the README with the new flag.", "i'll"), + ("Entendido. Voy a corregir el paginador.", "voy a"), + ("Moving on to the parser.", "moving on to"), + ("Moving on to the parser.\n\n## Next steps", "moving on to"), + # ── A closing "Next: " line, the progress note's own form (TD-5437) ── + # Real turn endings that stopped with no tool call. + ( + "I could not find it under the data folder.\n\nNext: Locate the actual session handoff " + "file with `ls -la ~/.local/share/app/sessions*` to read the correct prior context.", + "next:", + ), + ( + "The stream stalls in the browser only.\n\nNext: Reproduce the office stream through " + "the hub's WebSocket to separate a playback failure from a relay failure.", + "next:", + ), + ("Next: `web_fetch https://example.com/products.json` to list the models.", "next:"), + ("The parser is fixed. Next step: run the full suite.", "next:"), + ("**Next:** rerun the parser tests on a copy of the data.", "next:"), + ("Encontré el fallo. Siguiente paso: revisar los registros del nodo.", "next:"), + ("Next up: run the full suite.", "next:"), + ("Next action: inspect the worker logs.", "next:"), + ("NEXT STEP \u2014 rerun the parser test on a copy.", "next:"), + ("Next\u2014run the parser tests.", "next:"), + ("Next: rerun the failing test with -v.", "next:"), + ("The remaining work is rerunning the flaky suite.", "next:"), + ("Next: analyze the slow query plan.", "next:"), + ("El siguiente paso es revisar los registros.", "next:"), + ("The parser is fixed. The next step is to run the full suite.", "next:"), + ("_Next:_ check the cache keys.", "next:"), + # TD-5437 review round 3: read-only steps, wherever the lead sits. + ("Next: `grep -rn TODO src` to list the open items.", "next:"), + ("Next: inspect the payload parser.", "next:"), + ("Next: run the postgres query tests.", "next:"), + ("Siguiente paso: comprobar los registros del nodo.", "next:"), + # Review round 4: one action, read-only code, chained read-only commands. + ("Next: inspect the logs and compare the timestamps.", "next:"), + ("Next: `ls -la a && ls -la b` to read the layout.", "next:"), + ("Next: check the parser and the lexer.", "next:"), + ("Next: run the tests and check the coverage.", "next:"), + ("Next: `grep -rn TODO src | head` to list the open items.", "next:"), + ("Next: inspect `foo.py` and `bar.py`.", "next:"), + # Review round 5: flags and paths are not a second action. + ("The relay is up.\n\nNext: reproduce the stream to separate a relay/source failure.", "next:"), + # Review round 6: the common looks, a page to read, test tools, every lead form. + ("Next: `web_fetch https://example.com/docs/page` to read the page.", "next:"), + ("Next: read the page.", "next:"), + ("Next: check the status page.", "next:"), + ("Next: read the man page for rsync.", "next:"), + ("Next: run pytest.", "next:"), + ("Next: check the logs.", "next:"), + ("Next: run the tests.", "next:"), + ("Next: inspect the config.", "next:"), + ("The remaining work is checking the cache.", "next:"), + ("The next step is to inspect the logs.", "next:"), + ("Next - check the logs.", "next:"), + ("Next \u2013 check the logs.", "next:"), + ("Próximo paso: revisar los registros.", "next:"), + ("El próximo paso es revisar los registros.", "next:"), + ("Siguiente: revisar los registros.", "next:"), + ("Next: `git log -5` to read the history.", "next:"), + ("Next: `jq .items data.json` to read the items.", "next:"), + ("Next: `web_search rsync flags` to find the option.", "next:"), + # Review round 7: what was done above is no reason to stop a look; tools after "with". + ("Installed `pytest-xdist`.\n\nNext: run the tests.", "next:"), + ("Applied the fix to the parser.\n\nNext: run the tests.", "next:"), + ("I replaced the deprecated call in `api.py`.\n\nNext: run the tests.", "next:"), + ("Next: check the installed version.", "next:"), + ("Next: check in the logs for the timeout.", "next:"), + ("Next: verify with a SQL query.", "next:"), + ("Next: check with an HTTP request.", "next:"), + ("Next: check the logs on a node.", "next:"), + ("Next: read the file: `config.yaml`.", "next:"), + ("Next: check the logs with `grep`.", "next:"), + # Confirmation review: comparing with an earlier run is a look. + ("Next: compare with the previous run.", "next:"), + ("Next: compare it with the baseline.", "next:"), +] + +#: Replies that end the turn as they are. +MUST_NOT_TRIGGER = [ + # ── Offers, sign-offs, questions, finished work ───────────────────── + "I'll be here if you need anything.", + "All three actions are listed above. Let me know if you want them as a table.", + "I've finished the refactor and the tests pass.", + "I'll wait for your answer before touching the database.", + "Next I'll delete the old branch. Is that okay?", + "Which folder should I use? I'll start once you confirm.", + "Done. If you'd like, I'll open a pull request.", + "That's the fix. I'll keep that in mind for the rest of this project.", + "Understood \u2014 from now on I'll use British spelling.", + "The summary is above. Happy to dig into any of it.", + "You'll find the report in docs/. It will refresh nightly.", + "Next steps:\n1. Run the migration\n2. Deploy to staging", + "The script now retries twice. In production you will want a longer timeout.", + "I will not change the public API; the patch only touches the parser.", + "Everything I'll need is already in the repo, and the work is complete.", + "That's all done. I'll stop here.", + "When you're ready, I'll run the release.", + "I can't reach the server. Once you share the new address, I'll retry.", + "Now I'll explain the result. The cache was stale. Rebuilding it fixed the test. " + "All 214 tests pass.", + "Yes, the job finished at 10:42 with no errors.", + "", + "I've sent the draft. I'll also be available tomorrow.", + "Done. I'll let you decide.", + "The fix is in; let me summarize the changes:\n- the pager\n- its tests", + "Let me explain: the cache was stale, and rebuilding it fixed the test.", + "This will take a moment.", + "If anything breaks, I'll fix it.", + "The report is final. I'll wrap up.", + "I'm done here, so I'll leave it there.", + "Now I'll summarize what changed.", + "I'll let you know when the nightly run finishes.", + # ── Hand-backs and permission asks ────────────────────────────────── + 'Reply "yes" and I\'ll run it.', + 'Reply "yes" and I\'ll run it now.', + "I'll run it after your go ahead.", + "I'll run it now, after your go-ahead.", + "The script is ready. I'll run it with your permission.", + "Next I'll delete the cache, with your permission.", + "Pick an option and I'll implement it.", + "Two options are above. Pick one and I'll implement it next.", + "Send me the log file and I'll look at it next.", + "Paste the error here, then I'll dig in.", + "Choose A or B; I'll apply it right after that.", + "A quick yes and I'll push it now.", + "Merge the branch and I'll tag the release next.", + "Say the word and I'll start now.", + "Just say go and I'll run it now.", + "If you approve, I'll apply the patch now.", + "Once approved, I'll deploy it next.", + "I need your approval first. Then I'll deploy.", + "I'll need your API key before the next step.", + "I'm still working on it, but I'll need your password to go on.", + "Once you confirm the path, next I'll copy the files.", + "When you've reviewed the plan, I'll start on it right after that.", + "Tell me which one and I'll do it now.", + "Can you share the config? Next I'll compare it.", + "Please restart the server. After that I'll run the check.", + "The migration drops a column. Should I go on? Then I'll run it.", + "Do you want me to continue now", + "I can push now if you like.", + "Reply with 1 or 2:\n\n1. Rebase\n2. Merge\n\nThen I'll do it.", + "Grant access to the folder, and I'll index it next.", + "Your move. Then I'll continue.", + "Once I have the key, next I'll upload it.", + "Pending approval, I'll deploy next.", + "Answer the question above so I can continue; then I'll run it.", + "Either option works; you choose. Then I'll build it.", + "Next, you should run the migration; then I'll verify.", + "I'll proceed once I hear back, and then I'll deploy.", + "Hold on until the owner agrees; after that I'll merge.", + "I'll defer to you now.", + "Right now I'll have to decline.", + "I'll be quiet now.", + "I'll now end this session.", + "I'm going to sign off now.", + "Goodbye, I'll go now.", + "We'll see. Now I will rest.", + "I'll treat that as the rule now.", + "Thank you! I'll take that into account now.", + # ── Bare acknowledgements and habits ──────────────────────────────── + "Understood. I'll use tabs.", + "Understood. I'll use tabs from now on.", + "Got it \u2014 I'll keep the answers short.", + "Sure, I'll skip the tests.", + "Okay, I'll call it `parser_v2`.", + "Noted. I will avoid force pushes.", + "Will do. I'll stick to British spelling.", + "Okay then, I'll use the second layout.", + "All right, I'll go with your first idea then.", + "Thanks for the correction. I'll treat it as final.", + "Of course. I'll remember that now.", + "Sure thing, I'll do that next time.", + "Makes sense. I'll leave the file alone for now.", + "Fine by me, I'll proceed that way.", + "Absolutely, I'll continue in Spanish.", + # ── Offers of availability and talk ───────────────────────────────── + "I'll answer any follow-up questions.", + "Now I'll answer any questions you have.", + "Let me add one caveat: the numbers are estimates.", + "Let me now be clear: nothing was deleted.", + "Next I'll be around to review whatever comes back.", + "I'm happy to take the next step now.", + "Feel free to ask; I'll be ready then.", + "I'll need about ten minutes next time.", + "I'll review the next release notes when they exist.", + "I'll keep an eye on it in the future.", + "I'll look at it again next week.", + # ── Summaries and status ──────────────────────────────────────────── + "Everything is working now.", + "Logging now works as expected.", + "All 40 tests are passing now.", + "Passing now.", + "Building now takes two minutes instead of nine.", + "Testing is complete now.", + "Nothing else is running now.", + "The page loads correctly now, and the cache is warm.", + "The bug is fixed. I'll note the cause: a stale lock.", + "Done: the exporter handles empty rows now.", + "I ran the next job and it passed.", + "Before this change, the next run failed. Now it succeeds.", + "The worker restarts cleanly now, so I'm finished.", + "Summary:\n- parser fixed\n- docs updated\n- nothing left to do", + "The release is tagged. Next up for the team: the changelog.", + "Moved the settings. The app reads them from the new path now.", + "The file is parsed and tested.\n\n## Next steps", + "Done.\n\n### Moving on to the parser", + # ── Drafted messages ──────────────────────────────────────────────── + "Here's a draft email:\n\nSubject: Status\n\nHi Sam,\n\nNext I'll send you the figures.", + "Hi Sam,\n\nThe build is green. Next I'll ship it.\n\nBest,\nAlex", + "Here is the reply you can send:\n\nThanks for waiting. I'll check the account now.", + "Draft:\n\nI'm still working on the contract and will send it Friday.", + "Subject: Delay\n\nNow I will review the invoice and respond.", + "I wrote the note below.\n\nDear team,\n\nI'll now take over the rota.\n\nRegards,\nKim", + "Next I'll send this email:\n\nHello Ana,\n\nThe files are attached.", + "Running the export now.\n\nThanks,\nJo", + "You could send this:\n\nI'm running the numbers now.", + # ── Quoted text and code ──────────────────────────────────────────── + 'The email you pasted says: "I\'ll send the contract tomorrow."', + 'Here is the command:\n\n```bash\necho "Next I\'ll deploy"\n```', + "The log line reads 'next i'll retry' and nothing follows it.", + "Her message was 'Now I will restart the node.'", + "The ticket says \u2018I\u2019m still working on it\u2019.", + "The banner text is \u201cRunning the tests now.\u201d", + "The status string is `Next I'll sync`.", + "> Next I'll migrate the table.\n\nThat was the earlier plan; it is done.", + "The transcript ends like this:\n\n next i'll rebuild the index", + 'They wrote:\n"Now I will check.\nThen I will report."', + "| step | note |\n| --- | --- |\n| 1 | next i'll verify |", + # ── Spanish ───────────────────────────────────────────────────────── + "El valor es 3. Eso es todo lo que haré.", + "Aquí estaré si necesitas algo más.", + "Listo. Avísame si quieres que lo exporte.", + "Esperaré tu respuesta antes de continuar.", + "Voy a borrar la rama antigua, ¿te parece bien?", + "He terminado la revisión y todas las pruebas pasan.", + "Si quieres, prepararé un resumen.", + "De ahora en adelante usaré fechas ISO.", + "Dime cuál prefieres y seguiré con esa opción.", + "El informe está en la carpeta docs. Se actualizará cada noche.", + "Cuando me confirmes el nombre, continuaré.", + "Pásame el archivo y lo revisaré.", + "Pasame el archivo y ahora lo revisaré.", + "Perfecto, así lo haré.", + "Entendido, usaré tabulaciones.", + "Claro, lo haré así desde ahora en adelante.", + "Desde luego, lo haré.", + "Vale, haré el resumen más corto.", + "Elige una opción y después la implementaré.", + "Confírmame la ruta y luego copiaré los archivos.", + "Envíame el registro; después lo analizaré.", + "Si me das permiso, ahora voy a desplegarlo.", + "Cuando me pases la clave, continuaré con el resto.", + "Con tu permiso, ahora voy a borrar la caché.", + "Lo ejecutaré después de tu aprobación.", + "¿Quieres que siga? Después generaré la tabla.", + "Di que sí y lo haré ahora.", + "Avisa cuando esté listo y después lo probaré.", + "Necesito la contraseña; luego continuaré.", + "Una vez aprobado, ahora voy a desplegarlo.", + "Tú dirás. Luego lo haré.", + "Queda a tu elección; después lo implementaré.", + "En cuanto lo confirmes, ahora voy a hacerlo.", + "Ahora no haré nada más.", + "Déjame saber cuál y luego lo haré.", + "Contestaré cualquier duda después.", + "Déjame añadir una advertencia: las cifras son estimadas.", + "Ahora voy a explicarte el resultado.", + "Por ahora lo dejaré como está.", + "Hasta luego, estaré pendiente.", + "Ahora todo funciona correctamente.", + "Lo siguiente es lo que encontré: dos archivos duplicados.", + "Lo revisaré la próxima vez.", + "Aquí tienes el borrador del correo:\n\nHola Ana:\n\nAhora voy a revisar tu pedido.", + "Hola Luis,\n\nA continuación voy a enviarte las cifras.\n\nUn saludo,\nMarta", + "El mensaje dice «ahora voy a reiniciar el nodo».", + # ── "Next:" and "remaining work" that are the person's, or nothing (TD-5437) ── + "Next: send me the FCC ID from the back label.", + "Next: you'll need to approve the change.", + "Done.\n\nNext: your call on which camera to buy.", + "Next: if you want, I can add the camera.", + "Next: nothing, it's all done.", + "Next: none. Everything passed.", + "Next time: I'll remember that.", + "Next steps for you: install the camera and connect it to Wi-Fi.", + "The prompt template says 'Next: run the tests'.", + "The remaining work is yours: install the camera.", + "The remaining work is up to you.", + "Next: pick an option and I'll implement it.", + "Próximo paso: pásame la foto de la etiqueta.", + "Siguiente paso: dime qué cámara prefieres.", + # A step a person owns (TD-5437 review): shipping, deciding, anything + # that cannot be undone, or a step that names the person. + "Done \u2014 PR #123 is open and CI is green.\n\nNext: merge it once CI passes.", + "All tests pass.\n\nNext: deploy to production.", + "The fix is pushed to the branch.\n\nNext: review and merge the PR.", + "Next: decide between option A and option B.", + "Next: you can merge the PR.", + "Next: the user needs to restart the app.", + "Done.\n\nNext: the owner to review.", + "Next: your review.", + "**Next:** release notes (yours)", + "Next: I'd suggest adding a cache.", + "**Next:** two options:\n- Ship as is\n- Add caching first", + "The remaining step is to approve and merge the PR.", + "Next: `gh pr merge 123` to merge it.", + "Next: restart the app to load it.", + "Next: push the branch and open the PR.", + "Vision is on for the fast tiers. Next: enable it on the local tiers, then restart the app.", + # A status list, not a step. + "## Status\n\n- Done: parser fix\n- Next: release notes", + "Here's where things stand.\n\n- Done: parser fix\n- Next: run the release checks", + # Nothing left, or not work at all. + "Next: no further action needed.", + "Next: not needed.", + "Next: all set.", + "Next: TBD", + "Siguiente paso: no hay nada más.", + "The remaining work is nothing major.", + "The remaining work is being tracked in the backlog.", + "The remaining work is being handled by the other session.", + "The remaining work is something only you can do.", + "The remaining work is during the maintenance window on Friday.", + "The remaining work is waiting on the vendor's API key.", + "The remaining work is to be done by the design team.", + # Review round 2: what a person owns anywhere after the "Next" line's + # paragraph starts, inside code or quotes too, in any form or language. + "Next: run `gh pr merge 123`.", + "Next: run `git push origin main`.", + "Next: run `npm publish`.", + "Next: run `kubectl rollout restart deploy/api`.", + 'Next: run the "deploy" script.', + "Next: run this:\n\n```\ngit push --force\n```", + "Next: run the smoke tests on staging. If they pass, merge the PR.", + "Next: run the smoke tests on staging. Then merge and deploy to production.", + "Ready to merge. Next: check CI once more.", + "Next: run the migration on production.", + "Next: run the deletion job on prod.", + "Next: verify the build before merging.", + "Next: update the changelog before releasing.", + # A migration is the person's to run, even on a copy: a miss, the safe side. + "**Next:** rerun the migration on a copy of the database.", + "Próximo paso: ejecutar el despliegue a producción.", + "Siguiente paso: revisar y fusionar el PR.", + "Siguiente paso: actualizar y reiniciar el servidor.", + "Siguiente paso: abrir el PR y aprobarlo.", + "Siguiente paso: ejecutar la migración en producción.", + "Siguiente paso: comprobar y publicar la versión.", + "Siguiente paso: revisar el informe y enviárselo al cliente.", + # Addressed to the person. + "Next: update your password", + "Next: enable 2FA in your account settings", + "Next: configure DNS at your registrar", + "Next: check your inbox for the code.", + "Next: test it in your browser.", + "Next: try it yourself.", + "Siguiente paso: actualizar tu contraseña.", + "Next: open the PR and click the green button.", + "Next: add the API key to the vault", + # A list item, even with a line after it. + "## Status\n\n- Done: parser fix\n- Next: run the release checks\n\nThat's it for today.", + # TD-5437 counts a "Next" line only for a read-only or diagnostic step. + # A step that changes something is left to the model: a miss on purpose. + ( + "I found `vision: true` on the fast tiers and `vision: false` on the local tiers. " + "Next: enable `vision: true` on the local brain, worker, and validator tiers." + ), + "Próximo paso: corregir el paginador.", + ( + "The relay is configured. The remaining work is ensuring the camera feeds actually " + "reach those vision tools reliably." + ), + "Two files are done. The remaining step is to update the index.", + "Next: debug the worker's socket timeout.", + "The remaining work is debugging the socket timeout.", + "Next: re-run the import.", + "Next: start the dev server and load the page.", + "Next step - fix the parser's date handling.", + "The only remaining step is to update the index.", + # Review round 3: a fenced block, shipping, live changes, money, messages, + # and steps only the person can take. + "Next: run the build, then deploy it to Vercel.\n\n```\nnpx next build\n```", + "Next: check the logs, then deploy.\n\n```js\napp.use((req, res, next) => next())\n```", + "- Next: run the release checks\n\n```\nnext build\n```", + "Next: build and upload the app to TestFlight.", + "Next: run `twine upload dist/*`.", + "Next: `terraform apply` to update the DNS records.", + "Next: run `helm upgrade api ./chart`.", + "Next: update the live site with the new prices.", + "Next: run `shutdown -r now`", + "Next: run `systemctl stop nginx`", + "Next: `systemctl stop nginx` to check the port.", + "Next: run `docker system prune -a`", + "Next: `git clean -fdx` to rebuild", + "Next: add the camera to the cart and check out.", + "Next: retry the checkout.", + "Next: run the refund script for the order.", + "Next: wire the funds to the contractor.", + "Next: write the reply to Ana and mail it.", + "Next: open Settings and turn on Developer Mode.", + "Next: add the key to the .env file.", + "Next: run the setup wizard and follow the prompts.", + "Next: call the bank about the charge.", + "Next: update the DNS record at Cloudflare.", + "Siguiente paso: revisar los cambios antes de la fusión.", + "Siguiente paso: revisar el borrador. Luego publícala.", + "Next: `curl -X POST https://api.example.com/deploy` to check it.", + "Next: check out the release branch.", + # Review round 4: a second action, writing or chained code, context above. + "Next: inspect the VM and terminate it", + "Next: check the old instances and destroy them", + "Next: query the users table and purge stale rows", + "Next: audit the IAM roles and revoke the unused ones", + "Next: check the stuck worker and kill it", + "The next step is to verify the order and charge the card", + "Next: test the charge endpoint against the live Stripe API", + "Next: test the SMS alert by texting the on-call number", + "Next: `cat install.sh | sh`", + "Next: `grep -rl foo . | xargs rm`", + "Next: `ls && terraform apply`", + "Next: `git status && git commit -am wip`", + "Next: `cat /dev/null > app.db`", + "Next: `git status`, then `terraform apply`.", + "Note: `ls` works. Next: `terraform apply`.", + "Next: verify with `terraform apply`", + "Next: verify via `aws s3 rm s3://bucket --recursive`", + "Next: test it by running `stripe charges create --amount 5000`", + "Next: `git log && git push`", + "Next: `ls; rm -rf x`", + "Next: `gh pr view 1 --json state; gh pr merge 1`", + "PR #12 is open and ready to merge.\n\nNext: check the CI run.", + "Next: deploy the fix to production.\n\nNext: check the logs.", + "Next: `terraform apply` to update DNS.\nThe remaining step is to check the logs.", + "Next: check the cron job and fix it", + "Next: check this:\n\n```\ncat x | sh\n```", + "Next: 'cleanup.sh' to check it", + # Review round 5: one action to the end of the reply, any separator or purpose + # clause; bare commands; snake_case names; contacting someone. + "Next: check disk usage. If it's over 90%, clear the old logs.", + "Next: check the VM. Then stop it.", + "Next: check the logs. After that, stop the old worker.", + "Next: inspect the cert to renew it.", + "Next: query the users table to clear stale sessions.", + "Next: find the stale branches to clean them up.", + "Siguiente paso: revisar la VM para apagarla.", + "Next: check the VM — stop it if idle.", + "Next: check the cache: clear it if stale.", + "Next: inspect the VM & stop it.", + "Next: verify the config and/or update it.", + "Next: `make` to check the build.", + "Next: `./cleanup` to check disk.", + "Next: `rm` the stale lock to check.", + "Next: `poweroff`", + "Next: verify with `./apply.sh`.", + "Next: test it by running `./cleanup.sh`.", + "Next: `./scripts/prod_deploy.sh` to check it.", + "Next: `./apply_migrations.sh` to check the schema.", + "Next: test `send_email.py` with the client list.", + "Next: check with the vendor about the lead time.", + "Next: verify the numbers with Ana.", + "Siguiente paso: consultar con el abogado.", + "Next: map the custom domain to the Vercel project.", + "Next: list the camera on eBay for $300.", + "Next: test the alert by paging the on-call engineer.", + "Next: reproduce the bug by placing a test order on the live store.", + "Next: run the benchmarks on a fresh p4d instance.", + "Next: check this:\n\n cat x | sh", + "Next: run these checks:\n\n- `git status`\n- `sudo apt-get upgrade -y`", + "Next: `sort -o f f` to check the order.", + "Next: `rg --pre ./x.sh foo` to find it.", + ( + "Next: look at the earlier notes.\n\nThe config looks wrong… " + "Next: `sed -i s/a/b/ app.yaml` to check it." + ), + 'Next — "./cleanup.sh" to check the disk.', + ( + "Next: Inspect `~/.local/share/app-runs` and the current records to recover what " + "remains of the tooling and determine the safest step." + ), + # Review round 6: contacting someone, a second action, a script or a write, + # a cloud machine, an indented line after the lead. + "Siguiente paso: consultar con el médico.", + "Próximo paso: consultar con el asesor fiscal.", + "Siguiente paso: consultar a Ana.", + "Next: check with my lawyer.", + "Next: check with a vendor about the lead time.", + "Next: check with the airline.", + "Next: check the dependency versions and pin them.", + "Next: check the build and if it fails revert the commit.", + "Next: check the cert and if expired renew it.", + "Next: find-and-replace the old API name across the repo.", + "Next: check in the fix.", + "Next: run the tests and check in the fix.", + "Next: inspect the plan and 'apply' it.", + "Next: `bin/setup`.", + "Next: `scripts/install.sh`.", + "Next: run the benchmarks on a new VM.", + "Next: run the benchmarks on a fresh GPU instance.", + "Next: profile the model on a spot instance.", + "Next: test the Slack webhook.", + "Next: test the Stripe integration with a real card.", + "Next: `git diff --output=f` to check it.", + "Next: `terraform apply` to check the plan.\n\n next if line.empty?", + "Next: check this:\n\n cat x | sh\n next", + "Next: `echo $(whoami)` to check it.", + "Hi Ana,\nNext week works.\n---", + # Review round 7: pages to a person, anyone after "with", rewriting tools, + # a script after a join, a paging service. + "Next: test a page to the SRE on duty.", + "Next: test the pages to the SRE rotation.", + "Next: test the alert pages.", + "Next: test the page to the secondary on call.", + "Next: check with the plumber.", + "Next: check with my wife.", + "Next: check with the upstream maintainers.", + "Next: verify the dates with the hotel.", + "Siguiente paso: verificar con el fontanero.", + "Next: run ruff --fix on the module.", + "Next: run ruff format.", + "Next: run pytest --snapshot-update.", + "Next: `ls` then `scripts/setup.sh`.", + "Next: test the PagerDuty alert.", + # Confirmation review: a group named with a data word is still people. + "Next: check with the data team.", + "Next: check with the page owner.", + "Next: check with the python maintainers.", + "Next: verify the schema with the test team.", +] + + +@pytest.mark.parametrize(("reply", "phrase"), MUST_TRIGGER) +def test_an_announced_next_step_is_found(reply: str, phrase: str) -> None: + assert announced_next_step(reply) == phrase + + +@pytest.mark.parametrize("reply", MUST_NOT_TRIGGER) +def test_offers_sign_offs_and_finished_replies_are_left_alone(reply: str) -> None: + assert announced_next_step(reply) is None + + +def test_every_listed_phrase_matches_on_its_own() -> None: + for phrase in PHRASES: + assert announced_next_step(f"Done so far. {phrase} the rest.") is not None, phrase + + +def test_the_match_is_never_more_than_the_marker() -> None: + found = announced_next_step("I'll email the quarterly figures to the board now.") + assert found == "i'll" + + +def test_no_reply_is_listed_twice() -> None: + replies = [reply for reply, _ in MUST_TRIGGER] + MUST_NOT_TRIGGER + assert len(replies) == len(set(replies)) + + +@pytest.mark.parametrize( + "reply", + [ + "The migration is ready. Reply 'yes' and I'll run it.", + "Say yes and I'll apply the patch.", + "Confirm and I'll push the branch.", + "With your approval I'll delete the old logs.", + "Do you want me to proceed? I'll run it next.", + "Responde 'sí' y lo ejecuto ahora.", + "Con tu aprobación voy a borrar los registros.", + ], +) +def test_a_permission_ask_never_triggers(reply: str) -> None: + """TD-5428 review: a hand-back waits for the person, it is never nudged.""" + assert announced_next_step(reply) is None diff --git a/core/tests/test_follow_through_loop.py b/core/tests/test_follow_through_loop.py new file mode 100644 index 00000000..38a015a7 --- /dev/null +++ b/core/tests/test_follow_through_loop.py @@ -0,0 +1,519 @@ +"""The follow-through check in the agent loop (TD-5428). + +An interactive turn whose reply makes no tool call but announces a next +step is asked once to carry on, with the progress guard's labels. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +from pathlib import Path + +import pytest + +from tests.test_cap_enforcement import make_echo_session +from tests.test_delegate import _parent_dispatcher, _workspace +from tests.test_dispatch import make_config, start_loop, wait_for_turn +from tests.test_progress_guard import _brain_calls, _deltas, _pause_reason +from tstd.boundary_config import BoundaryConfig, CapsSection +from tstd.mock import MockProvider, Script +from tstd.progress_guard import ( + CONTINUE_INSTRUCTION, + FOLLOW_THROUGH_INSTRUCTION, + MAX_AUTO_CONTINUES, + TOOL_WINDOW, + ProgressGuard, + interpret_check, +) +from tstd.protocol import ( + FOLLOW_THROUGH_REPLACED, + AssistantDelta, + AssistantRetract, + ToolCall, + TurnComplete, +) +from tstd.provider import ChatCompletionRequest +from tstd.reply_retry import shown_deltas +from tstd.router import TierRouter +from tstd.session import Session, SessionRunner + +ANNOUNCES = "I've read the notes. Next I'll extract the unfinished actions." +AGAIN = "Almost there. Now I will group them by owner." + + +def _say(text: str, **extra: object) -> Script: + return Script(kind="stream", content=text, **extra) # type: ignore[arg-type] + + +def _echo(message: str, narration: str = "") -> Script: + return Script( + kind="tool_call", + tool_name="echo", + tool_arguments=json.dumps({"message": message}), + narration=narration, + ) + + +async def _run( + tmp_path: Path, + *scripts: Script, + autonomy: bool = False, + skip_all: bool = False, + delegate: bool = False, + caps: CapsSection | None = None, +) -> tuple[Session, MockProvider, SessionRunner]: + boundary = BoundaryConfig() if caps is None else BoundaryConfig(caps=caps) + session, dispatcher = make_echo_session(tmp_path, boundary) + session.autonomy = autonomy + session.delegate_depth = 1 if delegate else 0 + if skip_all: + dispatcher.skip_all_fn = lambda: True + mock = MockProvider(sequences={"test-brain": list(scripts)}, default=_say("unscripted")) + runner = await start_loop( + session, TierRouter(lead_turns=80), mock, make_config(), dispatcher.registry, dispatcher + ) + await session.add_user_message("extract the open actions") + return session, mock, runner + + +def _asked(mock: MockProvider, instruction: str = FOLLOW_THROUGH_INSTRUCTION) -> list[int]: + """The brain calls whose request ends on *instruction*.""" + calls: list[ChatCompletionRequest] = _brain_calls(mock) # type: ignore[assignment] + return [i for i, call in enumerate(calls) if call.messages[-1].content == instruction] + + +def _turns(session: Session) -> list[TurnComplete]: + return [e for e in session.event_log.all_events if isinstance(e, TurnComplete)] + + +def _shown(session: Session) -> str: + """What the chat shows: the deltas no retract took back.""" + return "".join(shown_deltas(session.event_log.all_events)) + + +def _retracts(session: Session) -> list[AssistantRetract]: + return [e for e in session.event_log.all_events if isinstance(e, AssistantRetract)] + + +def _tool_calls(session: Session) -> list[ToolCall]: + return [e for e in session.event_log.all_events if isinstance(e, ToolCall)] + + +async def _finish(session: Session, runner: SessionRunner, count: int = 1) -> TurnComplete: + turn = await wait_for_turn(session, count, 8.0) + await runner.cancel() + assert isinstance(turn, TurnComplete) + return turn + + +async def test_continue_then_a_tool_call_carries_the_same_turn_on(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, + _say(ANNOUNCES), + _say("CONTINUE: echo the actions"), + _echo("actions"), + _say("Three actions are open."), + ) + turn = await _finish(session, runner) + calls = _brain_calls(mock) + assert len(calls) == 4 + assert _asked(mock) == [1] + nudge, resumed = calls[1], calls[2] + assert nudge.tools is None # type: ignore[attr-defined] + assert resumed.tools # type: ignore[attr-defined] + last = resumed.messages[-1] # type: ignore[attr-defined] + assert (last.role, last.content) == ("user", CONTINUE_INSTRUCTION) + assert [c.name for c in _tool_calls(session)] == ["echo"] + assert len(_turns(session)) == 1 + assert turn.stopped_after_continue is False + assert turn.failed is False + assert f"{ANNOUNCES}\n\nNext: echo the actions\n\n" in _deltas(session) + # The stored nudge and its follow-up belong to the turn and are no user turn. + added = [m for m in session.conversation if m.role == "user"][1:] + assert [m.content for m in added] == [FOLLOW_THROUGH_INSTRUCTION, CONTINUE_INSTRUCTION] + assert all(m.steer and m.check for m in added) + + +async def test_a_tool_call_with_no_label_carries_on_and_runs_once(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, + _say(ANNOUNCES), + _echo("too early", narration="Reading them."), + _echo("actions"), + _say("Three actions are open."), + ) + turn = await _finish(session, runner) + # The call made with tools off is not run; the next one is. + assert [c.arguments for c in _tool_calls(session)] == [{"message": "actions"}] + assert _asked(mock) == [1] + assert turn.stopped_after_continue is False + roles = [m.role for m in session.conversation if m.role != "system"] + assert roles == ["user", "assistant", "user", "assistant", "tool", "assistant"] + + +async def test_done_replaces_the_reply_on_one_bubble(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, _say(ANNOUNCES), _say("DONE: Three actions are open.") + ) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 2 + assert turn.stopped_after_continue is False + assert turn.failed is False + # The reply is taken back and the answer is the reply: no second copy. + assert _shown(session) == "Three actions are open." + (retract,) = _retracts(session) + assert retract.reason == FOLLOW_THROUGH_REPLACED + first = next(e for e in session.event_log.all_events if isinstance(e, AssistantDelta)) + assert retract.response_id == first.response_id is not None + # The saved conversation holds the answer in the reply's place and no nudge. + assistant = [m.content for m in session.conversation if m.role == "assistant"] + assert assistant == ["Three actions are open."] + assert all(m.content != FOLLOW_THROUGH_INSTRUCTION for m in session.conversation) + assert session.conversation[-1].role == "assistant" + assert _pause_reason(session) == "" + + +async def test_blocked_adds_what_it_needs_under_the_reply(tmp_path: Path) -> None: + session, _mock, runner = await _run( + tmp_path, _say(ANNOUNCES), _say("BLOCKED: which folder holds the notes?") + ) + turn = await _finish(session, runner) + assert turn.stopped_after_continue is False + assert _retracts(session) == [] + assert _shown(session) == f"{ANNOUNCES}\n\nwhich folder holds the notes?\n\n" + assert session.conversation[-1].content == "which folder holds the notes?" + + +async def test_blocked_that_says_the_reply_again_replaces_it(tmp_path: Path) -> None: + session, _mock, runner = await _run( + tmp_path, _say(ANNOUNCES), _say(f"BLOCKED: {ANNOUNCES} Which folder?") + ) + await _finish(session, runner) + assert _shown(session).count("extract the unfinished actions") == 1 + assert [m.content for m in session.conversation if m.role == "assistant"] == [ + f"{ANNOUNCES} Which folder?" + ] + + +@pytest.mark.parametrize( + "answer", ["The notes are in the shared folder.", "Nothing else to do.", AGAIN] +) +async def test_an_answer_with_no_label_keeps_the_reply_and_marks_it( + tmp_path: Path, answer: str +) -> None: + """Review round 2: an unlabelled answer never stands in for the reply or sits under it.""" + session, mock, runner = await _run(tmp_path, _say(ANNOUNCES), _say(answer)) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 2 + assert turn.stopped_after_continue is True + assert _shown(session) == ANNOUNCES + assert [m.content for m in session.conversation if m.role == "assistant"] == [ANNOUNCES] + + +async def test_a_done_answer_that_still_announces_a_step_is_shown_and_marked( + tmp_path: Path, +) -> None: + session, mock, runner = await _run(tmp_path, _say(ANNOUNCES), _say(f"DONE: {AGAIN}")) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 2 + assert turn.stopped_after_continue is True + assert _shown(session) == AGAIN + + +@pytest.mark.parametrize( + "answer", + [ + _say(""), + _say("CONTINUE:"), + Script(kind="error", status_code=400, error_code="bad_request"), + ], + ids=["empty", "no-step", "error"], +) +async def test_a_model_that_still_stops_keeps_the_reply_and_marks_it( + tmp_path: Path, answer: Script +) -> None: + session, mock, runner = await _run(tmp_path, _say(ANNOUNCES), answer) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 2 + assert turn.stopped_after_continue is True + assert turn.failed is False + assert _shown(session) == ANNOUNCES + assert _retracts(session) == [] + assert _pause_reason(session) == "" + + +async def test_the_next_turn_may_be_asked_again(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, + _say(ANNOUNCES), + _say("DONE: first"), + _say(AGAIN), + _say("DONE: second"), + ) + await wait_for_turn(session, 1, 8.0) + await session.add_user_message("and the rest") + await _finish(session, runner, 2) + assert _asked(mock) == [1, 3] + + +@pytest.mark.parametrize( + "reply", + ["I'll be here if you need anything.", "Three actions are open.", "Shall I group them?"], +) +async def test_a_reply_that_announces_nothing_gets_no_nudge(tmp_path: Path, reply: str) -> None: + session, mock, runner = await _run(tmp_path, _say(reply)) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 1 + assert turn.stopped_after_continue is False + + +async def test_skip_all_is_still_checked(tmp_path: Path) -> None: + """The manager's correction: approvals off is the owner's own setting.""" + session, mock, runner = await _run(tmp_path, _say(ANNOUNCES), skip_all=True) + await _finish(session, runner) + assert len(_brain_calls(mock)) >= 2 + + +@pytest.mark.parametrize("kind", ["autonomy", "delegate"]) +async def test_autonomy_and_children_are_never_checked(tmp_path: Path, kind: str) -> None: + session, mock, runner = await _run(tmp_path, _say(ANNOUNCES), **{kind: True}) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 1 + assert turn.stopped_after_continue is False + + +async def test_a_real_delegate_worker_is_not_checked(tmp_path: Path) -> None: + ws = _workspace(tmp_path) + session = Session(str(ws)) + dispatcher = _parent_dispatcher(ws) + mock = MockProvider( + sequences={ + "test-brain": [ + Script( + kind="tool_call", + tool_name="delegate", + tool_arguments='{"task": "Read notes.md"}', + ), + _say("The worker answered."), + ], + "test-worker": [Script(kind="text", content=ANNOUNCES)], + } + ) + runner = await start_loop( + session, TierRouter(), mock, make_config(), dispatcher.registry, dispatcher + ) + await session.add_user_message("Delegate the read") + await _finish(session, runner) + assert len([c for c in mock.calls if c.model == "test-worker"]) == 1 + assert all(m.content != FOLLOW_THROUGH_INSTRUCTION for c in mock.calls for m in c.messages) + + +async def test_a_reached_cap_marks_the_reply_without_another_call(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, _say(ANNOUNCES), caps=CapsSection(max_iterations=1) + ) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 1 + assert turn.stopped_after_continue is True + + +async def test_stop_during_the_nudge_ends_the_turn_as_stopped(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, _say(ANNOUNCES), _say("DONE: never shown", chunk_delay=0.5) + ) + for _ in range(400): + if _asked(mock): + break + await asyncio.sleep(0.01) + assert _asked(mock) == [1] + await session.stop_turn() + turn = await _finish(session, runner) + assert turn.error_code == "stopped" + assert turn.stopped_after_continue is False + assert "never shown" not in _deltas(session) + + +async def test_each_match_is_logged_with_its_phrase( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.INFO, logger="tstd.follow_through"): + session, _mock, runner = await _run(tmp_path, _say(ANNOUNCES), _say(AGAIN)) + await _finish(session, runner) + found = [ + r.__dict__["extra_fields"] + for r in caplog.records + if r.getMessage() == "reply announces a next step" + ] + assert [(f["phrase"], f["nudge"]) for f in found] == [("next i'll", True)] + assert "unfinished actions" not in str(found) + + +# ── The counter shared with the progress guard ─────────────────────────── + + +def _windows(count: int) -> list[Script]: + """*count* full tool windows, each answered CONTINUE by the progress check.""" + scripts: list[Script] = [] + for window in range(count): + scripts.extend(_echo(f"read-{window}-{i}") for i in range(TOOL_WINDOW)) + scripts.append(_say(f"CONTINUE: read batch {window}")) + return scripts + + +# ── The progress check's own unlabelled answer ─────────────────────────── + + +async def test_an_unlabelled_progress_answer_is_followed_through(tmp_path: Path) -> None: + reads = [_echo(f"read-{i}") for i in range(TOOL_WINDOW)] + session, mock, runner = await _run( + tmp_path, *reads, _say(ANNOUNCES), _say("DONE: Three actions are open.") + ) + turn = await _finish(session, runner) + assert _asked(mock) == [TOOL_WINDOW + 1] + assert turn.stopped_after_continue is False + # The progress check's own answer is replaced too, not shown twice. + assert _shown(session).endswith("Three actions are open.") + assert ANNOUNCES not in _shown(session) + assert len(_retracts(session)) == 1 + assert [m.content for m in session.conversation if m.role == "assistant"][-1] == ( + "Three actions are open." + ) + + +async def test_an_unlabelled_progress_answer_that_still_stops_is_marked(tmp_path: Path) -> None: + reads = [_echo(f"read-{i}") for i in range(TOOL_WINDOW)] + session, _mock, runner = await _run(tmp_path, *reads, _say(ANNOUNCES), _say(AGAIN)) + turn = await _finish(session, runner) + assert turn.stopped_after_continue is True + + +async def test_a_labelled_progress_answer_is_taken_as_it_is(tmp_path: Path) -> None: + reads = [_echo(f"read-{i}") for i in range(TOOL_WINDOW)] + session, mock, runner = await _run(tmp_path, *reads, _say(f"BLOCKED: {ANNOUNCES}")) + turn = await _finish(session, runner) + assert _asked(mock) == [] + assert turn.stopped_after_continue is False + + +def test_the_terminal_says_a_reply_was_replaced_not_asked_again() -> None: + from tstd.cli import REPLACED_NOTICE, RETRACT_NOTICE, retract_notice + + assert retract_notice({"reason": FOLLOW_THROUGH_REPLACED}) == REPLACED_NOTICE + assert retract_notice({"reason": "stream_stalled"}) == RETRACT_NOTICE + + +async def test_a_permission_hand_back_ends_the_turn_with_no_nudge_and_no_tool( + tmp_path: Path, +) -> None: + """The manager's case (review round 1): the nudge got CONTINUE and the tool ran with no yes.""" + session, mock, runner = await _run( + tmp_path, _say('Reply "yes" and I\'ll run it.'), _say("CONTINUE"), _echo("ran") + ) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 1 + assert _asked(mock) == [] + assert _tool_calls(session) == [] + assert turn.stopped_after_continue is False + + +LONG_ANNOUNCES = ( + "The report covers every folder. " * 20 + + "That is the full account. Next I'll extract the actions." +) + + +async def test_a_check_cut_off_at_the_token_limit_never_replaces_the_reply( + tmp_path: Path, +) -> None: + session, mock, runner = await _run( + tmp_path, _say(ANNOUNCES), _say("DONE: Everything is", finish_reason="length") + ) + turn = await _finish(session, runner) + assert len(_brain_calls(mock)) == 2 + assert turn.stopped_after_continue is True + assert _shown(session) == ANNOUNCES + assert _retracts(session) == [] + assert [m.content for m in session.conversation if m.role == "assistant"] == [ANNOUNCES] + + +async def test_a_short_unlabelled_answer_never_replaces_a_long_reply(tmp_path: Path) -> None: + session, _mock, runner = await _run(tmp_path, _say(LONG_ANNOUNCES), _say("Okay.")) + turn = await _finish(session, runner) + assert turn.stopped_after_continue is True + assert _shown(session) == LONG_ANNOUNCES + assert _retracts(session) == [] + + +async def test_a_done_that_only_repeats_the_reply_is_not_shown_twice(tmp_path: Path) -> None: + session, _mock, runner = await _run(tmp_path, _say(ANNOUNCES), _say(f"DONE: {ANNOUNCES}")) + turn = await _finish(session, runner) + assert turn.stopped_after_continue is False + assert _shown(session) == ANNOUNCES + assert _retracts(session) == [] + + +def test_the_stopped_short_marker_survives_a_restart(tmp_path: Path) -> None: + """The flag rides on the persisted ``turn_complete`` event: no schema change.""" + from tstd.session_persist import SessionPersist + + persist = SessionPersist(tmp_path) + persist.append_event( + "chat-1", + TurnComplete( + session_id="chat-1", + seq=1, + tokens=1, + cost=0.0, + tier="brain", + duration=0.1, + stopped_after_continue=True, + ), + ) + loaded = SessionPersist(tmp_path).load("chat-1") + assert loaded is not None + assert [e.stopped_after_continue for e in loaded.events if isinstance(e, TurnComplete)] == [ + True + ] + + +# ── No per-turn limit (owner, 2026-12-01: "if there is work still to do it should not stop") ── + + +async def test_a_second_stop_is_nudged_again(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, + _say(ANNOUNCES), + _say("CONTINUE: echo the actions"), + _echo("actions"), + _say(AGAIN), + _say("DONE: All open actions are listed."), + ) + turn = await _finish(session, runner) + assert len(_asked(mock)) == 2 + assert turn.stopped_after_continue is False + + +async def test_spent_progress_windows_do_not_stop_the_nudge(tmp_path: Path) -> None: + session, mock, runner = await _run( + tmp_path, *_windows(MAX_AUTO_CONTINUES), _say(ANNOUNCES), _say("DONE: finished.") + ) + turn = await _finish(session, runner) + assert len(_asked(mock)) == 1 + assert turn.stopped_after_continue is False + + +def test_a_nudge_does_not_spend_the_progress_checks() -> None: + guard = ProgressGuard() + guard.note_follow_through("read the rest") + guard.note_follow_through("write the summary") + assert guard.auto_continues == 0 + assert guard.can_follow_through() + + +def test_the_same_next_step_twice_still_pauses() -> None: + guard = ProgressGuard() + guard.note_follow_through("read the rest") + kind, _ = interpret_check("CONTINUE: read the rest", guard.last_continue) + assert kind == "pause" diff --git a/core/tests/test_follow_through_reported.py b/core/tests/test_follow_through_reported.py new file mode 100644 index 00000000..5988cb33 --- /dev/null +++ b/core/tests/test_follow_through_reported.py @@ -0,0 +1,37 @@ +"""TD-5428's report, as a test that fails without the follow-through check. + +A model ended its turn on "I'm still working ... Next I'll ..." with no +tool call, and the turn was shown as finished. +""" + +from __future__ import annotations + +from pathlib import Path + +from tests.test_dispatch import wait_for_turn +from tests.test_progress_guard import _brain_calls, _request_text, _run +from tstd.mock import Script + +REPORTED_REPLY = ( + "Yes \u2014 I'm still working on it. I've read the meeting notes so far. " + "Next I'll extract the unfinished actions and group them by owner." +) + + +async def test_a_reply_that_says_it_will_continue_is_not_simply_finished( + tmp_path: Path, +) -> None: + session, mock, runner = await _run( + tmp_path, + { + "test-brain": [ + Script(kind="stream", content=REPORTED_REPLY), + Script(kind="stream", content="DONE: Three actions are open."), + ] + }, + ) + await wait_for_turn(session, 1, 8.0) + calls = _brain_calls(mock) + assert len(calls) == 2, "the turn ended as finished on a reply that says it will continue" + assert "Follow-through check" in _request_text(calls[1]) + await runner.cancel() diff --git a/core/tests/test_protocol.py b/core/tests/test_protocol.py index 8a4d3673..3933d573 100644 --- a/core/tests/test_protocol.py +++ b/core/tests/test_protocol.py @@ -950,6 +950,11 @@ def test_turn_complete(self) -> None: assert back.tokens == 1500 assert back.tier == "worker" assert back.duration == 2.5 + # TD-5428, additive: a turn is not marked unless the loop says so. + assert back.stopped_after_continue is False + marked = _roundtrip(evt.model_copy(update={"stopped_after_continue": True})) + assert isinstance(marked, TurnComplete) + assert marked.stopped_after_continue is True def test_error(self) -> None: evt = Error(code="test", message="something went wrong", seq=9) diff --git a/core/tests/test_protocol_parity.py b/core/tests/test_protocol_parity.py index e79d2ab9..8f85558d 100644 --- a/core/tests/test_protocol_parity.py +++ b/core/tests/test_protocol_parity.py @@ -131,3 +131,14 @@ def test_a_runs_start_is_on_both_sides() -> None: for field in ("session_id", "worker_id", "parent_call_id"): assert protocol.WorkerRunStarted.model_fields[field].is_required() assert re.search(rf"^\s+{field}: string;", body.group(1), re.M), field + + +def test_turn_complete_has_the_same_fields_on_both_sides() -> None: + """TD-5428: a field one side lacks is a marker the window never shows.""" + if not _PROTOCOL_TS.is_file(): + pytest.skip("the UI tree is not checked out beside core") + source = _PROTOCOL_TS.read_text(encoding="utf-8") + block = source.split("interface TurnComplete extends DaemonEvent {", 1)[1].split("\n}", 1)[0] + declared = set(re.findall(r"^ (\w+)\??:", block, re.MULTILINE)) + sent = set(protocol.TurnComplete.model_fields) - set(protocol.DaemonEvent.model_fields) + assert declared == sent | {"type"} diff --git a/core/tstd/cli.py b/core/tstd/cli.py index f49fd75c..30766635 100644 --- a/core/tstd/cli.py +++ b/core/tstd/cli.py @@ -37,7 +37,7 @@ from .cli_questions import prompt_questions from .config import DEFAULT_MAX_RUN_SECONDS from .logging import user_data_dir -from .protocol import PROTOCOL_VERSION +from .protocol import FOLLOW_THROUGH_REPLACED, PROTOCOL_VERSION from .provider import RetryConfig, worst_case_retry_seconds from .ws import read_port_file @@ -238,6 +238,14 @@ def _print_error(event: dict[str, Any]) -> None: # Streamed text cannot be taken back off a terminal, so this says why the # reply starts over below it. RETRACT_NOTICE = "(the provider went quiet; the reply above was withdrawn and is being asked again)" +# The follow-through check's answer takes the reply's place (TD-5428). +REPLACED_NOTICE = "(the reply above was replaced by the one that follows)" + + +def retract_notice(event: dict[str, Any]) -> str: + """One line for a response the daemon withdrew.""" + replaced = event.get("reason") == FOLLOW_THROUGH_REPLACED + return REPLACED_NOTICE if replaced else RETRACT_NOTICE def fallback_notice(event: dict[str, Any]) -> str: @@ -277,7 +285,7 @@ def _visible_event_line(event: dict[str, Any]) -> str | None: """One-line TTY form of a user-visible event. Not a JSON dump.""" typ = event.get("type") if typ == "assistant_retract": - return RETRACT_NOTICE + return retract_notice(event) if typ == "model_fallback": return fallback_notice(event) if typ == "stop_check": diff --git a/core/tstd/cli_turn.py b/core/tstd/cli_turn.py index f3876da1..5efb1721 100644 --- a/core/tstd/cli_turn.py +++ b/core/tstd/cli_turn.py @@ -40,7 +40,6 @@ from .cli import ( PLAN_WAITING, - RETRACT_NOTICE, _print_error, _recv_event, _send, @@ -48,6 +47,7 @@ config_trust_notice, fallback_notice, folder_trust_notice, + retract_notice, stop_check_notice, ) from .cli_approvals import prompt_approval @@ -339,16 +339,16 @@ def _worktree(self, event: dict[str, Any]) -> None: print(line, file=sys.stderr) def _withdraw(self, event: dict[str, Any]) -> None: - """The provider stalled partway through a response; the daemon asks again. + """The daemon withdrew a response: it asks again, or replaces it. The response leaves the reply. Text mode already wrote it, and a - pipe cannot take it back, so stderr says the retry follows. + pipe cannot take it back, so stderr says what follows. """ rid = event.get("response_id") self.reply = [(r, text) for r, text in self.reply if r is None or r != rid] if self.output == "text": self.end_line() - print(RETRACT_NOTICE, file=sys.stderr) + print(retract_notice(event), file=sys.stderr) async def _approval(self, ws: Any, event: dict[str, Any]) -> TurnOutcome | None: self.end_line() diff --git a/core/tstd/follow_through.py b/core/tstd/follow_through.py new file mode 100644 index 00000000..0fd46787 --- /dev/null +++ b/core/tstd/follow_through.py @@ -0,0 +1,884 @@ +"""Does a finished reply say the work is still going? (TD-5428) + +A model can end its turn on "Next I'll extract the open actions" and call +no tool. :func:`announced_next_step` finds such a reply, in English and +Spanish, from the reply's text alone. The loop only asks it about a reply +that made no tool call. + +Only the model's own prose is read (``follow_through_text.py``), from its +end. Two ways to match: + +- a still-working or next-step phrase, in the last two sentences of the + last paragraph (:data:`PHRASES`); +- the last sentence is first person and future with a time cue ("I'll run + the tests now", "Luego revisaré los registros"), or says the work is + under way ("Running the tests now"). + +A reply that hands the turn to the person never matches: a request, a +permission ask or a condition on them near the end, or a question. Nor do +bare acknowledgements, offers, standing habits or talk the reply delivers +itself. A missed announcement ends the turn as before, while a false match +sends a finished model back to work, so when in doubt it does not match. +""" + +from __future__ import annotations + +import re + +from .follow_through_text import prose_paragraphs + +#: Phrases that say the work goes on, as folded by the text module. +PHRASES: tuple[str, ...] = ( + # English + "i'm still working", + "i am still working", + "next i'll", + "next, i'll", + "next i will", + "next, i will", + "next i'm going to", + "next, i'm going to", + "now i'll", + "now, i'll", + "now i will", + "now, i will", + "now i'm going to", + "now, i'm going to", + "i'll now", + "i will now", + "i'm now going to", + "let me now", + "let me next", + "i'll keep working", + "i'll keep going", + "i'll continue with the rest", + "i'll continue with the remaining", + "i will continue with the rest", + "i will continue with the remaining", + "moving on to", + # Spanish + "a continuación voy a", + "a continuación, voy a", + "ahora voy a", + "ahora, voy a", + "ahora mismo voy a", + "luego voy a", + "después voy a", + "ahora procedo a", + "ahora déjame", + "déjame ahora", + "sigo trabajando", + "sigo en ello", + "todavía estoy trabajando", + "aún estoy trabajando", + "continuaré con los demás", + "continuaré con el resto", + "seguiré con los demás", + "seguiré con el resto", + "continúo con el resto", +) + +#: Phrases that need more than their words: (reported as, pattern). +_PHRASE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( + # "Still working on the report." with no subject. + ("still working on", re.compile(r"^still working on\b")), + # Only with a verb after it: "lo siguiente es lo que encontré" is a lead-in. + ( + "lo siguiente es", + re.compile(r"(?" (TD-5437) ───────────────────────────────── +# The progress check writes its notes as "Next: ", and models copy the +# form to end a reply that still has a step to take. The same line also ends +# finished replies that leave the step to the person ("Next: merge it once CI +# passes"), and no word list can tell every such step apart. So the line +# counts only when its step is read-only or diagnostic: looking something +# up, running the tests, or a read-only command. A misread then costs a look, +# never a merge, a payment or a deletion. A deny list on the rest of the +# reply, and the nudge's own "answer BLOCKED if the step is the user's", are +# the second and third layers. + +#: Read-only or diagnostic verbs, as the step's first word. +_LOOK_WORK = ( + "analyse", + "analyze", + "audit", + "check", + "compare", + "diff", + "enumerate", + "examine", + "fetch", + "find", + "grep", + "inspect", + "investigate", + "locate", + "look", + "measure", + "parse", + "probe", + "profile", + "query", + "read", + "reproduce", + "scan", + "search", + "test", + "trace", + "verify", +) +_SPANISH_LOOK_WORK = ( + "analizar", + "buscar", + "comparar", + "comprobar", + "examinar", + "inspeccionar", + "investigar", + "leer", + "listar", + "localizar", + "medir", + "rastrear", + "reproducir", + "revisar", + "verificar", +) + + +def _gerunds(verbs: tuple[str, ...]) -> set[str]: + forms: set[str] = set() + for verb in verbs: + forms.add(verb + "ing") + if verb.endswith("e") and not verb.endswith("ee"): + forms.add(verb[:-1] + "ing") + # map -> mapping. An extra form for a verb that does not double + # ("auditting") matches nothing. + if re.search(r"[^aeiou][aeiou][bdgmnpt]$", verb): + forms.add(verb + verb[-1] + "ing") + return forms + + +_LOOK_VERB = "|".join( + sorted(map(re.escape, _LOOK_WORK + _SPANISH_LOOK_WORK), key=len, reverse=True) +) +_LOOK_ONLY = re.compile(rf"(?:{'|'.join(map(re.escape, _LOOK_WORK + _SPANISH_LOOK_WORK))})$") +_LOOK_GERUND = "|".join(sorted(map(re.escape, _gerunds(_LOOK_WORK)), key=len, reverse=True)) +#: "run the tests", "rerun the failing test", "run the full suite", "run the build". +_RUN_CHECKS = ( + r"(?:re-?)?run(?:ning)? (?:(?:the |all |every |a |one )?(?:\w+ ){0,2}" + r"(?:tests?|suite|specs?|linters?|lint|type ?checks?|checks?|benchmarks?|build)" + r"|pytest|vitest|jest|mypy|ruff|tsc|cargo test|go test|npm test)\b" +) +#: "Next:", "Next step:", "Next up:", "Next step -", and the Spanish forms. +_NEXT_LEAD = ( + r"^_?(?:next(?: step| up| action)?|siguiente(?: paso)?|pr[oó]ximo paso)_?" + r"\s*(?::_?|\s[-\u2014\u2013]|[\u2014\u2013])\s*" +) +_NEXT_LINE = re.compile(_NEXT_LEAD + rf"(?:(?:{_LOOK_VERB})\b|{_RUN_CHECKS}|x\b)") +#: "The next step is to run the suite." / "The remaining work is checking ...". +_NEXT_IS = re.compile( + r"^(?:the )?(?:only )?(?:next|remaining) (?:step|work) is " + rf"(?:to (?:{_LOOK_VERB})\b|(?:to )?{_RUN_CHECKS}|(?:{_LOOK_GERUND})\b)" + rf"|^(?:el )?(?:siguiente|pr[oó]ximo) paso es (?:{_LOOK_VERB})\b" +) +#: A step that opens with inline code counts only for a read-only command. +_READ_ONLY_CODE = re.compile( + r"^(?:web_fetch|web_search|fs_read|fs_list|grep|rg(?!.*--pre)|cat|ls|head|tail|wc|stat|du|df" + r"|jq|git (?:log|status|diff|show|blame)|gh (?:pr|run|issue) (?:view|list|checks|diff))\b" +) +#: Redirection or command substitution: never read-only. +_SHELL_WRITES = re.compile(r"[<>]|\$\(|`|--output\b|\s-o\s") +#: One action only: after "and", "then", a comma or a semicolon the next word +#: is another look-up verb, an article or a stand-in, never a new verb +#: ("Next: inspect the VM and terminate it"). +_JOIN = re.compile( + r"(?:[,;:&+]|&&|\s-\s|\u2014|\u2013|\u2192|->|\band\b|\bthen\b|\bafter that\b" + r"|\bplus\b|\bas well as\b|\bor\b|\bto\b|\bby\b|\bwith\b|\bvia\b|\busing\b|\bbefore\b" + r"|\bso\b|\by\b|\be\b|\bo\b|\bluego\b|\bdespu[eé]s\b|\bpara\b|\bcon\b)" + r"\s*(?:then\s+|luego\s+)?(\w+)" +) +_AFTER_JOIN = frozenset( + { + "the", + "a", + "an", + "its", + "their", + "both", + "all", + "each", + "every", + "any", + "this", + "that", + "these", + "those", + "our", + "my", + "x", + "el", + "la", + "los", + "las", + "un", + "una", + "sus", + "su", + # Thinking, not doing: "... to recover what remains and determine the step". + "determine", + "identify", + "understand", + "see", + "figure", + "learn", + "list", + "separate", + "distinguish", + "rule", + "narrow", + "what", + "which", + "why", + "how", + "whether", + "qué", + "si", + "running", + "from", + "in", + "on", + "at", + "of", + "for", + } +) +#: What a person owns, matched on the raw text from the start of the paragraph +#: above the "Next" line's paragraph to the end of the reply (inline code, quotes and +#: fenced blocks after it included): shipping, deciding, paying, signing in, +#: what cannot be undone, production, and the person themself. Stems catch +#: most forms ("merging", "migration", "approval"). +_PERSON_OWNS = re.compile( + r"\b(?:merg|deploy|releas|publi|approv|decid|decision|choos|choice|purchas|submit|review" + r"|production|credential|password|passcode|registrar|invoice|account|login|log in|sign in" + r"|sign-in|signoff|sign-off|2fa|mfa|api key|secret|checkout|check out|refund|upload|payout" + r"|transfer|charg|countersign|stripe|credit card|real card|webhook|pagerduty|opsgenie)" + r"|\b(?:ship|push|pick|pay|buy|sign|send|sent|email|e-mail|mail|post|prod|click|tap|cart" + r"|wire|sms|text|paid)(?:s|es|d|ed|ped|ing|ping|ting|ment|ments)?\b" + # The person: "your password", "test it yourself". + r"|\b(?:you|your|yours|yourself|yourselves)\b" + # Spanish. + r"|\b(?:fusi[oó]n|fusion|desplieg|despleg|publi|lanza|lanzo|lanzó|aprob|aprueb" + r"|decid|decisi|elig|eleg|escog|firm|producci|contraseñ|cuenta|pag[aáoóuúü]|pagué" + r"|compr(?!ob)[aáoóeé]|env[ií][aáoóeé]|mand[aáoóeé])" + r"|\b(?:tu|tus|usted|ustedes|vos)\b", + re.IGNORECASE, +) +#: Changes that cannot be undone or that run or rewrite things, matched from +#: the "Next" line's own paragraph to the end: "Installed X." above a "Next: +#: run the tests" says what was done, not what comes next. +_CHANGES = re.compile( + r"\b(?:delet|remov|restart|reboot|shutdown|migrat|uninstall|rollback|roll back|rollout" + r"|installer|kubectl|terminat|destroy|purg|prun|wipe|truncat|revok|kill|flush|overwrit" + r"|replac|borr|elimin|reinici|migra)" + r"|\binstall(?:s|ing|ers?)?\b|\bappl(?:y|ies|ying)\b|\bcheck-?ins?\b" + r"|\bcheck(?:ed|ing)? in (?:the |this |that |my |our )?(?:fix|fixes|change|changes|code" + r"|commit|work|patch|flight|hotel|files?)\b" + r"|\b(?:drop|reset|force)(?:s|es|d|ed|ped|ing|ping|ting)?\b|\brm\s+-" + r"|--(?:fix|write|update|snapshot-update)\b|\bruff format\b|\bblack\b|\bprettier\b", + re.IGNORECASE, +) +#: "with" or "con", a determiner, and up to three words: someone, unless one +#: of the words is a tool or data ("verify with a SQL query"). +_WITH_SOMEONE = re.compile( + r"\b(?:with|con)\s+(?:(?:the|a|an|my|our|your|their|his|her|el|la|los|las|un|una|mi|mis" + r"|tu|su|nuestro|nuestra)\s+)?(`?[\w-]+`?)(?:\s+(`?[\w-]+`?))?(?:\s+(`?[\w-]+`?))?", + re.IGNORECASE, +) +_TOOL_WORDS = frozenset( + { + "query", + "queries", + "request", + "requests", + "tool", + "tools", + "debugger", + "profiler", + "flag", + "flags", + "option", + "options", + "filter", + "regex", + "pattern", + "test", + "tests", + "sample", + "samples", + "fixture", + "fixtures", + "copy", + "dry-run", + "verbose", + "breakpoint", + "breakpoints", + "log", + "logs", + "trace", + "traces", + "timeout", + "value", + "values", + "file", + "files", + "path", + "url", + "page", + "browser", + "devtools", + "inspector", + "sql", + "http", + "https", + "curl", + "grep", + "jq", + "python", + "json", + "yaml", + "metrics", + "dashboard", + "schema", + "data", + "dataset", + "input", + "inputs", + "payload", + "x", + "strace", + "gdb", + "tcpdump", + "wireshark", + "consulta", + "petición", + "registro", + "registros", + "archivo", + "archivos", + "datos", + "prueba", + "pruebas", + "herramienta", + "previous", + "last", + "earlier", + "baseline", + "run", + "runs", + "version", + "versions", + "build", + "builds", + "output", + "outputs", + "result", + "results", + "commit", + "branch", + "main", + "snapshot", + "reference", + "expected", + "original", + "anterior", + "versión", + "resultado", + "resultados", + } +) +#: People and groups: "the data team" is someone, whatever word comes before. +_PERSON_WORDS = frozenset( + { + "team", + "teams", + "owner", + "owners", + "maintainer", + "maintainers", + "officer", + "officers", + "group", + "folks", + "people", + "staff", + "department", + "committee", + "crew", + "squad", + "lead", + "leads", + "manager", + "managers", + "admin", + "admins", + "author", + "authors", + "reviewer", + "reviewers", + "user", + "users", + "vendor", + "supplier", + "client", + "customer", + "customers", + "support", + "lawyer", + "attorney", + "accountant", + "doctor", + "dentist", + "nurse", + "airline", + "agent", + "broker", + "contractor", + "landlord", + "bank", + "seller", + "buyer", + "boss", + "hr", + "equipo", + "responsable", + "dueño", + "cliente", + "proveedor", + } +) +#: Reaching someone or something that pages, sells or costs money. +_CONTACT = re.compile( + r"\b(?:on|en) (?:ebay|amazon|craigslist|etsy|facebook marketplace)\b" + r"|\bpag(?:ed|ing)\b|\bon[- ]call\b|\balert pages?\b" + r"|\bpages?\b[^.\n]{0,40}\b(?:sre|rotation|engineer|duty|team|secondary|primary)\b" + r"|\bpage (?:the |an? |our )?(?:engineer|team|someone|somebody|him|her|them|ops)\b" + r"|\b(?:test |real )?orders?\b(?! to\b)" + r"|\blive (?:store|site|server|system|database|db|environment|api)\b" + r"|\bon an? (?:(?:new|fresh|spot|gpu|cloud|bigger|larger) )+" + r"(?:vm|instance|server|machine|box|node|cluster|pod)\b" + r"|\b(?=\w*\d)\w+ instance\b", + re.IGNORECASE, +) + + +def _reaches_someone(text: str) -> bool: + if _CONTACT.search(text): + return True + for found in _WITH_SOMEONE.finditer(text): + words = [w.strip("`").casefold() for w in found.groups() if w] + # A tool or data word, a flag ("-v"), a number, or code: not a person. + if any(w in _PERSON_WORDS for w in words): + return True + if "`" in found.group(0) or any( + w in _TOOL_WORDS or w.startswith("-") or w.isdigit() for w in words + ): + continue + return True + return False + + +_LIST_LINE = re.compile(r"^\s*(?:[-*+\u2022]|\d+[.)])\s") +_FENCE_LINE = re.compile(r"^\s*(?:```|~~~)") +#: A raw line that opens with a "Next" lead, after markdown emphasis and a list marker. +_RAW_LEAD = re.compile( + r"(?:^\s*(?:(?:[-*+\u2022]|\d+[.)])\s+)?|[.!?)\u2026]\s+)[*_]{0,2}" + r"(?:next|the next|the only|the remaining|remaining|only remaining|siguiente" + r"|el siguiente|pr[oó]ximo|el pr[oó]ximo)\b", + re.IGNORECASE, +) +_CODE_SPAN = re.compile(r"`([^`\n]+)`") + + +def _lead_line(raw: str) -> tuple[int, list[str]] | None: + """The index of the last prose line with a "Next" lead, and the raw lines.""" + lines = raw.replace("\r\n", "\n").split("\n") + fenced = False + found: int | None = None + for index, line in enumerate(lines): + if _FENCE_LINE.match(line): + fenced = not fenced + continue + if fenced or line.startswith((" ", "\t")) or line.lstrip().startswith((">", "|", "#")): + continue + if _RAW_LEAD.search(line): + found = index + return None if found is None else (found, lines) + + +def _read_only_code(span: str) -> bool: + """A name ("config.yaml", "~/logs"), or commands that are all read-only and write nothing.""" + if _SHELL_WRITES.search(span): + return False + name = span.strip() + if not re.search(r"\s|[|;&]", name) and re.search(r"[./~]", name): + # "config.yaml", "~/logs": a name, unless it is run ("./cleanup"). + runs = name.startswith(("./", "../", "/usr/", "/bin/", "/sbin/", "bin/", "scripts/")) + return not runs and not name.endswith((".sh", ".ps1", ".bat", ".cmd", ".command")) + parts = [part.strip() for part in re.split(r"\|\|?|&&?|;", span)] + return all(_READ_ONLY_CODE.match(part) for part in parts if part) + + +def _one_action(sentence: str) -> bool: + sentence = re.sub(r"(? str | None: + """ "next:" when *sentence* is a closing "Next: " line, else ``None``.""" + if not (_NEXT_LINE.match(sentence) or _NEXT_IS.match(sentence)): + return None + if not _one_action(sentence): + return None + located = _lead_line(raw) + if located is None: + return None + index, lines = located + if _LIST_LINE.match(lines[index]): + return None + start = index + while start > 0 and lines[start - 1].strip(): + start -= 1 + # The paragraph above is read too: "ready to merge." then "Next: check CI". + above = start - 1 + while above > 0 and not lines[above].strip(): + above -= 1 + while above > 0 and lines[above - 1].strip(): + above -= 1 + tail = "\n".join(lines[max(above, 0) :]) + own = "\n".join(lines[start:]) + if _PERSON_OWNS.search(re.sub(r"[_.]", " ", tail)) or _reaches_someone(own): + return None + if _CHANGES.search(re.sub(r"[_.]", " ", own)): + return None + # A fenced block after the "Next" line is a command to run: never a look. + after = lines[index + 1 :] + if any(_FENCE_LINE.match(line) or line.startswith((" ", "\t")) for line in after): + return None + if any(not _read_only_code(span) for span in _CODE_SPAN.findall("\n".join(lines[start:]))): + return None + # Code right after the lead is the step itself: a read-only command, not a name. + lead = _RAW_LEAD.search(lines[index]) + rest = lines[index][lead.end() :] if lead else "" + first = re.match( + r"(?:\s+(?:step|up|action|paso))?[*_]{0,2}\s*(?::|-|\u2014|\u2013)[*_]{0,2}\s*`([^`\n]+)`", + rest, + ) + if first and not _READ_ONLY_CODE.match(first.group(1).strip()): + return None + # Quoted text right after the lead is someone's words, not a step. + quotes = "\"'\u201c\u2018\u00ab" + if re.search(rf"(?::|\s-|\u2014|\u2013)\s*[*_]{{0,2}}[{quotes}]", lines[index]): + return None + return "next:" + + +# ── Hand-backs: the turn is the person's now ──────────────────────────── + +#: What a person is asked to do, as an English or Spanish imperative. +_ASKS = ( + r"(?:reply|respond|answer|send|pick|choose|select|paste|share|provide|give|confirm|approve" + r"|say|type|upload|attach|drop|grant|allow|tell|let|decide|specify|check|review|click|press" + r"|run|open|add|set|enter|fix|merge|restart)" +) +_HAND_BACK = re.compile( + # A request that starts the sentence or a clause: "Pick an option and ...". + r"(?:^|[;:\u2014\u2013(]\s*|\s-\s+)(?:(?:please|just|then|or|and|so|ok|okay|also|first)[, ]+)?" + r"(?:reply|respond|answer|send|pick|choose|select|paste|provide|confirm|approve)\b" + # Any request that the reply then answers: "Merge it and I'll ...". + r"|(?:^|[.;:\u2014\u2013(]\s*)(?:(?:please|just|then|or|so|ok|okay|also|first)[, ]+)?" + + _ASKS + + r"\b[^;]*?(?:\band\b|\bthen\b|,)\s*i(?:'ll| will| can)\b" + r"|^(?:(?:a|one|just)\s+)?(?:(?:quick|simple)\s+)?(?:yes|ok|okay|word|confirmation" + r"|thumbs[- ]up|nod)\b.*\bi(?:'ll| will)\b" + # Asked of the person by name. + r"|\b(?:send|give|show|tell|point|message|email|ping)\s+me\b" + r"(?!\s+(?:a\s+)?(?:moment|second|minute|sec)\b)" + r"|\b(?:share|paste|send)\b[^,;.]{0,40}\bwith me\b" + r"|\blet me (?:know|see|have)\b|\bjust say\b|\bsay (?:the word|so|yes|go)\b|\bsay[- ]so\b" + r"|\bup to you\b|\bplease\b|\b(?:can|could|would|will) you\b|\bneed you\b" + r"|\byou(?:'ll| will)? (?:need|have) to\b|\bi(?:'ll| will)? need (?:you|your)\b" + r"|\b(?:want|like) me to\b|\b(?:should|shall) i\b|\b(?:do|would) you (?:want|like|prefer)\b" + # A condition on the person. + r"|\b(?:if|once|when|after|as soon as|until|before) you(?:'re|'ve|'d)?\b" + r"|\b(?:once|after|upon|pending|with|on) your\b|\bif your\b" + r"|\byou (?:should|must|choose|decide|pick|confirm|approve)\b|\bso i can\b" + r"|\b(?:over|defer) to you\b|\byour (?:move|turn)\b" + # A wait the reply names. + r"|\b(?:once|when|as soon as|until) i (?:have|get|hear|receive)\b|\bpending\b" + r"|\b(?:hold(?:ing)?(?: on)?|stand(?:ing)? by) until\b|\bstanding by\b" + r"|\buntil (?:\w+ ){1,3}(?:agrees|confirms|approves|replies|answers)\b" + # Their permission or answer. + r"|\byour (?:call|choice|permission|approval|go[- ]ahead|ok|okay|confirmation|answer|reply" + r"|input|sign[- ]?off|say[- ]so|decision|response|consent|thumbs[- ]up|instructions)\b" + r"|(? str | None: + """The phrase that says *text* will go on working, or ``None``. + + The returned value is the list's phrase, the future-tense marker + ("i'll", "voy a", "revisaré") or the verb under way ("running"), never + a longer piece of the reply. + """ + paragraphs = prose_paragraphs(text) + if not paragraphs: + return None + window = paragraphs[-1][-_PHRASE_WINDOW:] + if any(_is_question(sentence) for sentence in window): + return None + recent = [sentence for paragraph in paragraphs for sentence in paragraph] + if any(_hands_back(sentence) for sentence in recent[-_HAND_BACK_WINDOW:]): + return None + for sentence in reversed(window): + step = _as_step(sentence) + found = None + if step is not None: + # A "Next" step counts only as the reply's last sentence (TD-5437). + last_sentence = sentence is window[-1] + found = _phrase(step) or (_next_line(step, text) if last_sentence else None) + if found: + return found + last = _as_step(window[-1]) + if last is None or _acknowledged_habit([_REPORT_BACK.sub("", x) for x in window]): + return None + return _timed_future(last) or _under_way(last) + + +def _acknowledged_habit(sentences: list[str]) -> bool: + """An acknowledgement, then a habit verb: "Understood. I'll use tabs." is no step. + + An acknowledgement before real work is still a step ("Sure, I'll run the + tests now.", "Understood. I'll fix the paginator."). + """ + last = sentences[-1] + opens = _ACK.match(last) or (len(sentences) > 1 and _ACK_SENTENCE.match(sentences[-2])) + return bool(opens) and _HABIT.search(last) is not None + + +def _hands_back(sentence: str) -> bool: + return _HAND_BACK.search(_NOT_THE_PERSON.sub(" ", sentence)) is not None + + +def _as_step(sentence: str) -> str | None: + """*sentence* without its report-back tail, or ``None`` if it is no step.""" + step = _REPORT_BACK.sub("", sentence) + return None if _NOT_A_STEP.search(step) else step + + +def _phrase(sentence: str) -> str | None: + for phrase in PHRASES: + if re.search(rf"(? str | None: + for pattern in _FUTURE: + match = pattern.search(sentence) + if match: + return match.group(1) + for match in _SPANISH_FUTURE.finditer(sentence): + if match.group(1) not in _NOT_VERBS: + return match.group(1) + return None + + +def _under_way(sentence: str) -> str | None: + for pattern in _UNDER_WAY: + match = pattern.search(sentence) + if match: + return match.group(1) + return None + + +def _is_question(sentence: str) -> bool: + return sentence.rstrip(" \"')]*_").endswith("?") or sentence.startswith("¿") diff --git a/core/tstd/follow_through_text.py b/core/tstd/follow_through_text.py new file mode 100644 index 00000000..b88cc2a4 --- /dev/null +++ b/core/tstd/follow_through_text.py @@ -0,0 +1,158 @@ +"""The part of a reply the follow-through detector reads (TD-5428). + +Only the model's own prose counts. Code blocks, block quotes, tables, text +in quotes or inline code, and drafted messages are someone else's words, or +words for someone else, and are dropped before any rule looks. +""" + +from __future__ import annotations + +import re +from collections.abc import Sequence + +_FENCE = re.compile(r"(```|~~~).*?(?:\1|\Z)", re.DOTALL) +#: Quoted text and inline code. A single quote opens and closes only at a +#: word's edge, so an apostrophe ("I'll", "users'") is not a quotation. +_QUOTATIONS = tuple( + re.compile(pattern) + for pattern in ( + r"`[^`\n]*`", + r"\"[^\"]*\"", + r"\u201c[^\u201d]*\u201d", + r"«[^»]*»", + r"\u2018(?:[^\u2018\u2019]|\u2019(?=\w))*\u2019(?!\w)", + r"(? list[list[str]]: + """The reply's own paragraphs, each as folded sentences, in order. + + A list under a lead-in line is left out: the lead-in says what it is. + A reply that ends inside a drafted message gives nothing at all, since + the line that introduced the draft was delivered with it. + """ + body = _FENCE.sub("\n\n", text) + for pattern in _QUOTATIONS: + body = pattern.sub(_stand_in, body) + lines = _without_drafts(_fold(body).split("\n")) + if lines is None: + return [] + paragraphs: list[list[str]] = [] + previous: list[str] = [] + for block in re.split(r"\n\s*\n", "\n".join(lines)): + if block.startswith((" ", "\t")) and not _LIST_ITEM.match(block): + continue + kept = [line.strip() for line in block.split("\n")] + # A heading labels a section; it is not a sentence of the reply. + kept = [line for line in kept if line and not line.startswith((">", "|", "#"))] + if not kept: + continue + # A list standing apart from the line that introduces it. + listed = all(_LIST_ITEM.match(line) for line in kept) + if listed and previous and previous[-1].endswith(":"): + continue + previous = kept + sentences = _sentences(_without_list(kept)) + while sentences and _FILLER.match(sentences[-1]): + sentences.pop() + if sentences: + paragraphs.append(sentences) + return paragraphs + + +def _stand_in(match: re.Match[str]) -> str: + """A placeholder that keeps the sentence's shape, and its end.""" + inner = match.group(0)[1:-1].rstrip() + return "x." if inner.endswith((".", "!", "?")) else "x" + + +def _fold(text: str) -> str: + """Lower case, straight apostrophes, no markdown emphasis.""" + text = text.replace("\u2019", "'").replace("\u2018", "'") + # A "* " bullet stays, for the list rules. + return re.sub(r"\*\*|__|\*(?=\w)|(?<=[\w.!?:,])\*", "", text).casefold() + + +def _without_drafts(lines: Sequence[str]) -> list[str] | None: + """*lines* minus any drafted message, or ``None`` if the reply ends in one.""" + if _ends_signed(lines): + return None + kept: list[str] = [] + drafting = signed = False + for line in lines: + bare = line.strip().lstrip("# ").strip() + if not drafting: + if _DRAFT_HEAD.match(bare): + drafting, signed = True, False + continue + kept.append(line) + if _DRAFT_LEAD.search(bare): + drafting, signed = True, False + elif _RULE.match(bare) or (signed and not bare): + drafting = False + kept.append("") + elif _SIGN_OFF.match(bare): + signed = True + return None if drafting else kept + + +def _ends_signed(lines: Sequence[str]) -> bool: + """Whether the reply closes like a letter: "Best," and at most a name.""" + filled = [line.strip() for line in lines if line.strip()] + for back, line in enumerate(reversed(filled[-3:])): + if line.endswith(",") and _SIGN_OFF.match(line): + return all(len(after.split()) <= 4 for after in filled[len(filled) - back :]) + return False + + +def _without_list(lines: list[str]) -> list[str]: + """Drop a closing list under a lead-in line in the same paragraph.""" + end = len(lines) + while end > 0 and _LIST_ITEM.match(lines[end - 1]): + end -= 1 + if 0 < end < len(lines) and lines[end - 1].endswith(":"): + return lines[:end] + return [_LIST_ITEM.sub("", line) for line in lines] + + +def _sentences(lines: Sequence[str]) -> list[str]: + joined = "\n".join(lines) + return [part.strip() for part in _SENTENCE_END.split(joined) if re.search(r"\w", part)] diff --git a/core/tstd/follow_through_turn.py b/core/tstd/follow_through_turn.py new file mode 100644 index 00000000..fef1b6d3 --- /dev/null +++ b/core/tstd/follow_through_turn.py @@ -0,0 +1,181 @@ +"""Follow through on a reply that says it will go on (TD-5428). + +An interactive turn ends on a reply with no tool call. When that reply +announces a next step (``follow_through.py``), the model is asked one +tool-free question with the progress guard's labels: + +- ``CONTINUE``, or a tool call: the same turn goes on with tools; +- ``DONE``: that text replaces the reply, unless it only says the reply again; +- ``BLOCKED``: what the model needs is added under the reply; +- an empty or step-less answer, a repeated step, a failed call, an answer cut + off at the token limit, or a text answer with no label: the reply stays. + +The turn ends marked as stopped short when the reply stays, or when the +text shown in its place or under it still announces a next step. The reply +is never shown twice: a ``BLOCKED`` answer that repeats it replaces it. + +There is no per-turn limit (the owner: "If there is work still to do then +it should not stop and just do it"): every stop that announces a step is +nudged, and the nudge does not spend the progress guard's +``MAX_AUTO_CONTINUES``. A repeated next step pauses, and a cap already +reached ends the turn marked, with no further model call. +Autonomy runs and delegate children are never checked; skip-all turns are. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from typing import TYPE_CHECKING, Literal + +from .follow_through import announced_next_step +from .logging import get_logger +from .output_cap import LENGTH_FINISH +from .progress_guard import ( + CONTINUE_INSTRUCTION, + FOLLOW_THROUGH_INSTRUCTION, + ProgressGuard, + interpret_check, + label_of, +) +from .protocol import FOLLOW_THROUGH_REPLACED, AssistantDelta, AssistantRetract +from .provider import ChatMessage + +if TYPE_CHECKING: + from .reply_retry import StreamResult + from .session import Session + +log = get_logger("tstd.follow_through") + +#: ``end``: finish the turn as usual. ``stopped_short``: finish it with the +#: marker. ``retry``: call the model again. ``stopped``: Stop or cancel. +FollowThrough = Literal["end", "stopped_short", "retry", "stopped"] + + +async def follow_through( + reply: str, + *, + response_id: str | None, + session: Session, + guard: ProgressGuard, + messages: list[ChatMessage], + ask: Callable[[list[ChatMessage]], Awaitable[StreamResult]], + cap_reached: Callable[[], bool], +) -> FollowThrough: + """Check the tool-free *reply* the turn is about to end on. + + *response_id* is the one the reply's text was shown under. *ask* makes + one model call with no tools and shows nothing. The nudge joins the + conversation only with an answer added after the reply. + """ + # Skip-all is checked too (the manager's correction): the nudge asks the + # model to keep its word, it is not a cap, and the person who asked for it + # runs with approvals off. Autonomy and children have their own breakers. + if session.autonomy or session.delegate_depth >= 1: + return "end" + phrase = announced_next_step(reply) + if phrase is None: + return "end" + nudge = guard.can_follow_through() and not cap_reached() + log.info( + "reply announces a next step", + extra={"extra_fields": {"session_id": session.id, "phrase": phrase, "nudge": nudge}}, + ) + if not nudge: + return "stopped_short" + asked = ChatMessage(role="user", content=FOLLOW_THROUGH_INSTRUCTION, steer=True, check=True) + answer = await ask([*messages, asked]) + if session.cancel_requested or session.stop_turn_requested: + return "stopped" + content = answer.content.strip() + label = label_of(content) + kind, detail = interpret_check(content, guard.last_continue) + log.info( + "follow-through check answered", + extra={ + "extra_fields": { + "session_id": session.id, + "kind": "failed" if answer.failed else kind, + "label": label, + "tool_call": bool(answer.tool_calls), + } + }, + ) + if answer.failed: + return "stopped_short" + if answer.finish_reason == LENGTH_FINISH: + # Cut off at the token limit: whatever it says is unfinished, so it + # never stands in for the reply. + return "stopped_short" + if answer.tool_calls and label is None: + # It went to work. The call was made with no tools offered, so it + # is not run: the next request offers them and it is made again. + guard.note_follow_through(content or guard.last_continue) + await _carry_on(session, messages) + return "retry" + if kind == "pause": + return "stopped_short" + if kind == "continue": + messages.append(asked) + guard.note_follow_through(detail) + await _show(session, messages, f"Next: {detail}") + await _carry_on(session, messages) + return "retry" + if label is None: + # No label: the check was not answered, so nothing it said stands in + # for the reply or sits under it (review round 2). The reply stays, + # marked, and Continue is one click away. + return "stopped_short" + if label != "BLOCKED" and _repeats(detail, reply): + return "end" + if label == "BLOCKED" and not _repeats(detail, reply): + messages.append(asked) + await _show(session, messages, detail) + else: + await _replace(session, messages, detail, response_id) + return "end" if announced_next_step(detail) is None else "stopped_short" + + +def _repeats(text: str, reply: str) -> bool: + """Whether *text* says the whole of *reply* again.""" + return " ".join(reply.split()).casefold() in " ".join(text.split()).casefold() + + +async def _replace( + session: Session, messages: list[ChatMessage], text: str, response_id: str | None +) -> None: + """*text* in place of the reply, in the conversation and in the chat. + + The window takes the reply's text off its bubble by its response id and + puts *text* there, so there is one reply on one bubble. + """ + messages[-1] = ChatMessage(role="assistant", content=text) + await session.conversation_changed() + if response_id is not None: + await session.event_log.add( + AssistantRetract( + session_id=session.id, + response_id=response_id, + reason=FOLLOW_THROUGH_REPLACED, + seq=1, + ) + ) + await session.event_log.add(AssistantDelta(session_id=session.id, delta=text, seq=1)) + + +async def _show(session: Session, messages: list[ChatMessage], text: str) -> None: + """*text* on the transcript and in the chat, a paragraph of its own. + + The window adds it to the reply that is still open, so the blank lines + keep it apart from what that reply already says. + """ + messages.append(ChatMessage(role="assistant", content=text)) + await session.conversation_changed() + await session.event_log.add( + AssistantDelta(session_id=session.id, delta=f"\n\n{text}\n\n", seq=1) + ) + + +async def _carry_on(session: Session, messages: list[ChatMessage]) -> None: + # The request must end on a user turn (TD-5177). + messages.append(ChatMessage(role="user", content=CONTINUE_INSTRUCTION, steer=True, check=True)) + await session.conversation_changed() diff --git a/core/tstd/loop.py b/core/tstd/loop.py index 65d4ec3a..ea191248 100644 --- a/core/tstd/loop.py +++ b/core/tstd/loop.py @@ -92,6 +92,7 @@ from .discovery import discover_model, resolve_tier_slugs from .effort import DEFAULT_EFFORT, with_effort from .fallback import BackupChain, TurnBackups, announce_switch, backup_wanted +from .follow_through_turn import FollowThrough, follow_through from .hooks import HOOK_BLOCKED_NOTE, with_hook_context from .keychain import KeychainError from .local_worker import ( @@ -164,7 +165,13 @@ ToolDefinition as ProviderToolDefinition, ) from .reply_guard import ReplyGuard, user_blocks -from .reply_retry import GUARDED_CODE, StreamResult, stream_reply, thinking_ate_cap +from .reply_retry import ( + GUARDED_CODE, + StreamResult, + new_response_id, + stream_reply, + thinking_ate_cap, +) from .router import TierName, TierRouter from .session import QueuedUserMessage, Session, SessionEventLog from .session_goal import ( @@ -331,11 +338,19 @@ async def _clear_stale_results( ) -async def _show_progress_note(session: Session, messages: list[ChatMessage], text: str) -> None: - """Put the check's text on the transcript and in the chat.""" +async def _show_progress_note( + session: Session, messages: list[ChatMessage], text: str, response_id: str | None = None +) -> None: + """Put the check's text on the transcript and in the chat. + + *response_id* names the text, for one the follow-through check may + replace (TD-5428). + """ messages.append(ChatMessage(role="assistant", content=text)) await session.conversation_changed() - await session.event_log.add(AssistantDelta(session_id=session.id, delta=text, seq=1)) + await session.event_log.add( + AssistantDelta(session_id=session.id, delta=text, response_id=response_id, seq=1) + ) async def _finish_progress_answer( @@ -350,10 +365,12 @@ async def _finish_progress_answer( calibration: CalibrationStore, *, check_failed: bool = False, + stopped_short: bool = False, ) -> None: """The progress check answered the user. End the turn on that answer. - *check_failed* ends it as a failed done-check (TD-5124). + *check_failed* ends it as a failed done-check (TD-5124); + *stopped_short* marks an answer that says it will go on (TD-5428). """ router.record_success() await _emit_turn_complete( @@ -363,6 +380,7 @@ async def _finish_progress_answer( tracker, failed=check_failed, error_code="stop_check_failed" if check_failed else None, + stopped_after_continue=stopped_short, ) await maybe_verify_after_turn(session, config, tracker, client_for, assembler, calibration) session.snapshot_branches() @@ -372,6 +390,32 @@ async def _finish_progress_answer( ) +def _tool_free_ask( + provider: ProviderLike, + model_slug: str, + session: Session, + tracker: CostTracker, + tier: TierName, + tier_cfg: TierConfig, +) -> Callable[[list[ChatMessage]], Awaitable[StreamResult]]: + """One model call with no tools that shows nothing: how both checks ask.""" + + async def ask(messages: list[ChatMessage]) -> StreamResult: + return await _stream_and_parse( + provider, + model_slug, + messages, + session, + None, + tracker, + tier, + tier_cfg, + emit_events=False, + ) + + return ask + + async def _progress_check_gate( guard: ProgressGuard, session: Session, @@ -388,6 +432,8 @@ async def _progress_check_gate( router: TierRouter, calibration: CalibrationStore, stop_check: TurnStopCheck | None = None, + *, + cap_reached: Callable[[], bool] = lambda: False, ) -> Literal["proceed", "pause", "stop"]: """Ask the tool-free question. ``stop`` means the turn is over. @@ -400,17 +446,8 @@ async def _progress_check_gate( *messages, ChatMessage(role="user", content=PROGRESS_CHECK_INSTRUCTION), ] - check = await _stream_and_parse( - provider, - model_slug, - check_messages, - session, - None, - tracker, - tier, - tier_cfg, - emit_events=False, - ) + ask = _tool_free_ask(provider, model_slug, session, tracker, tier, tier_cfg) + check = await ask(check_messages) content, tool_calls, failed, error_msg = ( check.content, check.tool_calls, @@ -442,7 +479,26 @@ async def _progress_check_gate( }, ) if kind == "reply": - await _show_progress_note(session, messages, detail) + # An answer with no label is the model's own final reply, so it is + # followed through like any other (TD-5428). A labelled one is not. + own_reply = None if has_label(content or "") else new_response_id() + await _show_progress_note(session, messages, detail, own_reply) + followed: FollowThrough = "end" + if own_reply is not None: + followed = await follow_through( + detail, + response_id=own_reply, + session=session, + guard=guard, + messages=messages, + ask=ask, + cap_reached=cap_reached, + ) + if followed == "retry": + return "proceed" + if followed == "stopped": + await _finish_stopped_turn(session, tier, turn_start, tracker) + return "stop" checked = "end" if stop_check is None else await stop_check.at_turn_end(messages) if checked == "retry": guard.note_reply() @@ -461,6 +517,7 @@ async def _progress_check_gate( router, calibration, check_failed=checked == "failed", + stopped_short=followed == "stopped_short", ) return "stop" if kind == "continue": @@ -494,6 +551,8 @@ async def _interactive_guard( router: TierRouter, calibration: CalibrationStore, stop_check: TurnStopCheck | None = None, + *, + cap_reached: Callable[[], bool] = lambda: False, ) -> bool: """True when the loop should call the model. False ends this turn. @@ -520,6 +579,7 @@ async def _interactive_guard( router, calibration, stop_check, + cap_reached=cap_reached, ) if checked == "stop": return False @@ -656,6 +716,7 @@ async def _emit_turn_complete( tracker: CostTracker, failed: bool = False, error_code: str | None = None, + stopped_after_continue: bool = False, ) -> None: """Emit a ``turn_complete`` event with cost and duration. @@ -676,6 +737,7 @@ async def _emit_turn_complete( duration=round(duration, 3), failed=failed, error_code=error_code, + stopped_after_continue=stopped_after_continue, seq=1, # overwritten by event log ) ) @@ -2240,6 +2302,12 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: ), ) + def cap_reached() -> bool: + """Whether the next model call would break a declared cap (TD-707).""" + runtime = session.delegate_runtime + children = runtime.child_calls if runtime is not None else 0 + return _cap_violation(session, tracker, _session_start, _iterations + children) is not None + # ── Turn loop ─────────────────────────────────────────────────── while not session.cancel_requested: # 1. Wait for user input @@ -2862,6 +2930,7 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: router, calibration, stop_check, + cap_reached=cap_reached, ): break @@ -3281,6 +3350,24 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: joined += await inject_worker_notes(session, messages) if joined: continue + # TD-5428: a reply that says it will go on is followed through + # before it counts as the end of the turn. + followed: FollowThrough = "end" + if not tool_calls and not cut_calls: + followed = await follow_through( + collected_content, + response_id=reply.response_id, + session=session, + guard=guard, + messages=messages, + ask=_tool_free_ask(provider, model_slug, session, tracker, tier, tier_cfg), + cap_reached=cap_reached, + ) + if followed == "retry": + continue + if followed == "stopped": + await _finish_stopped_turn(session, tier, turn_start, tracker) + break checked = await stop_check.at_turn_end(messages) if checked == "retry": continue @@ -3294,6 +3381,7 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: tracker, failed=checked == "failed", error_code="stop_check_failed" if checked == "failed" else None, + stopped_after_continue=followed == "stopped_short", ) await maybe_verify_after_turn( session, config, tracker, client_for, assembler, calibration diff --git a/core/tstd/progress_guard.py b/core/tstd/progress_guard.py index 7c545be4..d48a21ec 100644 --- a/core/tstd/progress_guard.py +++ b/core/tstd/progress_guard.py @@ -21,6 +21,11 @@ Resume clears the window, the identical-call streak, and the 52-call budget, then the same turn continues. + +The follow-through check (TD-5428, follow_through_turn.py) asks with the +same labels and spends the same ``MAX_AUTO_CONTINUES``: a ``CONTINUE`` it +gets is one of the three, and with all three spent it does not ask. It +asks at most once a turn. """ from __future__ import annotations @@ -46,15 +51,29 @@ # Sent after the "Next: ..." note so the request ends on a user turn (TD-5177). CONTINUE_INSTRUCTION = "Carry on with that next step." -PROGRESS_CHECK_INSTRUCTION = ( - "Progress check. Tools are off for this reply. " +# The answer both checks ask for, and :func:`interpret_check` reads. +_CHECK_LABELS = ( "Start your reply with one of these labels and make no tool call:\n" "DONE: \n" "CONTINUE: \n" - "BLOCKED: \n" + "BLOCKED: " +) + +PROGRESS_CHECK_INSTRUCTION = ( + "Progress check. Tools are off for this reply. " + f"{_CHECK_LABELS}\n" "CONTINUE must name a different next step than the previous check." ) +# TD-5428: sent when a reply with no tool call says the work goes on. +FOLLOW_THROUGH_INSTRUCTION = ( + "Follow-through check. Tools are off for this reply. " + "Your reply announced a next step but made no tool call. " + "Carry on with the step you announced (answer CONTINUE), or answer DONE or BLOCKED. " + "If that step is the user's to take, or needs their go-ahead, answer BLOCKED. " + f"{_CHECK_LABELS}" +) + # One label line, as models really write it: "DONE: x", "**Done:** x", # "- CONTINUE - x", "BLOCKED" on a line of its own. A dash needs a space # before it, so "continue-on-error: true" is not a label. @@ -63,8 +82,10 @@ r"(?:(?:\s*:|\s+[-\u2013\u2014]|[\u2013\u2014](?=\s))[*_`]*\s*(.*)|\s*)$", re.IGNORECASE, ) -# The check's own header repeated back, alone or with its first sentence. -_ECHO_LINE = re.compile(r"^progress check(?:[\s:.!\u2013\u2014-]*$|\.\s*tools are off)") +# A check's own header repeated back, alone or with its first sentence. +_ECHO_LINE = re.compile( + r"^(?:progress|follow-through) check(?:[\s:.!\u2013\u2014-]*$|\.\s*tools are off)" +) ToolNote = tuple[str, str, bool] @@ -118,9 +139,15 @@ def interpret_check(text: str, previous_continue: str) -> tuple[CheckKind, str]: return "reply", reply +def label_of(text: str) -> str | None: + """The label a check answer used (``DONE``, ``CONTINUE``, ``BLOCKED``), if any.""" + found = _find_label(text.strip().splitlines()) + return None if found is None else found[1] + + def has_label(text: str) -> bool: """True when the check answer used one of the three labels.""" - return _find_label(text.strip().splitlines()) is not None + return label_of(text) is not None def _find_label(lines: Sequence[str]) -> tuple[int, str, str] | None: @@ -149,6 +176,19 @@ class ProgressGuard: identical_streak: int = 0 pause_reason: str = "" + def can_follow_through(self) -> bool: + """Whether this turn may still be asked to follow through.""" + # No per-turn limit: a model that says there is more to do is sent back + # every time. A repeated next step or the model-call budget still pauses. + return True + + def note_follow_through(self, action: str) -> None: + """A follow-through nudge carried on: remember its step for the repeat check. + + It does not spend the progress check's three auto-continues. + """ + self.last_continue = _norm(action) + def note_reply(self) -> None: """User-visible text resets the tool window, not the model-call budget. diff --git a/core/tstd/protocol.py b/core/tstd/protocol.py index 8c9c01e7..fdd1a108 100644 --- a/core/tstd/protocol.py +++ b/core/tstd/protocol.py @@ -2702,6 +2702,11 @@ class AssistantReasoning(DaemonEvent): response_id: str | None = None +#: The ``assistant_retract`` reason for a reply the follow-through check's +#: answer takes the place of (TD-5428). +FOLLOW_THROUGH_REPLACED = "follow_through_replaced" + + class AssistantRetract(DaemonEvent): """Withdraw one model response's shown text and thinking (TD-5159). @@ -2718,6 +2723,10 @@ class AssistantRetract(DaemonEvent): turn, stay. The partial text never entered the model's conversation. A client that does not know this event drops it and keeps showing the withdrawn text above the retry. + + With ``reason`` ``follow_through_replaced`` (TD-5428) nothing is asked + again: the reply's new text follows at once, in the next + ``assistant_delta``, and the window keeps the thinking that led to it. """ type: Literal["assistant_retract"] = "assistant_retract" @@ -3355,6 +3364,11 @@ class TurnComplete(DaemonEvent): thinking, after one retry with a larger cap where there was room (TD-5233), and ``empty_completion`` when it ended without writing anything and did not stop at the cap. + + ``stopped_after_continue`` (TD-5428, additive) marks a turn whose reply + announced a next step and ended there: the follow-through check could + not get the model to take it. The window shows "Stopped after saying it + would continue" on that reply, with Continue. """ type: Literal["turn_complete"] = "turn_complete" @@ -3365,6 +3379,7 @@ class TurnComplete(DaemonEvent): duration: float = Field(ge=0) failed: bool = False error_code: str | None = None + stopped_after_continue: bool = False class ContextCompacted(DaemonEvent): diff --git a/docs/architecture.md b/docs/architecture.md index 493b7a8b..cc0a508d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -875,7 +875,7 @@ are stamped by a session's event log, `connection` events fix it at 1, and `ping | `assistant_model` | session | Which tier and model write the response `response_id`, sent before its text. The window labels each reply with it and shows a hand-over line when the tier changes (JOURNEY1-10). | | `assistant_delta` | session | A streamed chunk of assistant output. Additive `response_id` names the model response it belongs to (TD-5159); text the daemon writes itself (a failure, a progress note) has none. | | `assistant_reasoning` | session | A streamed chunk of a reasoning model's thinking. Separate from `assistant_delta` because it is not part of the answer: the window folds it behind a disclosure, and it is never replayed to the provider as assistant speech. OpenRouter `reasoning_details` flatten into this event for the UI; the raw array is echoed on the next assistant message after tools, not as speech. Carries the same `response_id` as the deltas (TD-5159). | -| `assistant_retract` | session | Withdraw every `assistant_delta` and `assistant_reasoning` with this `response_id`, and the loop asks again under a new id. `reason` says why: the provider went quiet partway through that response (`stream_stalled`, TD-5159), the endpoint cut it off (`stream_interrupted`, TD-5183), the reply guard cut it (`reply_guarded`, TD-5175), or the response ended at the output cap with only thinking and is asked again with a larger `max_tokens` (`output_cap_thinking`, TD-5233). Before a move to a backup it is the failed call's error code (TD-5120). Tool calls already run and earlier responses in the turn stay. An older client drops the event and keeps the withdrawn text above the retry. | +| `assistant_retract` | session | Withdraw every `assistant_delta` and `assistant_reasoning` with this `response_id`, and the loop asks again under a new id. `reason` says why: the provider went quiet partway through that response (`stream_stalled`, TD-5159), the endpoint cut it off (`stream_interrupted`, TD-5183), the reply guard cut it (`reply_guarded`, TD-5175), or the response ended at the output cap with only thinking and is asked again with a larger `max_tokens` (`output_cap_thinking`, TD-5233). Before a move to a backup it is the failed call's error code (TD-5120). Tool calls already run and earlier responses in the turn stay. `follow_through_replaced` (TD-5428) is no retry: the follow-through check's answer takes the reply's place and arrives in the next `assistant_delta`, so the window drops the reply's text, keeps its thinking and shows no Working line. An older client drops the event and keeps the withdrawn text above the retry (and, for `follow_through_replaced`, above the answer). | | `tool_call` | session | A tool call about to execute, with its decision class. The class is judged on the same workspace-joined paths dispatch uses, so a relative path shows the class the call runs with; `arguments` stay as the model sent them (TD-5148). `worker_id` and `parent_call_id` are set when a `delegate`, `workflow` task or checker child made the call (TD-5423): the child's run (`run-` and twelve hex digits, new for each run) and the `delegate` or `workflow` call that started it. A child's `tool_call_id` is `/`, unique to the run. The child's calls are relayed onto the parent's log, so the audit writer records them and a window nests them in Activity under the call `worker_run_started` named; the chat, the Files pane, its review comments' open/resolved status, `tst run`'s refusal count and the history before a window leave them out. Null for the session's own calls; an older client ignores both. | | `tool_result` | session | The outcome of a tool call, with an error code and diff when applicable. `allowed_by` names the read-only shell list entries that let the call run without asking, and is empty when a policy rule, an approval or any other class default decided (TD-5103). `transcript` holds a `delegate` child's steps (task, replies, tool calls and results, notes), for display only: the model gets the capped summary in `output`. A `workflow` call's holds each worker's and checker's steps under a header (TD-5195). It is empty for every other tool (TD-5117). A child's relayed result carries its `worker_id` and `parent_call_id`, as on its `tool_call` (TD-5423), and is sent as soon as that call ends; a child call its run never finished has `status` `error` and `error_code` `cancelled` (the run was stopped or cancelled) or `worker_failed` (a crash escaped dispatch), its output starting "Not finished", or `approval_stopped` (stopped while its approval card was still open; output "Not run"). An approval entry reads cancelled only when its call ends `approval_stopped`; one the person approved stays approved when the run is stopped after. `hooks` lists the after-write hooks (a formatter or linter from `hooks.after_write`) that ran on an `fs_write` or `fs_edit`'s files: each `name`, `status` (`passed`, `failed`, `timed_out`, `error`), `exit_code`, `duration_ms` and whether it `changed` a file. The step timeline shows their time; a failure's output is already in `output`, for the model (TD-5135). | | `shell_output` | session | A streamed chunk of a shell command's stdout or stderr. | @@ -892,7 +892,7 @@ are stamped by a session's event log, `connection` events fix it at 1, and `ping | `verify_result` | session | Interactive validator review of a write turn. Timeline only; not a chat bubble (TD-4204). | | `cost_update` | session | Accrued spend: this turn, this session, all time, by tier, and the classifier separately. A `consult` call (TD-5119) counts on the tier it asked, in the turn that made it; a delegate child's lands on its parent's session, and so does each `workflow` worker's and checker's (TD-5195). | | `boundary_update` | session | The resolved workspace boundary and caps, and where they came from. Additive `config_trust` (TD-5113) is set when the workspace config loosens anything: `state` (`pending`, `trusted` or `declined`), its `sha256`, and each loosened setting with its default. Pending and declined run on packaged defaults. | -| `turn_complete` | session | A finished turn: tokens, cost, tier, duration, and any failure code. A turn a restart cut is sealed once at revive with `failed`, zeros and `error_code: interrupted_by_restart` (TD-5018). | +| `turn_complete` | session | A finished turn: tokens, cost, tier, duration, and any failure code. A turn a restart cut is sealed once at revive with `failed`, zeros and `error_code: interrupted_by_restart` (TD-5018). Additive `stopped_after_continue` (TD-5428) is true when the turn's reply announced a next step and the turn ended there: the follow-through check (configuration.md, "A reply that says it will continue") asked and got no tool call or label, or could not ask. The window marks that reply "Stopped after saying it would continue" and offers Continue. | | `tier_state` | session | The active tier, any pinned override, slugs, preset, hosts (TD-1720), plan-mode lock (TD-4603; read-only since TD-5123), the picked `effort`, Fast (`fast`, `fast_available`, `fast_note`; TD-5176) and Ultracode (`ultracode`, `ultracode_available`; TD-5195). An older daemon omits `ultracode_available`, so a window hides the switch; a logged or bridged `tier_state` with effort `ultracode` reads as `max` with `ultracode` on. Native-engine sessions only. Additive `fallbacks` maps a tier that moved to a backup endpoint this turn to the backup's 1-based position in its list; `model_slugs` and `hosts` then name the backup (TD-5120), also in one the daemon sends mid-turn for `set_plan`, `set_tier` or `set_preset` (TD-5161). | | `context_compacted` | session | Older turns were compacted to fit the context window. Never silent. Additive `trigger` (`auto` \| `manual` \| `from_here`) and `guidance` say who asked and what to keep (TD-5109). The trigger `inflight_trim` is not compaction: the loop trimmed the middles of this turn's tool results and no message left, so `dropped_messages` counts the results trimmed. The window shows it as a quieter "Trim" row that leads with the results trimmed and the tokens freed (TD-5150). The trigger `clear_stale` is not compaction either: before any turn is compacted, tool results from earlier turns were replaced with a one-line placeholder naming the tool, its target and the size that went (`clear_tool_results` in config.yaml), and no message left, so `dropped_messages` counts the results cleared. The window shows it as the same quiet "Trim" row, previewed "Cleared earlier tool results" (TD-5115). Whether the worker or the extractive fallback wrote the summary, and whether recent files came back under it, does not change the event (TD-5128). | | `context_usage` | session | The next request's estimated tokens against the tier's window and its compaction point, for the title-bar gauge. Sent before each model call and after a compaction (TD-5109). Additive `model` names the model the figures are for, and `fallback` its 1-based position in the tier's `fallbacks` (0 for the tier's own model): on a backup the window and the calibrated estimate are the backup's (TD-5120). | diff --git a/docs/configuration.md b/docs/configuration.md index 9ae3b278..4218a977 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3409,6 +3409,170 @@ Resume, on the banner, starts the counters over and continues the same turn. A r window only. A file write resets the 52-call budget too. Unattended autonomy runs keep the charter breakers and do not take this check. +**A reply that says it will continue is followed through (TD-5428).** This is not a setting +either. When an interactive turn's reply makes no tool call but announces a next step ("Next I'll +extract the open actions", "Ahora voy a revisar las pruebas"), the model is asked one question +with the tools removed: carry on with that step, or answer `DONE` or `BLOCKED`. `CONTINUE`, or a +tool call, carries the same turn on with tools. `DONE` replaces the +reply (a `DONE` that only says the reply again leaves it as it was; a text answer with no label +never replaces it or sits under it: the reply stays, marked): the window takes the reply off its bubble and puts the answer there, so there is one reply +and never a second copy of it. `BLOCKED` adds what the model needs under the reply (and replaces +the reply if it says it all again). An answer that is empty, names no step, repeats the last one, +fails, or was cut off at the token limit (`finish_reason` `length`) leaves the reply as it was and +shows the marker. The turn ends marked "Stopped after saying it would continue", +with a Continue button, when the reply stays or when the text that replaced it, or came under +it, still announces a next step; any other answer ends the turn unmarked. Continue sends an +ordinary "Continue" message. It stays on that reply while no turn runs and only notices (a +hand-over line, a trimmed-history line) come after it. + +There is no per-turn limit: every stop that announces a step is nudged, and the nudge does not +spend the progress guard's three auto-continues. A `CONTINUE` that repeats the last step pauses the +turn, marked, and a cap already reached (the model-call budget, spend, time) stops it as usual. Each +match is logged with the phrase that matched. Autonomy runs and delegated, workflow and checker +workers are not checked, and neither is the Grok engine. Skip-all turns are checked: the nudge +asks the model to keep its word, it is not a cap. + +What counts, exactly. Only the model's own prose is read, from the end of the reply, in English +and Spanish. A reply is an announcement when any of these holds: + +- one of these phrases is in the last two sentences of the last paragraph: "I'm still working", + "still working on" (opening a sentence), "next I'll", "next I will", "next I'm going to", "now + I'll", "now I will", "now I'm going to" (each with or without the comma), "I'll now", "I will + now", "I'm now going to", "let me now", "let me next", "I'll keep working", "I'll keep going", + "I'll continue with the rest" or "with the remaining", "moving on to"; "a continuación voy a", + "ahora voy a", "ahora mismo voy a", "luego voy a", "después voy a", "ahora procedo a", "ahora + déjame", "sigo trabajando", "sigo en ello", "todavía estoy trabajando", "continuaré con el resto" + or "con los demás" (also "seguiré con", "continúo con"), and "lo siguiente es" followed by a verb + in the infinitive; +- or the reply's last sentence is a "Next" line whose step is one read-only or diagnostic + action (TD-5437). The progress check writes its own notes as "Next: ", and models copy + the form; such a line does not say who takes the step, so it counts only when the step is a + look, which is harmless whoever takes it. The line opens with "Next", "Next step", "Next up" + or "Next action" ("Siguiente", "Siguiente paso", "Próximo paso") and a colon, a dash with a + space before it, or an em or en dash, or reads "The next step is", "The next work is", "The + remaining step is" or "The remaining work is" ("the" and "only" optional; "El siguiente paso + es", "El próximo paso es"). The step is one of: + - a look-up verb: analyse, analyze, audit, check, compare, diff, enumerate, examine, fetch, + find, grep, inspect, investigate, locate, look, measure, parse, probe, profile, query, + read, reproduce, scan, search, test, trace, verify (after "is", as "to " or its -ing + form); in Spanish: analizar, buscar, comparar, comprobar, examinar, + inspeccionar, investigar, leer, listar, localizar, medir, rastrear, reproducir, revisar, + verificar; + - running checks: "run" or "rerun" ("re-run", "running"), an optional "the", "all", "every", + "a" or "one", up to two words, then test or tests, suite, spec or specs, lint, linter or + linters, type check or typecheck (or -s), check or checks, benchmark or benchmarks, or build, + or "run" and pytest, vitest, jest, mypy, ruff, tsc, cargo test, go test or npm test ("run the + full suite", "rerun the failing test", "run pytest"); + - inline code right after the lead (and its colon or dash) that is a read-only command as + below, not a name ("Next: `web_fetch …` to enumerate the models."; "Next: `bin/setup`." + does not count). + + One action: wherever these come in the sentence — a comma, semicolon, colon, "&", "&&", "+", + a dash with spaces round it, an em or en dash, an arrow ("->" or the arrow sign), "and", + "then", "after that", "plus", "as well as", "or", "to", "by", "with", "via", "using", + "before", "so" (Spanish "y", "e", "o", "luego", "después", "para", "con"), with a "then" or + "luego" after it skipped — the next word is a look-up verb above, "run" with checks as above, + a number, inline code or quoted text, or one of a, all, an, any, at, both, determine, + distinguish, each, every, figure, for, from, how, identify, in, its, learn, list, my, narrow, + of, on, our, rule, running, see, separate, that, the, their, these, this, those, understand, + what, whether, which, why, el, la, las, los, qué, si, su, sus, un, una. "Next: inspect the VM and terminate it" and "Next: inspect the cert to renew + it" do not count. Every inline code span from the "Next" line's paragraph to the end of the + reply is a name (no spaces, with a dot, slash or "~", not starting with "./", "../", "/usr/", + "/bin/", "/sbin/", "bin/" or "scripts/", and not ending in .sh, .ps1, .bat, .cmd or .command) + or read-only commands: no <, >, $(, backtick, "--output" or " -o ", and + every command it + chains or pipes (|, ||, &, &&, ;) opens with web_fetch, web_search, fs_read, fs_list, grep, rg + (not with --pre), cat, ls, head, tail, wc, stat, du, df, jq, git log/status/diff/show/blame, + or gh pr/run/issue view/list/checks/diff. A bare word such as `make` is a command. A fenced or + indented block after the "Next" line does not count, nor does that line when a quote + (straight, curly or «) comes right after a colon, " -", an em or en dash anywhere on it. + + Nor does it count when the raw text from the start of the paragraph above the "Next" line's + own paragraph to the end of the reply (inline code, quotes and fenced blocks included, with + "_" and "." read as spaces so `prod_deploy.sh` is read) holds anything a person owns: a word + starting merg, deploy, releas, publi, approv, decid, decision, choos, choice, purchas, submit, + review, production, credential, password, passcode, registrar, invoice, account, login, log + in, sign in, sign-in, signoff, sign-off, 2fa, mfa, api key, secret, checkout, check out, + refund, upload, payout, transfer, charg, countersign, stripe, credit card, real card, webhook, + pagerduty or opsgenie; the words ship, push, pick, pay, buy, sign, send, sent, email, e-mail, + mail, post, prod, click, tap, cart, wire, sms, text or paid (alone or with -s, -es, -d, -ed, + -ped, -ing, -ping, -ting, -ment or -ments, so "payload" and "postgres" do not block); you, + your, yours, yourself, yourselves; in Spanish a word starting fusión, fusion, desplieg, + despleg, publi, lanza, lanzo, lanzó, aprob, aprueb, decid, decisi, elig, eleg, escog, firm, + producci, contraseñ or cuenta, or pag followed by a, o or u (accented or not, or ü; "pagué"), + compr followed by a, o or e (accented or not, never "comprob"), envi or enví followed by a, o + or e (accented or not), or mand followed by a, o or e (accented or not); or tu, tus, usted, + ustedes, vos. + + From the "Next" line's own paragraph to the end (what a paragraph above says was done, such + as "Installed `pytest-xdist`.", does not count) it also does not count for a change that runs + or rewrites things: a word starting delet, remov, restart, reboot, shutdown, migrat, + uninstall, rollback, roll back, rollout, installer, kubectl, terminat, destroy, purg, prun, + wipe, truncat, revok, kill, flush, overwrit, replac, borr, elimin, reinici or migra; install, + installs, installing, installer, installers; apply, applies, applying; check-in, check-ins, + checkin, checkins; "check in" (or "checked in", "checking in") and optionally the, this, that, + my, our, then fix, fixes, change, changes, code, commit, work, patch, flight, hotel, file or + files; drop, reset or force (with -s, -es, -d, -ed, -ped, -ing, -ping or -ting); "rm -"; + --fix, --write, --update, --snapshot-update; ruff format, black or prettier. Nor when it reaches + someone: "with" or "con", optionally the, a, an, my, our, your, their, his, her, el, la, los, + las, un, una, mi, mis, tu, su, nuestro or nuestra, then up to three words none of which is a + tool or data word (query, queries, request, requests, tool, tools, debugger, profiler, flag, + flags, option, options, filter, regex, pattern, test, tests, sample, samples, fixture, + fixtures, copy, dry-run, verbose, breakpoint, breakpoints, log, logs, trace, traces, timeout, + value, values, file, files, path, url, page, browser, devtools, inspector, sql, http, https, + curl, grep, jq, python, json, yaml, metrics, dashboard, schema, data, dataset, input, inputs, + payload, x, strace, gdb, tcpdump, wireshark, consulta, petición, registro, registros, + archivo, archivos, datos, prueba, pruebas, herramienta, previous, last, earlier, baseline, + run, runs, version, versions, build, builds, output, outputs, result, results, commit, branch, + main, snapshot, reference, expected, original, anterior, versión, resultado, resultados), a + flag starting "-", a number or inline code, and none of which names people (team, teams, + owner, owners, maintainer, maintainers, officer, officers, group, folks, people, staff, + department, committee, crew, squad, lead, leads, manager, managers, admin, admins, author, + authors, reviewer, reviewers, user, users, vendor, supplier, client, customer, customers, + support, lawyer, attorney, accountant, doctor, dentist, nurse, airline, agent, broker, + contractor, landlord, bank, seller, buyer, boss, hr, equipo, responsable, dueño, cliente, + proveedor), which counts whatever else comes with it ("check with my lawyer", "check with the + data team", "verify the dates with the hotel" and "verificar con el fontanero" do not count; + "verify with a SQL query" and "compare with the previous run" do); "on" or "en" eBay, Amazon, + Craigslist, Etsy or Facebook Marketplace; paged or paging; on-call or "on call"; "alert page" + or "alert pages"; "page" or "pages" with sre, rotation, engineer, duty, team, secondary or + primary within the next 40 characters of the sentence; "page" and (optionally the, a, an, our) + engineer, team, someone, somebody, him, her, them or ops (a page to read does not count); + order or orders (not "order to"); a live store, site, server, system, database, db, + environment or api; "on a" or "on an" and one or more of new, fresh, spot, gpu, cloud, + bigger, larger, then vm, instance, server, machine, box, node, cluster or pod ("check the logs on a node" + still counts); or an instance named with a digit ("a p4d instance"). Nor when the + "Next" line is a list item ("- Next: release notes"). The "Next" line is the last prose line + with such a lead at the start or after ".", "!", "?", ")" or an ellipsis; fenced blocks, + quotes, headings, tables and indented code are not read for it. The nudge it sends also tells + the model to answer `BLOCKED` when the step is the person's to take or needs their go-ahead; +- or the last sentence is first person and future ("I'll", "I will", "I'm going to", "I'm about + to", "let me"; "voy a", "vamos a", "procedo a", "déjame", or a future in -aré/-eré/-iré), with + or without a time cue ("The test hangs. I'll fix the call that is waiting on the lock.", + "Encontré el error. Voy a corregirlo en el paginador."), or says the work is under way + ("Running the tests now.", "Ejecutando las pruebas ahora."). After an acknowledgement opener + ("Understood", "Got it", "Sure", "Noted", "Perfecto", "Entendido", "Claro") a habit or + preference does not count ("Understood, I'll use tabs.", "Noted. I will avoid force pushes.", + "Perfecto, así lo haré."); real work still does ("Understood. I'll fix the paginator."). A + heading line is not a sentence: "Moving on to the parser." followed by "## Next steps" still + counts, and a heading alone does not. + +None of these count, whatever else the reply says: a question, a request, a permission ask or a +condition on you in the last four sentences ("Reply yes and I'll run it", "after your go-ahead", +"with your permission", "once you confirm", "if you approve", "pick an option and I'll…", "tell +me", "let me know", "please", "pásame el archivo y…", "dime", "avísame", "cuando me confirmes", +"si me das permiso"; "when you're offline" is not a condition); a bare acknowledgement ("Understood. +I'll…", "Perfecto, así lo haré"); an offer of availability ("I'll be here", "I'll answer any +questions", "aquí estaré"); a standing habit or another day ("from now on", "next time", "next +week", "de ahora en adelante"); talk the reply delivers itself ("let me explain", "let me add one +caveat:", "I'll need your API key", "ahora voy a explicarte"); a first-person future that is a +condition ("if needed", "unless", "si quieres"); text in quotes, in inline code or in a code +block; and a drafted message (a "Subject:" line, a greeting line such as "Hi Sam,", the text +under "Here's a draft:", or a reply that closes with "Best," and a name). A trailing "and let you +know the results" or "y te aviso del resultado" does not cancel a step. A +missed announcement ends the turn as it always did, and a false match costs one model call, so the +rules lean to missing. + **A delegated child runs inside these caps too.** The `delegate` tool starts a one-level child on the worker tier. It gets at most 8 model calls. Its calls count on the session's `max_iterations` together with the parent's, and the cap, spend and wall clock are checked before each of its calls the same diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index df93572a..bfca7b39 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -15980,6 +15980,38 @@ A11Y-03's Fix ("make an accidental cancel recoverable") and INTERACT-01 (b), con **Size:** 1 · **Status:** In review +### TD-5428 — A reply that says it will continue is followed through, not shown as finished + +From live use: a model ended its turn on a reply with no tool call that said it was still working and what it would do next, and the chat showed the turn as finished. The manager's ask. + +- [x] A follow-through check on interactive turns, sharing the progress guard's CONTINUE/DONE/BLOCKED protocol: when the final tool-free reply announces next steps ("next I'll", "I'm still working", "now I will", "let me now"; or a first-person future in the last sentence (an acknowledgement followed by a habit, such as "Understood, I'll use tabs.", does not count; "Understood. I'll fix the paginator." does); or "Running the tests now."), and on no other reply, the model gets one short tool-free nudge to carry on with the step it announced, or answer DONE or BLOCKED. A hand-back or permission ask ("Reply yes and I'll run it", "with your permission", "once you confirm"), a bare acknowledgement ("Understood. I'll use tabs."), an offer, a standing habit, text in quotes or code, and a drafted message never trigger it (docs/configuration.md lists the exact rules). +- [x] No per-turn limit (the owner: "If there is work still to do then it should not stop and just do it"): every announcing stop is nudged, and the nudge does not spend the progress guard's windows; a repeated next step pauses, and the model-call budget and other caps still apply. It runs with skip-all too (the manager's correction: the owner runs with approvals off, and the nudge is not a cap); never for autonomy or delegates. +- [x] A DONE answer replaces the reply on its bubble; an answer with no label, or a check cut off at the token limit, never does (never a second copy of it); BLOCKED adds under it. If the model still stops, the turn ends and the window marks that reply "Stopped after saying it would continue", with a Continue button (the stopped turn's Continue, TD-5417) that stays while only notices follow the reply. +- [x] Detection is a short phrase list plus "the last sentence is first-person future, or work under way", in English and Spanish (narrowed from "the last sentence is future tense" by hand-back, permission, acknowledgement, quote and draft exclusions; DECISIONS.md). Each detection is logged with the matched phrase, and one table of whole reply texts is the source of truth: those that must trigger, those that must not ("I'll be here if you need anything", hand-backs, acknowledgements, drafts, quotes) and those left out on purpose. + +**Size:** 3 · **Status:** In review + +### TD-5430 — Continue after a reply that stopped short resumes the same turn + +TD-5428's Continue (the manager accepted it for 0.5.14: "A new turn in the same chat is fine for 0.5.14. The model keeps the whole conversation, which is what matters") starts a new turn in the same chat, with fresh counters and a fresh nudge. This story makes it reopen the ended turn instead: a protocol message and daemon state to resume a turn that ended on "Stopped after saying it would continue". + +- [ ] Continue on a marked reply resumes that turn (its counters and its "Worked for" time), not a new one. +- [ ] A test resumes a marked turn and checks it is the same turn. + +**Size:** 3 · **Status:** Ready + +### TD-5437 — A reply that ends on "Next: " is followed through + +From live use (the owner: "Why am I having to type continue so often? If there is work to do the model should just continue"): in one long chat, six of nineteen turns ended with no tool call on a closing "Next: " line or "The remaining work is …", and TD-5428's check passed them all, so the turn showed as finished and the owner typed "continue". The progress check writes its own notes as "Next: ", and the model copies that form. + +- [x] A closing "Next" line ("Next:", "Next step:", "Next up:", "Next action:", "Next step -", "Siguiente paso:", "Próximo paso:"), or "The next step is" / "The remaining step is" / "The remaining work is" / "El siguiente paso es", triggers the check only when its step is read-only or diagnostic: a look-up verb (locate, inspect, read, check, search, grep, fetch, trace, compare, reproduce, verify and the rest of the list in docs/configuration.md), running the tests, suite, linter or build, or a read-only command in inline code (web_fetch, grep, ls, git log, gh pr view …). A step that changes something does not count, so a misread costs a look, never a merge, a payment or a deletion (review round 3: no word list could catch every person-owned step, such as "upload to TestFlight" or "`terraform apply`"). +- [x] Even a read-only step does not count when the raw text from the paragraph above the "Next" line's paragraph to the end of the reply, code, quotes and fences included, holds anything a person owns (English and Spanish stems, and "you/your/tu/usted"), or when that line is a list item. The "Next" line is found among prose lines only, never inside a fence, quote, heading or table. +- [x] One action only (review rounds 4 and 5): the "Next" line must be the reply's last sentence; after any join (and, then, a comma, colon, semicolon, dash, "&", "+", "or", "to", "by", "with", "so" and the rest in docs/configuration.md) comes another look-up, a check run, an article, a number, code or a thinking word, never a new verb ("Next: inspect the VM and terminate it", "Next: inspect the cert to renew it"). Every inline code span to the end of the reply is a name or read-only commands, chained or piped, with no redirect or substitution; a bare word such as `make` is a command (`cat install.sh | sh`, `ls && terraform apply`, "verify with `./apply.sh`" do not count). The deny check reads the paragraph above too, splits `snake_case` and dotted names, and a step that reaches someone (a vendor, a doctor, "my lawyer", a named person, a marketplace, paging the on-call engineer, an order, a live store) or a machine that costs money (on a new, spot or GPU VM or instance, an instance named with a digit) does not count; code right after the lead must be a read-only command, never a name such as `bin/setup` (review round 6). Review round 7: anyone after "with" counts as contact unless a tool or data word follows ("check with the plumber" does not count; "verify with a SQL query" does); pages to a person, "on call" and paging services count as contact; rewriting tools (--fix, --write, ruff format) and scripts under bin/ or scripts/ count as changes; changes are read from the "Next" paragraph on, so "Installed X." above "Next: run the tests" does not stop it. A fenced or indented block after the "Next" line never counts. +- [x] The follow-through nudge tells the model to answer BLOCKED when the step is the person's to take or needs their go-ahead. +- [x] Of the chat's nineteen endings, three that stopped on a read-only "Next" step now trigger ("Next: Locate…", "Next: Reproduce…", "Next: `web_fetch …` to enumerate…"). Three do not, by design: "Next: Inspect … to recover what remains" (a purpose clause), "Next: enable … then restart TST Desk" and "The remaining work is ensuring …". The other thirteen (reports, and questions to the owner) still do not. The table holds every case from the seven review rounds. + +**Size:** 1 · **Status:** In review + ### TD-5427 — A web view that cannot draw is relaunched without compositing, never left blank From a live Linux install: the WebKitGTK web process aborted at start ("Could not create default EGL display: EGL_BAD_PARAMETER. Aborting..."), the window showed only the File and Edit menu, nothing said why, and the host still logged "connected to tstd". The manager's requirements: diff --git a/ui/src/lib/chat-events.ts b/ui/src/lib/chat-events.ts index aec9d2ee..033eeaf1 100644 --- a/ui/src/lib/chat-events.ts +++ b/ui/src/lib/chat-events.ts @@ -8,7 +8,7 @@ import { endSafeStart, holdsAutoBind } from "./safe-start.svelte.js"; import type { BranchSnaps } from "./chat-fork"; import { applyHeldList, clearHeldPending } from "./chat-held"; import { applyHistory, nextUserIndex, noteTrimmed } from "./chat-history"; -import { markResponse, withdrawResponse } from "./chat-retract"; +import { FOLLOW_THROUGH_REPLACED, markResponse, withdrawResponse } from "./chat-retract"; import type { ChatMessage, ChatState, ToolBlock } from "./chat-store"; import type { MessageQueue } from "./chat-queue"; import { toChips, type AttachmentChip } from "./attachments"; @@ -201,6 +201,17 @@ function sealInFlightAssistant(state: ChatState): void { } } +/** TD-5428: mark the reply a turn stopped short on. A user row met first + * means the turn wrote no reply, and an earlier turn's is left alone. */ +function markStoppedShort(state: ChatState): void { + for (let i = state.messages.length - 1; i >= 0; i--) { + const row = state.messages[i]; + if (row.role === "notice") continue; + if (row.role === "assistant") row.stoppedShort = true; + return; + } +} + /** A refusal of a user_message (TD-5112). Every one names `in_reply_to`; an * attachment code says so too, for a computer on an older daemon. */ function refusesSend(event: Extract): boolean { @@ -435,6 +446,13 @@ export function applyChatEvent(ctx: ChatEventContext, event: DaemonEventUnion): // it spent the output limit thinking (TD-5233): its text and thinking // come off the row, and the daemon is asking again. Until the retry's // first token the Working line says so, in the reason's words. + if (event.reason === FOLLOW_THROUGH_REPLACED) { + // TD-5428: the follow-through check's answer takes this reply's + // place, and arrives next. Nothing is asked again, and the thinking + // stays with the reply it led to. + withdrawResponse(state.messages, event.response_id, true); + return; + } withdrawResponse(state.messages, event.response_id); state.turnState = "running"; wait.begin(event.reason); @@ -448,6 +466,7 @@ export function applyChatEvent(ctx: ChatEventContext, event: DaemonEventUnion): case "turn_complete": { if (event.session_id !== state.sessionId) return; sealInFlightAssistant(state); + if (event.stopped_after_continue === true) markStoppedShort(state); wait.end(); // The turn is provably over; the session itself stays alive. state.turnState = null; diff --git a/ui/src/lib/chat-message.ts b/ui/src/lib/chat-message.ts index 3f9c26c2..8892ef33 100644 --- a/ui/src/lib/chat-message.ts +++ b/ui/src/lib/chat-message.ts @@ -76,6 +76,10 @@ export interface ChatMessage { /** Daemon-issued id for this user turn. Stamps a local echo so replay * of `user_turn` does not duplicate the row. */ turnId?: string; + /** On an assistant row: its turn ended on a reply that announced a next + * step (TD-5428, `turn_complete.stopped_after_continue`). The row says so + * and, while it is the last one, offers Continue. */ + stoppedShort?: boolean; /** Where the latest model response began on this assistant row, so an * `assistant_retract` can take it back off (TD-5159, chat-retract.ts). */ responseMark?: ResponseMark; diff --git a/ui/src/lib/chat-retract.test.ts b/ui/src/lib/chat-retract.test.ts index 3164747a..ca8a6be1 100644 --- a/ui/src/lib/chat-retract.test.ts +++ b/ui/src/lib/chat-retract.test.ts @@ -233,3 +233,32 @@ describe("a reply that spent the output limit thinking", () => { expect(state.awaitingFirstToken).toBe(false); }); }); + +describe("a reply the follow-through check replaces (TD-5428)", () => { + const REPLACED = "follow_through_replaced"; + + it("has its text taken off and the answer in its place, with the thinking kept", () => { + const { state, apply, reply } = bound(); + apply( + thinking("Weighing the owners", "r1"), + delta("Next I'll group them by owner.", "r1"), + retract("r1", REPLACED), + ); + // Nothing is asked again: no Working line, no retry. + expect(state.awaitingFirstToken).toBe(false); + expect(state.retryingReply).toBe(false); + expect(reply().text).toBe(""); + + apply(delta("Three owners hold the open actions."), turnComplete()); + expect(reply().text).toBe("Three owners hold the open actions."); + expect(reply().parts).toEqual([{ kind: "text", text: "Three owners hold the open actions." }]); + expect(reply().reasoning).toBe("Weighing the owners"); + expect(state.messages.filter((m) => m.role === "assistant")).toHaveLength(1); + }); + + it("is a quiet row on the timeline, not a provider fault", () => { + const entry = eventToEntry(retract("r1", REPLACED)); + expect(entry?.title).toBe("Reply replaced"); + expect(entry?.preview).toContain("follow-through"); + }); +}); diff --git a/ui/src/lib/chat-retract.ts b/ui/src/lib/chat-retract.ts index 73ca3121..20630058 100644 --- a/ui/src/lib/chat-retract.ts +++ b/ui/src/lib/chat-retract.ts @@ -7,8 +7,12 @@ // began, and a retract for that id cuts the row back to the note: its text, // its thinking and the text parts it opened. Tool calls never arrive inside a // response (their `tool_call` comes after it ends), so a tool that already ran -// stays on the row. Text with no id (a failure line, a progress note, an older -// daemon) never starts a response and is never withdrawn. +// stays on the row. Text with no id (a failure line, an older daemon) never +// starts a response and is never withdrawn. +// +// The follow-through check (TD-5428) withdraws a reply the same way when its +// own answer takes the reply's place. Nothing is asked again then, so the +// Working line does not come back, and the thinking behind the reply stays. import type { ChatMessage } from "./chat-message"; @@ -21,6 +25,9 @@ export function retryLine(reason: string | null): string { return "Reply interrupted. Asking again"; } +/** The retract reason for a reply the follow-through check's answer replaces. */ +export const FOLLOW_THROUGH_REPLACED = "follow_through_replaced"; + /** Where one model response began on a row: the lengths it found. */ export interface ResponseMark { id: string; @@ -56,14 +63,18 @@ export function markResponse(row: ChatMessage, responseId: string | null | undef * now while the response streamed (TD-1704) puts a user row in the middle, * so its later deltas open a second row: both are withdrawn (TD-5160). * False when no row does: the deltas were never seen, or already gone. */ -export function withdrawResponse(messages: ChatMessage[], responseId: string): boolean { +export function withdrawResponse( + messages: ChatMessage[], + responseId: string, + keepThinking = false, +): boolean { let found = false; for (let i = messages.length - 1; i >= 0; i--) { const row = messages[i]; if (row.role !== "assistant") continue; const mark = row.responseMark; if (mark === undefined || mark.id !== responseId) continue; - cutBack(row, mark); + cutBack(row, mark, keepThinking); found = true; // An earlier row the response alone filled would stay as an empty // bubble; the newest one is where the retry's text arrives. @@ -81,15 +92,17 @@ function isBlank(row: ChatMessage): boolean { ); } -function cutBack(row: ChatMessage, mark: ResponseMark): void { +function cutBack(row: ChatMessage, mark: ResponseMark, keepThinking: boolean): void { row.text = row.text.slice(0, mark.text); - if (mark.reasoning === null) { - delete row.reasoning; - } else if (row.reasoning !== undefined) { - row.reasoning = row.reasoning.slice(0, mark.reasoning); + if (!keepThinking) { + if (mark.reasoning === null) { + delete row.reasoning; + } else if (row.reasoning !== undefined) { + row.reasoning = row.reasoning.slice(0, mark.reasoning); + } + setOrDelete(row, "reasoningStartedAt", mark.reasoningStartedAt); + setOrDelete(row, "reasoningMs", mark.reasoningMs); } - setOrDelete(row, "reasoningStartedAt", mark.reasoningStartedAt); - setOrDelete(row, "reasoningMs", mark.reasoningMs); const parts = row.parts; if (parts !== undefined) { parts.splice(mark.parts); diff --git a/ui/src/lib/chat-stopped-short.test.ts b/ui/src/lib/chat-stopped-short.test.ts new file mode 100644 index 00000000..d82f2fb9 --- /dev/null +++ b/ui/src/lib/chat-stopped-short.test.ts @@ -0,0 +1,205 @@ +// @vitest-environment jsdom +// +// TD-5428: a turn that ends on a reply announcing a next step is marked on +// that reply, with Continue. The chat pane is mounted for real; only the +// socket is faked. + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { flushSync, mount, unmount } from "svelte"; +import type { ClientMessageUnion, DaemonEventUnion } from "./protocol"; + +const mocks = vi.hoisted(() => ({ + handlers: new Set<(event: DaemonEventUnion) => void>(), + sent: [] as Record[], +})); + +vi.mock("./connection-status.svelte.js", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + onDaemonEvent: (handler: (event: DaemonEventUnion) => void) => { + mocks.handlers.add(handler); + return () => mocks.handlers.delete(handler); + }, + sendToDaemon: (msg: ClientMessageUnion) => (mocks.sent.push(msg as unknown as Record), true), + attachToSession: () => {}, + detachFromSession: () => {}, + }; +}); + +// jsdom has no layout, so the virtualizer would render no row at all. +vi.mock("@tanstack/svelte-virtual", async () => { + const { readable } = await import("svelte/store"); + return { + createVirtualizer: () => { + let count = 0; + let notify: (() => void) | null = null; + const api = { + setOptions: (options: { count: number }) => { + count = options.count; + notify?.(); + }, + getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, key: index, start: 0 })), + getTotalSize: () => 0, + measureElement: () => {}, + scrollToIndex: () => {}, + }; + return readable(api, (set) => { + notify = () => set({ ...api }); + return () => (notify = null); + }); + }, + }; +}); + +import ChatPane from "./components/chat/ChatPane.svelte"; +import { ws } from "./connection-status.svelte.js"; + +const MARKER = "Stopped after saying it would continue"; + +let app: ReturnType | null = null; +let seq = 1; + +function emit(event: Record): void { + seq += 1; + const full = { session_id: "s1", seq, ...event } as DaemonEventUnion; + for (const handler of [...mocks.handlers]) handler(full); + flushSync(); +} + +function markers(): HTMLElement[] { + return [...document.querySelectorAll(".stopped-short")]; +} + +function continueButtons(): HTMLButtonElement[] { + return markers().flatMap((m) => [...m.querySelectorAll("button")]); +} + +function turn(turnId: string, reply: string, marked?: boolean): void { + emit({ type: "user_turn", turn_id: turnId, content: `ask ${turnId}` }); + emit({ type: "assistant_delta", delta: reply, response_id: `r-${turnId}` }); + emit({ type: "turn_complete", duration: 66, failed: false, error_code: null, stopped_after_continue: marked }); +} + +beforeEach(() => { + mocks.handlers.clear(); + mocks.sent.length = 0; + const data = new Map(); + const storage: Storage = { + getItem: (key) => data.get(key) ?? null, + setItem: (key, value) => void data.set(key, value), + removeItem: (key) => void data.delete(key), + clear: () => data.clear(), + key: (index) => [...data.keys()][index] ?? null, + get length() { + return data.size; + }, + }; + Object.defineProperty(window, "localStorage", { configurable: true, value: storage }); + if (typeof globalThis.ResizeObserver === "undefined") { + globalThis.ResizeObserver = class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} + } as unknown as typeof ResizeObserver; + } + ws.state = "connected"; + app = mount(ChatPane, { target: document.body }); + flushSync(); + emit({ + type: "session_list", + sessions: [ + { + session_id: "s1", + workspace_path: "/workspace", + state: "idle", + created_at: "2026-11-04T10:00:00Z", + updated_at: "2026-11-04T10:00:00Z", + event_count: 0, + archived: false, + starred: false, + }, + ], + }); +}); + +afterEach(() => { + if (app !== null) { + unmount(app); + app = null; + } + ws.state = "disconnected"; + document.body.innerHTML = ""; +}); + +describe("a reply that stopped after saying it would continue", () => { + it("carries the marker, on that reply only", () => { + turn("t1", "Three actions are open."); + turn("t2", "Next I'll group them by owner.", true); + expect(markers()).toHaveLength(1); + // Rows: ask t1, its reply, ask t2, its reply. + expect(markers()[0].closest("[data-index]")?.getAttribute("data-index")).toBe("3"); + expect(markers()[0].textContent).toContain(MARKER); + }); + + it("has no marker when the daemon does not say so", () => { + turn("t1", "Next I'll group them by owner."); + turn("t2", "Done.", false); + expect(markers()).toHaveLength(0); + expect(document.body.textContent).not.toContain(MARKER); + }); + + it("offers Continue, which sends an ordinary message once", () => { + turn("t1", "Next I'll group them by owner.", true); + const [button] = continueButtons(); + expect(button.textContent?.trim()).toBe("Continue"); + expect(button.disabled).toBe(false); + mocks.sent.length = 0; + button.click(); + flushSync(); + expect(mocks.sent.filter((m) => m.type === "user_message").map((m) => m.content)).toEqual(["Continue"]); + // Its own message is now the last row: the marker stays, the button goes. + expect(markers()).toHaveLength(1); + expect(continueButtons()).toHaveLength(0); + }); + + it("waits, disabled, while nothing can be sent", () => { + turn("t1", "Next I'll group them by owner.", true); + ws.state = "reconnecting"; + flushSync(); + expect(continueButtons()[0].disabled).toBe(true); + }); + + it("keeps an older reply's marker without its button", () => { + turn("t1", "Next I'll group them by owner.", true); + turn("t2", "Grouped."); + expect(markers()).toHaveLength(1); + expect(continueButtons()).toHaveLength(0); + }); + + it("keeps Continue when a notice comes after the marked reply", () => { + emit({ type: "assistant_model", response_id: "r-a", tier: "brain", model: "big" }); + turn("t1", "Next I'll group them by owner.", true); + // A hand-over to another tier is a notice row, no one's message. + emit({ type: "assistant_model", response_id: "r-b", tier: "worker", model: "small" }); + expect(document.querySelectorAll('[role="note"]')).toHaveLength(1); + expect(markers()).toHaveLength(1); + const [button] = continueButtons(); + expect(button.textContent?.trim()).toBe("Continue"); + expect(button.disabled).toBe(false); + }); + + it("loses Continue once anyone says something after the marked reply", () => { + turn("t1", "Next I'll group them by owner.", true); + emit({ type: "user_turn", turn_id: "t2", content: "wait" }); + expect(markers()).toHaveLength(1); + expect(continueButtons()).toHaveLength(0); + }); + + it("marks no earlier reply when the turn wrote none", () => { + turn("t1", "Three actions are open."); + emit({ type: "user_turn", turn_id: "t2", content: "more" }); + emit({ type: "turn_complete", duration: 1, stopped_after_continue: true }); + expect(markers()).toHaveLength(0); + }); +}); diff --git a/ui/src/lib/chat-store.ts b/ui/src/lib/chat-store.ts index 9a1173f3..7d7625cf 100644 --- a/ui/src/lib/chat-store.ts +++ b/ui/src/lib/chat-store.ts @@ -126,8 +126,10 @@ export interface ChatStore { * one fails its caps or its text test (TD-1709). */ sendUserMessage(text: string, attachments?: readonly NewAttachment[]): boolean; retryLastUserMessage(): boolean; - /** Pick up a turn a restart cut off (TD-5019): an ordinary "Continue" - * message the user clicked, through the same path as any other send. */ + /** Pick up a turn a restart cut off (TD-5019), one the user stopped + * (TD-5417) or one that stopped after saying it would continue (TD-5428): + * an ordinary "Continue" message the user clicked, through the same path + * as any other send. */ continueTurn(): boolean; /** The draft or the queue changed: save them once typing settles. */ keepDraft(): void; diff --git a/ui/src/lib/components/chat/ChatPane.svelte b/ui/src/lib/components/chat/ChatPane.svelte index f2b76c72..987c3393 100644 --- a/ui/src/lib/components/chat/ChatPane.svelte +++ b/ui/src/lib/components/chat/ChatPane.svelte @@ -220,6 +220,7 @@ messages={chat.messages} turnLive={showCancel(chat.turnState)} onretry={retryLastUserMessage} + oncontinue={sendable ? continueTurn : undefined} /> {/if} diff --git a/ui/src/lib/components/chat/MessageBubble.svelte b/ui/src/lib/components/chat/MessageBubble.svelte index 95e085bf..b3794e10 100644 --- a/ui/src/lib/components/chat/MessageBubble.svelte +++ b/ui/src/lib/components/chat/MessageBubble.svelte @@ -27,19 +27,26 @@ import ToolFold from "./ToolFold.svelte"; import CheckFold from "./CheckFold.svelte"; import NoticeRow from "./NoticeRow.svelte"; + import StoppedShort from "./StoppedShort.svelte"; let { message, first = false, + last = false, turnLive = false, onretry, + oncontinue, }: { message: ChatMessage; /** First row of the conversation: suppresses the turn hairline. */ first?: boolean; + /** Last row of the conversation that is somebody's message, notices aside: + * Continue is offered here only (TD-5428). */ + last?: boolean; /** A turn is in flight: retry stands down (TD-1606). */ turnLive?: boolean; onretry?: () => void; + oncontinue?: () => void; } = $props(); let editing = $state(false); @@ -180,6 +187,9 @@ aria-hidden="true">▍{/if} {/if} + {#if message.stoppedShort} + + {/if} {#if message.complete}
{/each} diff --git a/ui/src/lib/components/chat/StoppedShort.svelte b/ui/src/lib/components/chat/StoppedShort.svelte new file mode 100644 index 00000000..e3655cb2 --- /dev/null +++ b/ui/src/lib/components/chat/StoppedShort.svelte @@ -0,0 +1,63 @@ + + +
+ Stopped after saying it would continue + {#if offer} + + {/if} +
+ + diff --git a/ui/src/lib/protocol-fixtures.json b/ui/src/lib/protocol-fixtures.json index d472fd48..99b4c628 100644 --- a/ui/src/lib/protocol-fixtures.json +++ b/ui/src/lib/protocol-fixtures.json @@ -1592,7 +1592,8 @@ "tier": "worker", "duration": 2.5, "failed": false, - "error_code": null + "error_code": null, + "stopped_after_continue": true }, "turn_complete_failed": { "type": "turn_complete", @@ -1603,7 +1604,8 @@ "tier": "brain", "duration": 0.4, "failed": true, - "error_code": "auth_failed" + "error_code": "auth_failed", + "stopped_after_continue": false }, "tier_state": { "type": "tier_state", diff --git a/ui/src/lib/protocol.test.ts b/ui/src/lib/protocol.test.ts index 1820896b..1d9d8385 100644 --- a/ui/src/lib/protocol.test.ts +++ b/ui/src/lib/protocol.test.ts @@ -1042,6 +1042,7 @@ describe("Daemon event fixtures match TypeScript types", () => { expect(isBoolean(m.failed)).toBe(true); expect(m.failed).toBe(false); expect(m.error_code).toBeNull(); + expect(m.stopped_after_continue).toBe(true); expect(isNumber(m.seq)).toBe(true); }); diff --git a/ui/src/lib/protocol.ts b/ui/src/lib/protocol.ts index adc1975d..e12f1a6c 100644 --- a/ui/src/lib/protocol.ts +++ b/ui/src/lib/protocol.ts @@ -2310,6 +2310,9 @@ export interface TurnComplete extends DaemonEvent { // notifications can key tailored copy off the typed cause. failed: boolean; error_code: string | null; + /** TD-5428: the reply announced a next step and the turn ended there; the + * window marks it and offers Continue. Older daemons omit it. */ + stopped_after_continue?: boolean; } export interface SteeringReloaded extends DaemonEvent { diff --git a/ui/src/lib/timeline.ts b/ui/src/lib/timeline.ts index b29dd9b2..200abe1e 100644 --- a/ui/src/lib/timeline.ts +++ b/ui/src/lib/timeline.ts @@ -21,6 +21,7 @@ import type { ContextCompacted, DaemonEventUnion, AfterWriteRun, ModelFallback, SessionState, TurnComplete, UserTurn } from "./protocol"; import { formatTokens } from "./context-gauge"; +import { FOLLOW_THROUGH_REPLACED } from "./chat-retract"; /** Presentation category driving visually distinct treatment (AC #6). * `turn` is the group header the other kinds sit under: one per user @@ -219,6 +220,7 @@ function retractTitle(reason: string): string { if (reason === "stream_interrupted") return "Reply cut off"; if (reason === "reply_guarded") return "Reply guard cut the reply"; if (reason === "output_cap_thinking") return "Thinking used the output limit"; + if (reason === FOLLOW_THROUGH_REPLACED) return "Reply replaced"; return "Provider went quiet"; } @@ -226,6 +228,7 @@ function retractTitle(reason: string): string { * wrote no answer to withdraw; its retry gets a larger limit (TD-5233). */ function retractPreview(reason: string): string { if (reason === "output_cap_thinking") return "Asking again with a larger output limit."; + if (reason === FOLLOW_THROUGH_REPLACED) return "The follow-through check's answer took its place."; return "The partial reply was withdrawn; asking again."; }