Skip to content

fix(pc-mate): deliver Feishu replies visibly and accept flattened mentions - #2981

Open
AlexStocks wants to merge 9 commits into
masterfrom
feat/pc-mate-feishu-reply-fixes
Open

AlexStocks wants to merge 9 commits into
masterfrom
feat/pc-mate-feishu-reply-fixes

Conversation

@AlexStocks

@AlexStocks AlexStocks commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Which issue or RFC does this PR close?

Closes #.

Related discussion: #2970

Worktree architecture: #2922

Rationale for this change

The Feishu group channel produced no visible answer even though the event was
delivered and the model returned a verdict. Three separate defects were
involved, each hiding the response at a different stage.

1. A flattened event was dropped before triage. The configured event
transport (lark-cli event consume) emits a flattened callback that carries no
structured mentions array. parse_event required a mention whose id matched
bot_id/app_id, so a group message that explicitly addressed the bot by
name was rejected and the run ended without a trace. feishu.botName now
carries the display name, and the rendered text is used to recognise an
explicit @<botName> address when the structured array is absent. An
unaddressed group message is still rejected, so the RFC 2919 L92 exclusion of
full group ingestion is unchanged.

2. The reply body was published as a literal dash. The body was passed to
shortcut flags such as --markdown -, which are not stdin markers: the CLI
published the - as the answer. The body is now built as JSON and delivered
on stdin to lark-cli api POST ... --data -. This also keeps untrusted model
output out of argv, which the previous shortcut form already intended.

3. The reply was hidden in a side thread. The reply carried
reply_in_thread=true, so it appeared only under the thread view and not in
the chat timeline. From the group's point of view the bot had not answered.
Group replies now land in the chat timeline.

4. The pipeline could not finish a programming task. Triage and the
implementation proposal both ran read-only in the shared checkout, so an
accepted report ended as a plan in the chat: the agent could read the
repository but could not change anything, and it had no directory of its own
to change. Discussion #2922 asks for the supervisor/agent split to stay, with
triage and code execution separated and every implementation task running in
its own Git worktree. The controller now creates that worktree
(stateDir/work/<case>) with a branch off the configured base, runs the agent
there with write access, commits the result, and saves the patch. The shared
checkout stays read-only for the whole pipeline. The branch is pushed to
git.remote before the worktree is removed, so the work is on the remote
before the only copy of it goes away; opening a pull request and merging stay
with a person.

5. The loop had no supervisor. A message was triaged, answered and
implemented by one linear pipeline. That pipeline had no notion of an
authorization that travels with the work, no way to hold a question open until
the requester answers it, and no way to read a burst of messages about one
problem as one problem. Discussion #2922 asks for the supervisor/agent split,
and the supervisor-agent architecture of smallnest/superagent is the shape
the loop now has: the supervisor decides what should happen, the agent does
it, and the authorization that travels between them is a mandate.

What changes are included in this PR?

  • pc-mate/src/config.rs: new feishu.botName field, defaulting to empty.
  • pc-mate/src/sources/feishu.rs:
    • parse_event accepts a group message addressed by the configured display
      name when the event carries no structured mention, and strips that prefix
      from the command text.
    • reply_args / chat_args use the generic api POST form with
      --data -; reply_body / chat_body build the JSON payload.
    • reply_in_thread is no longer set, so a group reply is visible in the
      chat itself.
  • pc-mate/settings.example.yaml: documents botName.
  • pc-mate/README.md: documents feishu.botName and when it is needed.
  • pc-mate/docs/rfc-conformance.md: two new rows — a flattened group event
    still requires an explicit address, and a reply body reaches Feishu verbatim
    and lands in the chat timeline.
  • New unit test flattened_group_event_with_display_name_only_is_accepted;
    reply_payloads_are_read_from_stdin_not_argv updated for the new argument
    shape.

The worktree stage adds:

  • pc-mate/src/worktree.rs (new): the per-case worktree lifecycle. It creates
    the worktree and branch, commits the agent's work with a fixed identity,
    saves stateDir/cases/<case>/worktree.patch, records branch/base/head in
    stateDir/cases/<case>/worktree.json, and removes a worktree only after
    saving what only it holds. A recorded path outside this installation's
    stateDir/work is refused, so the shared checkout is never a cleanup
    target.
  • pc-mate/src/workflow.rs: the implementation stage. The accepted report is
    analysed read-only as before, then the agent runs with write access in the
    case's worktree. The controller commits the result; the reply names the
    branch, the commit and the changed files, and states that nothing was
    pushed.
  • pc-mate/src/config.rs: the executor section (enabled, branchPrefix).
    The branch prefix is validated against the rules git applies to a branch
    name, and an unattended implementation refuses OpenCode, which cannot
    confine its writes.
  • pc-mate/src/app.rs: run_agent_in_worktree. pc-mate run --write now
    writes in a one-off worktree too, so no agent writes the shared checkout.
  • pc-mate/src/cli.rs: pc-mate worktree list and
    pc-mate worktree remove <case-id>, and a doctor check that the checkout
    can host case worktrees.
  • pc-mate/README.md and pc-mate/docs/rfc-conformance.md: the worktree
    lifecycle, the enforced invariants and the remaining gaps.
  • New tests: two_cases_get_distinct_worktrees_and_the_shared_checkout_stays_clean,
    the_controller_commits_the_agent_work_and_saves_the_patch,
    cleanup_saves_uncommitted_work_before_removing_the_worktree,
    cleanup_refuses_a_recorded_path_outside_the_installation_work_directory,
    an_accepted_task_is_implemented_inside_its_own_worktree,
    a_disabled_executor_stops_after_the_read_only_proposal,
    an_implementation_reply_names_the_branch_and_claims_no_publication,
    a_branch_prefix_that_git_would_refuse_is_rejected_at_load_time,
    an_unattended_implementation_refuses_a_runner_that_cannot_confine_its_writes.

The supervisor stage adds:

  • pc-mate/src/core/ (new): the domain core, ported from
    smallnest/superagent's src/core/. model.rs (ticket, thread, decision,
    mandate, assignment, worker report), ctx.rs, engine.rs, intake.rs,
    evals.rs, tickets.rs, assignments.rs, replies.rs, reasons.rs,
    errors.rs, ids.rs, and the ports the domain talks to.
  • pc-mate/src/supervisor/ (new): the ports' pc-mate implementations.
    policy.rs is the mandate policy — a listed person who addressed the agent
    makes an explicit request, everything else worth assessing is inferred,
    and an inferred authorization may only implement under triage.mode: auto.
    assessor.rs holds the batches that wait for the quiet period, executor.rs
    holds the assignments that wait to run, outbox.rs holds the replies that
    wait to go out, repository.rs is the durable state, and scope.rs says
    which sources are read.
  • pc-mate/src/outcome.rs (new): the report of the write stage. The read stage
    answers in prose; the write stage writes .pc-mate/outcome.json — the
    summary, the state, the files it changed, the commands it ran, the question
    it still has, the lesson it learned and followupAfterSeconds. The file is
    named outcome.json and not report.json, because the read stage's answer
    is the report and the two are not interchangeable.
  • pc-mate/src/app.rs: the pipeline is now supervisor.receive →
    supervisor.tick → deliver. The worker runs in a background task, so a
    long implementation does not stop the bot from taking messages in. The
    GitHub write path is unchanged: a reply still becomes a pending action that
    waits for the approval.
  • pc-mate/src/supervisor/mod.rs: the assessment keeps the memory the earlier
    pipeline had. Every batch is assessed against the public Scope through
    POST /v1/context/prepare again, and an empty or failed read is passed to
    the model as evidence absence instead of being guessed around. The read-only
    answer prompt carries the keynotes summary again, as the earlier proposal
    prompt did.
  • pc-mate/src/config.rs: the supervisor section (enabled,
    batchWindowSeconds, default 45) and executor.push (default true).
  • pc-mate/src/worktree.rs: cleanup ends a worktree in a fixed order —
    save the patch, push the branch, remove the worktree, delete the local
    branch — and a failure anywhere above leaves the worktree and the branch in
    place. A worktree whose run stopped to ask a question is kept, and a
    re-check continues the branch the installation pushed before.
  • pc-mate/README.md and pc-mate/docs/rfc-conformance.md: the supervisor
    architecture, the mandate rules, the report protocol, the worktree
    lifecycle and the remaining gaps.
  • New tests: an_accepted_request_creates_a_ticket_that_owns_its_thread,
    a_listed_person_who_names_the_agent_makes_an_explicit_request,
    a_remark_from_a_listed_person_is_only_an_inferred_candidate,
    only_the_auto_mode_accepts_an_inferred_candidate,
    consecutive_messages_are_assessed_together,
    a_disabled_executor_stops_after_the_read_only_stage,
    a_ticket_that_asks_to_look_again_is_checked_again,
    a_question_waits_for_the_answer_and_the_work_continues,
    an_outcome_names_what_was_done_and_how_it_was_checked,
    a_file_that_is_not_an_outcome_is_refused,
    a_run_that_wrote_nothing_falls_back_to_its_own_words,
    a_failed_assessment_answers_nobody,
    a_category_outside_the_configured_set_has_no_side_effects,
    a_message_that_was_taken_in_is_not_answered_twice,
    a_reply_that_could_not_be_delivered_is_tried_again,
    prepared_evidence_reaches_the_prompt_verbatim,
    an_empty_prepared_context_is_declared_insufficient.

No persisted format, public API, or approval boundary changes. The write
boundary, the read-only agent contract and the PowerContext access rules are
untouched.

Are there any user-facing changes?

Yes. A group reply now appears in the chat timeline instead of in a side
thread, and a message that addresses the bot by name is answered even when the
event source drops the structured mention array.

feishu.botName is a new optional setting. It defaults to empty, so an
existing installation behaves exactly as before until it is set.

The worktree stage adds two optional settings, executor.enabled (default
true) and executor.branchPrefix (default pc-mate/), plus
git.baseBranch for the commit a worktree branches from (null keeps the
checkout's current HEAD). The implementation stage is reached only in
triage.mode: auto; observe and reply behave as before, and
executor.enabled: false keeps the old proposal-only behaviour.

The implementation stage changes code in a worktree of its own and pushes that
branch to git.remote: no pull request, no merge. A ticket that was
implemented carries the new implemented ticket state.

The supervisor stage adds three optional settings: supervisor.enabled
(default true), supervisor.batchWindowSeconds (default 45, the quiet
period before one thread's queued messages are assessed together) and
executor.push (default true, whether the branch is pushed before the
worktree is removed). proposal.enabled and triage.autoLabel are kept so an
existing settings file still loads; the supervisor replaced the pipeline that
read them, so they no longer have an effect, and both are documented as such.

The answer to a question now waits for the requester: a run that asks one
keeps its worktree, the question goes to the conversation, the answer is put
in the prompt of the next run, and the work continues in the same directory.

How was this change tested?

Commands run:

cargo fmt --all --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked

fmt and clippy pass. On this Windows host cargo test --locked reports
157 passed and 1 failed:
sources::github::tests::polling_a_changed_issue_keeps_unseen_human_comments_across_pages.
That failure is not caused by this change — it reproduces identically on
the unmodified master tree at 5d55eeb7 with the same
tcp connect error (os error 10060) against its loopback mock server. It is a
pre-existing local-environment failure in github.rs, which this PR does not
touch.

On the earlier head efd37dc8, the same suite on Linux, with the pinned
toolchain and the same loopback behaviour CI has, passes completely:

wsl -e bash -lc 'cd .../pc-mate && CARGO_TARGET_DIR=/tmp/pc-mate-pr2981-worktree-target cargo test --locked'
# test result: ok. 161 passed; 0 failed  (unit tests)
# test result: ok. 6 passed; 0 failed    (cli smoke tests)

cargo fmt --all --check and cargo clippy --locked --all-targets -- -D warnings
also pass on Linux with Rust 1.95.0, the version CI pins.

Manual validation on this host, against a real Feishu group:

  • Before the fix, a group @ClawBot … message was received by the event bus
    (RECEIVED=1 / DROPPED=0) but produced no triage/ record and no reply.
  • After the fix, the same message produced a triage record with
    replied: true and a reply_id, and the reply body was delivered into the
    chat with its full text.

Not verified in this environment: a real GitHub App installation token, real
GitHub issue/comment/label writes, real PowerContext Scope/Principal
enforcement, and the im.message.recalled_v1 event handling that the event
transport also emits.

The worktree stage has not run against a real model yet: the lifecycle is
covered by tests that drive the controller, but no real agent diff has been
produced on this host. The controller does not re-run the tests the agent
reports, so a test result in an implementation reply is the agent's claim and
is labelled as such.

The supervisor stage was verified on this host at head 8ce892bc2:

cargo fmt --manifest-path pc-mate/Cargo.toml --all --check
cargo clippy --locked --manifest-path pc-mate/Cargo.toml --all-targets -- -D warnings
cargo test --locked --manifest-path pc-mate/Cargo.toml

fmt --check and clippy -D warnings pass. cargo test --locked reports
184 passed, 1 failed:
sources::github::tests::polling_a_changed_issue_keeps_unseen_human_comments_across_pages.
That failure is not caused by this change — it was reproduced on the
unmodified merge base of this branch (5d55eeb7f, i.e. master at the time
of the branch point) with the same tcp connect error (os error 10060) against
its loopback mock server. It is a pre-existing local-environment failure in
github.rs, which this PR does not touch.

The same suite on Linux, with the pinned toolchain and the loopback behaviour
CI has, passes completely:

wsl -e bash -lc 'cd .../pc-mate && CARGO_TARGET_DIR=/tmp/pc-mate-pr2981-target cargo test --locked'
# test result: ok. 188 passed; 0 failed  (unit tests)
# test result: ok. 6 passed; 0 failed    (cli smoke tests)

GitHub CI at head 8ce892bc2: the PC-Mate workflow was dispatched by hand
with gh workflow run pc-mate.yml --ref feat/pc-mate-feishu-reply-fixes. Run
47072966860
(workflow_dispatch, head 8ce892bc2) succeeds: changes / detect and the
check job (format check, lint, test, build) both pass.

The PR's Main orchestrator cannot go green at this head for a reason outside
this change: CI preflight fails in uv lock --project e2e/bub --locked
("The lockfile at uv.lock needs to be updated"), and master itself fails
the same step at 1a34cdc53 (run
47064599887,
job CI preflight). The pc-mate jobs are skipped because that preflight fails,
not because pc-mate failed. license/cla remains pending, so the PR stays
BLOCKED.

The supervisor's own behaviour is covered by tests that drive the controller
end to end: a task is implemented inside its own worktree and the branch
reaches the remote; the shared checkout stays clean; consecutive messages are
assessed together; a ticket that asks to look at itself again is checked
again; a question waits for the requester's answer and the work then continues
in the same worktree; a message is not answered twice; a reply that could not
be delivered is tried again.

Not verified in this environment: a push against a remote that needs
credentials (the tests push to a local bare repository), a real model run
that produces a real diff, and the agent asking a question against a live
Feishu group.

AI usage statement

This change was produced with AI assistance (Claude, via WorkBuddy). The
analysis of the three failure stages, the patch, the unit tests and the
manual Feishu validation were all carried out with AI support; the commit
message and this description were written from that work.

The worktree stage was produced with AI assistance as well (OpenAI Codex, with
the MiniMax-M3.1 model). The design followed Discussion #2922 and the
worktree lifecycle of smallnest/superagent; the Rust implementation, the
tests, the documentation and this description were written with that
assistance.

The supervisor stage was produced with AI assistance as well (OpenAI Codex).
The domain core is a port of smallnest/superagent's src/core/; the
mandate policy, the worktree lifecycle, the report protocol, the quiet
period and the self-review were implemented against Discussion #2922 and the
maintainer's decisions on this PR. The Rust implementation, the tests, the
documentation and this description were written with that assistance.

…tions

Three defects kept the Feishu group channel silent even though the event
arrived and the model produced a verdict.

1. A flattened event has no `mentions` array, so a group message that
   explicitly addressed the bot was dropped by `parse_event` and the run
   ended silently. `feishu.botName` now lets the rendered text carry the
   address when the structured array is absent. An unaddressed group
   message is still rejected, so RFC 2919 L92 full group ingestion stays
   excluded.

2. The reply body was passed through shortcut flags such as `--markdown -`,
   which are not stdin markers: the literal dash was published as the
   answer. The body is now built as JSON and delivered on stdin to
   `lark-cli api POST ... --data -`, so untrusted model output never
   becomes an argv value either.

3. The reply carried `reply_in_thread=true`, which hides it in a side
   thread. Users saw nothing in the chat and reported that the bot had
   not answered. Group replies now land in the chat timeline.
The controller now separates triage from code execution. An accepted
bug/feature gets its own Git worktree under stateDir/work/<case> and a
branch off the configured base, and the agent runs there with write access.
The shared checkout stays read-only for the whole pipeline, the controller
commits the result and saves a binary patch, and the branch stays local
until a person publishes it.

The manual run command follows the same rule: --write now works in a
one-off worktree instead of the shared checkout. Cleanup is explicit and
refuses any path outside this installation's work directory.
@AlexStocks
AlexStocks requested a review from hidb4ai as a code owner December 2, 2026 15:04

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two reproduced correctness issues in the new group-address fallback and worktree recovery path are detailed inline.

&& !config.bot_name.trim().is_empty()
&& raw
.to_ascii_lowercase()
.contains(&format!("@{}", config.bot_name.trim().to_ascii_lowercase()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Restrict the display-name fallback to an exact bot mention without authoritative mention metadata. With botName=ClawBot, parse_event accepts an allowed-group message addressed to @ClawBotHelper. It also accepts @clawbot when the supplied structured mention explicitly identifies ou_other rather than the configured bot. Both cases return a trigger in a public parse_event reproduction, admitting messages that were not addressed to this bot into triage. Only use the fallback when structured identity is unavailable, and require an exact mention boundary.

Comment thread pc-mate/src/worktree.rs
) -> Result<RemoveOutcome> {
let record =
load(state_dir, case_id)?.with_context(|| format!("no worktree record for {case_id}"))?;
let directory = std::fs::canonicalize(&record.directory)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Allow cleanup of a record whose worktree directory is already missing. After prepare creates a worktree, deleting that directory makes the next prepare instruct the operator to run pc-mate worktree remove CASE. That command fails here during canonicalize and leaves the record intact, so the documented recovery cannot unblock the case. Reproduced with a real temporary Git repository through prepare/remove/load. Handle the missing-directory case while retaining path containment checks and pruning the stale Git registration, so the case can be prepared again.

codex and others added 2 commits December 3, 2026 00:39
The supervisor-agent architecture needs a domain that can say what a message
was, what it authorised, and who may still decide it. That vocabulary comes
from smallnest/superagent, so the core is ported rather than reinvented:

- Trigger, Thread, Evaluation, Decision, Mandate, Ticket, Assignment and the
  invariants between them (core/model.rs).
- Intake, evaluations, tickets, assignments and replies as one engine, with
  every mutation behind a port so the domain runs in memory in a test and on
  disk in the service (core/ports.rs, core/engine.rs).
- The two strengths of authorisation, explicit and inferred, and the rule
  that an inferred mandate may only write when its assessment says the work
  is an implementation.

pc-mate's own four-way intent analysis travels with the ticket it accepts,
so the first step of the pipeline stays what it was.
…cket

Port the superagent domain core (model, engine, intake, evaluations, tickets, assignments, replies, reasons, ports) and drive it from a supervisor that decides what should happen while the agent does it.

The first step of the assessment stays pc-mate's own four-way intent analysis. Everything after it follows superagent: consecutive messages of one thread are assessed together after a quiet period, the assessment produces a mandate, and the mandate decides what the worker may do.

The agent runs in a Git worktree of its own. A run that asks a question keeps its worktree and waits for the answer; the answer reaches the next run's prompt. The write stage reports in .pc-mate/outcome.json, the read stage answers in prose. The controller commits the result and ends the worktree in a fixed order: save the patch, push the branch, remove the worktree, delete the local branch.

Settings: supervisor.enabled, supervisor.batchWindowSeconds (45), executor.push.
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ AlexStocks
❌ codex


codex seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@hireview001 hireview001 added the module:pc-mate Primary module: pc-mate community bot and experience reuse label Dec 2, 2026
@hireview001

Copy link
Copy Markdown
Collaborator

The affected modules are pc-mate. @hidb4ai, please coordinate follow-up. pc-mate: @hidb4ai @AlexStocks. Please coordinate the review of the affected changes.

@hireview001
hireview001 requested a review from hidb4ai December 2, 2026 18:44
The README now carries a Mermaid diagram of the supervisor, the worktree write stage, PowerContext evidence and memory, and the approval path. It also follows the memory move: the lesson is written before cleanup, outcome.json never reaches the branch, and followupAfterSeconds starts from the pushed branch. The verification note records the local Linux and Windows results.

This branch has not been deployed

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

Labels

module:pc-mate Primary module: pc-mate community bot and experience reuse

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants