Skip to content

feat: /stop ends the turn and has a read-only sub-agent review it - #162

Open
royosherove wants to merge 7 commits into
mainfrom
feat/stop-and-review
Open

royosherove wants to merge 7 commits into
mainfrom
feat/stop-and-review

Conversation

@royosherove

@royosherove royosherove commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

What

/stop [question] ends the turn in progress the way /cancel does, then hands what the agent did so far to a read-only reviewer sub-agent and posts its report in the chat.

  • The reviewer has read, grep, find, ls only: no shell, no edits, no MCP, and none of the working directory's AGENTS.md/CLAUDE.md, prompt templates, themes or project settings (--tools … --no-mcp --no-context-files --no-prompt-templates --no-themes --no-approve).
  • It gets the turn as turn.md in its run folder: the exchange just before the turn (so a request like "yes" can be understood), then the owner's request and every step (what was said, which tool was called with what, what came back). Long output is shortened, every line sits behind │ so tool output cannot pass for the transcript's structure, and obvious secrets are removed.
  • It answers in six parts: asked / done so far / doing when stopped / problems / left behind / suggestion. /stop why did it touch the router? makes it answer that too.
  • The report is posted as it is (secrets removed again, titled with the time of the stop) and starts no agent turn. The agent hears about the stop with the owner's next message, and gets the report as data (<stop_review>, </> replaced) with the first message after it arrives. Each once, in memory.
  • Every stopped turn gets its own review, up to two running at a time. /stop on a turn that is already stopped tells the agent to stop again and starts nothing else.

Supporting changes: AgentAdapter.describeTurn() (pi: from session.messages, not queued behind the running turn, with reached/requestAt so a turn whose request is not yet in the conversation is not confused with the one before it); PromptHooks.onStart and AdapterInfo.reportsPromptStart; SpawnSpec.tools, .files, .delivery (stored in status.json, so a restart between spawn and completion still posts); /stop in Telegram's menu; README, CHANGELOG, CLAUDE.md.

Also fixed on the way (older than /stop)

  • A request cancelled before it had started ran anyway, unseen. /cancel on a message that was still waiting (behind a memory save, or while its session was opening) aborted what was running; the waiting request then ran in full with nobody reading its output. The pi adapter now drops a streamed prompt that was asked for before its thread was aborted, and aborts again a run that begins after the abort. What such a message carried (the memory files, a note about an earlier stop) goes with the next message.
  • /cancel could act on the wrong turn. A sub-agent's result arriving while a turn ran (or the owner's message during a result's turn) took the running turn's place as "the turn in this chat". A turn now takes that place when it gets the thread lock.
  • A prompt that failed before it started lost the memory files it carried, and its error. When the session would not open, or pi's own checks failed (expired credentials), the memory state already said "injected", so the next message went out without the files; and the stream could end before the error was recorded, so the owner saw "Agent returned no response". The gateway re-arms the injection on the error path too, the pi adapter counts a prompt as started only when pi reports it (preflightResult), and the error is recorded before the stream ends. (Found by the automated review of this PR.)
  • A sub-agent that hung was never cut off by the gateway that started it: the watcher skips runs started in the same process, and nothing else enforced their deadline. spawn() now arms a timer.
  • A sub-agent that could not start no longer leaves its run folder behind; its logs are created 0600.

How it was checked

  • 992 tests, typecheck clean at ef9e36f; CI test and secret-scan green. New: test/stop-review.test.ts, test/turn-transcript.test.ts, additions to test/subagents.test.ts, test/pi-adapter-session.test.ts, test/memory.test.ts, test/security-hardening.test.ts (a stranger cannot use /stop). Key tests were checked by breaking the code on purpose; the ones that passed without the fix were tightened.

  • Independent read-only reviewers, six rounds (sub-agents with read,grep,find,ls, on the diff):

    1. Correctness and security, two reviewers: one blocker (the report could close its own <stop_review> wrapper with nested tags) and eleven should-fix items.
    2. One reviewer on that fix: no blocker, seven should-fix items.
    3. One reviewer on the follow-up (4bb82c2, first version): one blocker (the "already stopped" answer skipped the abort).
    4. One reviewer on its fix: one blocker, older than this PR (the cancelled-before-start request above).
    5. One reviewer on the adapter and gateway change for that: no blocker, three should-fix items.
    6. One reviewer on ef9e36f (the fix for the automated review's first finding): no blocker, one should-fix item (a fallback that counted a put-off prompt as started), addressed before the push.

    All blockers and the should-fix items that held up are fixed; the commit messages list them. The fixes for round 5 (onStart, the second abort at agent_start, the runningTurns rule in both directions) were not reviewed again by these reviewers, except onStart, which round 6 covered.

  • Used live on the host that proposed it, seven stops on two builds of this branch: five on 95c76df (four near-empty turns, one long turn with 14 tool calls) and two on 4bb82c2 (one of them a 50-second counting script, stopped at 12: the process died with the stop and the report matched). Every report arrived and was accurate; the agent got the note and the report with the next message and did not resume.

Open

  • Automated review (Codex), second finding, P2, on ef9e36f: not fixed. When /stop is sent from a Telegram forum topic or a Slack reply thread, the routing keeps the chat or channel and drops the topic or thread, so the report is posted at the root of the chat. This is the first item under "Known limits" below. A fix would keep the originating thread id in the run's routing and post there; it can only be tested with fakes on the host that proposed this (private chats only).
  • Its first finding (memory not re-armed when a prompt fails before it starts) is fixed in ef9e36f and the thread is resolved.

Known limits

  • The report is posted to the chat, not to a forum topic or Slack thread. Use it in a private chat (chat.dmOnly).
  • Redaction is best effort; the reviewer is also told never to open or repeat credential files. turn.md is deleted after a delivered report (kept after a failed one, which the message points to).
  • The notes for the agent are in memory: a restart drops them.
  • With /topic active, a sub-agent's result runs on the chat's base session beside the topic's turn and takes the chat's record. With several private chats on one session, /cancel or /stop from the chat whose message is waiting also aborts the turn running for the other (as /cancel did before).
  • A memory save or cron prompt that is waiting in the queue is not cancellable (on purpose: a skipped save would be recorded as done).
  • Not tested live: Slack, groups, the kiro adapter, two reviews running at once, and the cancelled-before-start path against a real model (covered with a scripted SDK only).

Not published to npm; the publish workflow runs on v* tags only, so merging does not release anything by itself.

/stop does what /cancel does, then hands the turn so far to a reviewer
sub-agent that can read and search files and nothing else (pi --tools
read,grep,find,ls --no-mcp). The reviewer gets the owner's request and every
step as turn.md in its run folder, and answers in six parts: asked, done,
doing when stopped, problems, left behind, suggestion. An optional question
after the command is answered too.

The report is posted in the chat as it is and starts no agent turn, so the
agent that was stopped does not start working again because it arrived. The
agent is told with the owner's next message that the turn was stopped on
purpose, and given the report as data (once, in memory, dropped after 12 h).
A reviewer that fails, times out or cannot start is reported.

Supporting changes:
- AgentAdapter.describeTurn(), implemented for pi from session.messages (not
  queued behind the running turn); renderTurn() shortens tool output and drops
  the oldest steps first when the turn is long.
- SpawnSpec.tools, .files and .delivery. The delivery is stored in status.json
  so a restart between spawn and completion still posts the report.
- The sub-agent launch notice is skipped for chat deliveries.
- /stop in Telegram's command menu, README, CHANGELOG, CLAUDE.md.

Tests: stop-review (15), turn-transcript (11), sub-agent launcher and files,
the pi adapter's describeTurn, and /stop among the commands a stranger cannot
use. 918 passing, typecheck clean.
Two read-only reviewers went through the change. One blocker and the should-fix
findings that held up are addressed:

Blocker
- The report's wrapper could be closed from inside it (`</stop_</stop_review>review>`
  survives a single replace). The report text now has `<` and `>` replaced.

Security
- Secrets: the transcript the reviewer reads, the report posted to the chat and
  the note handed to the agent have bot tokens, API keys, passphrases and
  private keys removed (best effort); the reviewer is told never to open or
  repeat credentials; turn.md is deleted once the report is out.
- The transcript's structure could be forged by tool output: every line of
  request, speech, call and result now sits behind "│ ".
- An earlier stop's note and report are not shown as the owner's words.
- The reviewer no longer loads AGENTS.md/CLAUDE.md, prompt templates or themes
  from the working directory (--no-context-files and friends): the agent under
  review could have written them.
- Run folders: logs created 0600; no folder left behind when nothing started;
  reserved file names compared case-insensitively (APFS).
- One review at a time; a second /stop in the abort window is turned away.

Correctness
- /stop before the turn reached the model reviewed the previous turn; it now
  only stops, and says so.
- The reviewed turn could be a request that began while the abort settled; the
  snapshot from before the abort is used when the request differs.
- The agent's note is set in the same tick as the abort, is no longer taken by
  a turn that is then dropped, is applied after transcription (a voice-only
  message kept its transcript out otherwise), only promises a reviewer once one
  has started, and a late report no longer repeats "do not resume".
- A tool call with no result is marked as possibly not run.
- A hung sub-agent was never cut off by the gateway that started it (the watcher
  skips in-process runs); spawn() now arms its deadline.

Known and documented: the report is posted to the chat, not to a forum topic or
Slack thread (the host runs with chat.dmOnly).

947 tests passing, typecheck clean.
A third read-only reviewer checked the first fix commit against the eleven earlier
findings and looked for what the fix introduced. No blocker; the should-fix items
that held up:

- A note is used up only when the turn that carries it starts (peek/commit): a
  message dropped between reading and prompting leaves it for the next one, and a
  turn aborted during transcription or memory preparation no longer takes it.
- /stop deciding whether to start a reviewer ("pending") no longer lets the owner's
  next message delete the record and hide the review from a second /stop; a report
  nobody has passed on yet survives a newer /stop.
- The turn whose request is not yet in the conversation is detected from the pi
  adapter (promptStartedAt against the last user message's timestamp), not only from
  a flag that is set slightly too early; snapshots are told apart by requestAt, so
  two turns with the same words are not mixed up.
- A message that never reached the agent is described as cancelled, not "stopped".
- Redaction: bot tokens inside URLs and ending in "-", escaped JSON (curl -d '{…}'),
  lower-case password=/api_key:, URL user info, curl -u. Counts such as "tokens:
  1200" are left alone. Checked for backtracking on 200 KB hostile inputs (ms).
- The raw session file (unredacted) is no longer pointed out to the reviewer; error
  messages and role names go through the same quoting and redaction as the rest.
- --no-approve for the reviewer (project-local settings in the working directory).
- Test that passed without the fix (deadline timer cleared on exit) now fails
  without it; timer delay clamped to the 32-bit limit.

957 tests passing, typecheck clean.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T00:54:01.859562Z ef9e36f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

After /stop went live it was used five times; a reviewer could not tell what a
"Yes" referred to, and a second stop got advice it could not follow. Fixed
those, then had independent read-only reviewers go through the result three
times; each round's findings are fixed here.

The transcript the reviewer reads
- Begins with the exchange before the stopped turn (the previous request and
  the end of the assistant's last reply), as context only.
- The gateway's memory-save prompt is not the owner's request: it neither
  starts a turn nor counts as the previous exchange.
- A turn whose request was compacted away is described from the summary on,
  and says what is missing. pi's system-prompt records are not steps.
- Stop notes in the request become one neutral line; an earlier report goes.

Stops and reviews
- StopNotes keeps one record per stop: each stopped turn has its own review
  (up to two running) and its own report, matched by run id, titled with the
  time of its stop. The ceiling evicts unheard notes before running reviews.
- /stop on a turn that is already stopped starts nothing new, but still tells
  the agent to stop (it can be saving memory or compacting on its way out).
- A review that never reports stops counting as running after 15 minutes.

Found by the reviewers, older than /stop
- A request cancelled before it had started ran anyway, unseen: /cancel or
  /stop on a message waiting behind a memory save (or while its session was
  opening) aborted what was running, and the waiting request then ran in full
  with nobody reading. The pi adapter now drops a streamed prompt asked for
  before its thread was aborted, and aborts again a run that begins after it.
- What such a message carried is no longer lost: the adapter reports when the
  agent has a message (PromptHooks.onStart, AdapterInfo.reportsPromptStart);
  the /stop note is committed then, and a memory injection is re-armed if the
  turn ends without it.
- "Reached" is judged from when a prompt was asked for, not from when it left
  the queue, so a turn waiting behind a memory save is not taken for the one
  before it.
- A sub-agent's result arriving during a turn (or the owner's message during a
  result's turn) took the running turn's place in runningTurns, so /cancel and
  /stop acted on the waiting one. A turn now takes the place with the lock.

Not changed, known: with /topic active an injected turn runs on another
session beside the topic's turn and takes the chat's record; the non-streamed
prompt path is not cancellable while queued.

985 tests passing, typecheck clean. The last additions (onStart, the abort at
agent_start, the runningTurns rule for both directions) answer the third
round's findings and were not reviewed again.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4bb82c2bb8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gateway/gateway.ts Resolved
…ore it starts

The automated review of this PR found that when the memory files were injected
into a message and the prompt then failed before it started (for example while
the session was being opened), the memory state already said "injected" and
the re-arm added for cancelled prompts was only reached when the stream ended
normally. The next message went out without memory the agent never received.

- gateway: the re-arm runs on the way out of the turn whichever way that is
  (after the stream, and in the catch before the overflow recovery), once.
- pi adapter: "the agent has the message" is now pi's own word for it. The
  prompt is given `preflightResult`, and `onStart` fires on "started", which
  pi reports only after its checks (input hooks, model, credentials, the
  run's first messages). Before, it fired just ahead of `session.prompt()`,
  so a prompt that failed those checks (expired credentials) counted as
  delivered. A prompt an extension takes over, or one pi puts off, is not
  counted until pi says it started. The options are typed `PromptOptions`, so
  a pi without the callback fails the type check.
- pi adapter: an error from the prompt is recorded before the stream is
  marked done. It was recorded a few ticks later by a handler on the queue's
  promise, and a reader that asked for the next event in between saw an
  ordinary end: a prompt that failed before producing anything was shown as
  "Agent returned no response" and skipped the gateway's error path.

Tests: a gateway with memory on and an agent that reports its start (the files
go out once; again after a message that failed or was cancelled before it
started; not again after one that failed once the agent had it; a /stop note
is kept the same way), and the adapter against pi's dispositions (failed
checks, handled, put off). Each fix was removed in turn to see its test fail.
An independent read-only reviewer went through the change: no blocker; its one
should-fix (a fallback that counted a put-off prompt as started) is addressed.

992 tests passing, typecheck clean.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ef9e36f49b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +261 to +264
const id = typeof thread?.id === "string" ? thread.id : "";
const [transport, chatId] = id.split(":");
if ((transport !== "telegram" && transport !== "slack") || !chatId) return null;
return { transport, chatId, parentThreadId: agentThreadId };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the originating thread for review reports

When /stop is issued from a Telegram forum topic or a Slack reply thread, this keeps only the chat/channel ID and drops the topic/thread ID. deliverReviewToChat() later creates a root-level thread from that ID, detaching the report from the conversation where /stop was requested; preserve the source thread/topic in the routing and use it when posting.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant