Commit Graph
293 Commits
Author SHA1 Message Date
d276991c60 MUL-6743 refactor(issues): remove the assignment handoff note (#7626)
* refactor(issues): remove the assignment handoff note (MUL-6743)

Usage data puts the handoff note at 0.2% of assignments, so the box
occupied the confirm dialog's centre for the other 99.8% and bought
them nothing. Removing it takes the whole feature with it: the note
input and its runtime version gate, the `handoff_note` write field on
PATCH/batch issue updates, the task column write, and the daemon's
opening-prompt + issue_context.md handoff sections.

The confirm dialog itself stays — it still names who is about to run
and still offers "Don't start yet" (suppress_run).

The `*WithHandoff` enqueue methods only ever varied by that note, so
they become `EnqueueTaskForIssueByActor` / `EnqueueTaskForSquadLeaderByActor`
— the actor-carrying variants autopilot already called with an empty
note. `preview-trigger` drops `handoff_supported`, which nothing read
after the gate moved client-side.

`agent_task_queue.handoff_note` is deliberately left in place: it holds
historical rows and this is the expand half of an expand-contract pair.
Nothing reads or writes it now, so a follow-up migration can drop it
once no deployed binary selects it.

Co-authored-by: multica-agent <[email protected]>

* docs(issues): reshoot the assignment confirm dialog (MUL-6743)

The asset still showed the handoff note box the surrounding prose no
longer describes. Recaptured from the app at the same 600x450 frame;
the confirm button now carries the send-chord keycaps it has shipped
with since MUL-5694.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Lambda <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-09-03 16:13:33 +08:00
879d0de916 refactor(agent tasks): drop the Active sibling runs prompt block (MUL-6984) (#7937)
Every issue turn carried a claim-time snapshot of the same agent's other
in-flight tasks, scoped only by (agent, workspace) and capped at five. The
scope had no relatedness filter, so the list answered "what else is this
agent running right now", not "what else touches the code you are about to
change".

Measured over one day of runs on this workspace: the block was injected 78
times across 30 runs, listing 96 distinct (current issue, sibling) pairs, and
not one pair shared a PR, a branch, or an issue family. `run-messages` was
invoked zero times off it. Meanwhile the day's one genuine overlap — a PR
review pushing to server/internal/metrics/pricing.go and a concurrent change
to the model catalog next to it — was never paired, because overlapping in
time is not the same as overlapping in code.

The duplicate-run defect this shipped with (#6947) is fixed by
shouldSuppressActiveSelfAssignment, which stops a second run on the same
(issue, agent) at the server. Once that holds, the block can only ever list a
DIFFERENT issue, so it was structurally unable to help with what it was added
for. #7922 then gave the coordination question a correct answer —
`issue runs --active` / `--siblings`, cross-agent, family-scoped, and read at
the moment it is asked — which is the same information as a pull instead of a
per-turn push.

Removed end to end rather than hidden behind a flag: the prompt block, the
claim payload field on both sides of the wire, and ListActiveSiblingIssueTasks.
The field was `omitempty` and the daemon already rendered nothing for an empty
list, so old and new server/daemon pairs stay compatible in both directions;
nothing outside server/ ever read active_sibling_runs.

Kept: the self-assignment suppression and its tests, `--no-start`,
`issue run-messages`, and `issue runs --active/--siblings`.

Co-authored-by: J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-09-03 13:28:05 +08:00
603519d158 MUL-6977: test: remove implementation-only coverage (#7932)
* test: remove implementation-only coverage

Co-authored-by: multica-agent <[email protected]>

* test: remove remaining implementation-only coverage

Co-authored-by: multica-agent <[email protected]>

* test: restore compatibility and fragment navigation coverage

Co-authored-by: multica-agent <[email protected]>

* test: preserve behavioral cleanup contracts

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-09-03 13:23:25 +08:00
4dfa08917b fix(daemon): isolate managed OpenClaw MCP servers without reading user config (MUL-6684, MUL-6857) (#7279)
* fix(daemon): build the managed-MCP config from `config get mcp --json`

Preparing a task for an OpenClaw agent with a managed `mcp_config` reads the
user's resolved configuration so the wrapper can replace `mcp.servers` while
keeping the user's other `mcp.*` settings. That read asks for the resolved root,
`openclaw config get --json` with no key path, and current releases do not
answer it: measured against 2026.5.27 the CLI writes zero bytes to stdout and
never exits, and the same shape is reported against 2026.7.1-2. Every
managed-MCP task on such a host therefore fails preparation.

`config get mcp --json` is answered, and it is also the only part of the
configuration this code needs. Switching to it means the snapshot can no longer
be a flat copy of the user's resolved config, so it becomes an include chain:

  1. `$include` the user's live config,
  2. merge `{"mcp": null}`, which OpenClaw's include merge treats as a
     wholesale replacement of the user's MCP object,
  3. restore the resolved non-server MCP settings.

The wrapper then contributes the managed server set, which is the only server
definition the chain can yield. `sessionIdleTtlMs` and its siblings still
resolve; user-only servers do not.

Security posture moves in both directions, so both are worth stating:

- Better: the task directory no longer receives a copy of the user's resolved
  configuration. That copy was a flat snapshot of everything the loader
  produced, which the code it replaces acknowledged could carry API keys and
  model-provider tokens, mitigated only by 0o600. The chain writes include paths
  and MCP tuning, and nothing else.
- Worse: because the chain reaches out to the user's real config, the daemon has
  to grant its directory through OPENCLAW_INCLUDE_ROOTS. The flat copy was
  self-contained and needed no grant. The trade is a read grant on one directory
  instead of duplicating that directory's secrets into per-task state, which
  also means the include never goes stale relative to the user's config.

The MCP read uses the same deadline as every other call in the preparation
rather than a shorter budget of its own. It is one of the
openclawMaxCLICallsPerPreparation calls the budget arithmetic already accounts
for, it is the same class of invocation as the discovery calls — measured at
4.3s on the slow host in #7142 — and it has to honour
MULTICA_OPENCLAW_CLI_TIMEOUT for the same reason those do. A shorter private
budget would fail closed on exactly the machines that raise the override because
they need it.

`openclawResolvedFullConfig` and `stripUserMcpServers` lose their only caller.
The discovery cache's note about deliberately not caching the resolved config is
updated: the reason is no longer that the payload holds secrets, but that the
MCP subtree is per-agent state that has to reflect the user's configuration as
it is now.

Tests: the three strict-replace tests move to the MCP subtree and assert the
chain rather than a copy, including that the snapshot contains none of the
user's server bytes. TestPrepareOpenclawConfigIncludeRootGrants covers the grant
for all three include targets, because getting it wrong fails at OpenClaw's
include-confinement check with nothing pointing back here. The real-CLI test
behind the agentintegration tag asks the installed binary to resolve the
generated chain, since the correctness of the reset bridge lives in OpenClaw's
merge semantics rather than in the JSON this package writes.

* fix(ci): compile the agentintegration tests, and correct the snapshot doc

Two review follow-ups on the managed-MCP include chain.

The `openclawUserSnapshotFile` comment still described the flat sanitized
copy this PR replaced — "the user's config minus the `mcp` block". The file
now holds no user config bytes at all, only an include chain, which is also
why its 0o600 is about the paths it names rather than secrets it carries.
The name stays because the wrapper's include target is not worth churning
for a rename; the comment says why.

The design's load-bearing claim — that `{"mcp": null}` makes OpenClaw's
include merge replace the user's MCP object rather than merge into it —
is verified by openclaw_mcp_real_integration_test.go, and nothing compiled
that file. `agentintegration` guards nine files across the module and no CI
job referenced the tag, so a helper renamed in an ordinary test file, or two
branches each defining one in the same package, breaks the tagged build with
every untagged job still green. That is not hypothetical here: #6275 adds
openclaw_real_integration_test.go to this package with its own
`realOpenclawBin`, and dropping it in beside this one leaves `go build ./...`
passing while the new step reports

  vet: openclaw_real_integration_test.go:18:6: realOpenclawBin redeclared

vet type-checks test files, so the gate needs no agent CLI and no runner
that can execute one. It sits next to Build, before the suite that would
otherwise be the first thing to notice.

* docs(execenv): scope the root-read claim to what was actually measured

Two comments asserted that "current releases" do not answer
`config get --json`, citing a report against 2026.7.1-2 as corroboration. The
measurement behind them is one host on 2026.5.27, and the citation does not
support the claim: the 2026.7.1-2 reports (@kaverjody in #6275, #7308) are both
about `openclaw config file` — cold-start timings and a descendant holding
stdout — not about the root read. #7308 in fact measures `config file` exiting
cleanly in 4.2s on that version.

Which command is which is the whole premise of this change: `config get mcp
--json` is answered while the root is not, so treating an observation of one as
evidence about the other undercuts the argument it was meant to support.

Scoped both comments to the measurement, and stated that the root read's
behaviour on 2026.7.1-2 is unmeasured. The decision does not need the broader
claim: the subtree is the only part of the configuration this code needs, and
the fail-open branch being removed is a silent-degradation bug on its own terms,
reachable from any cause that makes the read come back empty.

* fix(daemon): harden OpenClaw MCP isolation

* fix(execenv): correct the root-read diagnosis against measured channels

Measured 2026-08-26 on Windows 10.0.19045.6466 against the three npm channels.
Two claims in this branch were wrong, and the corrected version is a stronger
argument for the change rather than a weaker one.

**The root read does not hang; it is not a valid invocation.** `config get`
requires a path, and the pathless form is rejected outright:

    2026.6.34   (extended-stable)  exit 1 in 2.9s  Missing required argument "path".
    2026.7.1-2  (latest)           exit 1 in 3.0s  same message
    2026.8.1-beta.3 (beta)         exit 1 in 4.4s  same message, JSON envelope

So `openclawResolvedFullConfig` did not degrade on some hosts — it failed
preparation for every managed-MCP task on all three channels shipping today.
2026.5.27 writing nothing and never exiting within 60s is one version differing
from every current one, and is now recorded as that rather than as the general
case. Switching to the subtree stops being a workaround for a hang and becomes
the request this code should always have made.

**The "exits 0 with empty stdout" shape is unobserved.** It needs exit 0; all
three channels exit 1. The fail-open branch removal still stands on its own —
it is a silent-degradation path and the new chain has no equivalent — but it is
no longer offered as the mechanism behind the reported `Unknown model`, which
remains a real symptom with an unestablished cause.

Also corrected from the same measurements:

- The missing-key transports are not a migration. 2026.6.34 and 2026.7.1-2 are
  stderr-only with empty stdout; only 2026.7.2-beta.7 onward puts the envelope
  on stdout. Both paths are load-bearing for channels shipping today, which the
  detector doc now states with the version table.
- `config get agents.list --json` on 2026.6.34 and 2026.7.1-2 emits
  "Config path not found: agents.list" and names the path, so requiring the
  diagnostic to name the requested key does not regress the registry fallback on
  current stable. `agents list --json` answers on all three.
- 2026.8.1-beta.3's `mcp` schema is exactly `servers` + `apps` with
  additionalProperties:false; `sessionIdleTtlMs` is gone. Stage 3 of the chain
  can only carry keys the same CLI just returned, which is what keeps it safe
  against that constraint. Comments now use `mcp.apps` as the current example.

New regressions, all from verbatim measured output:

- the pathless usage error must not read as a missing key, in both the stderr
  and the JSON-envelope form. This is the shape that actually occurs, and
  misreading it would turn a broken invocation into a silent "user has no mcp
  block";
- beta.3's invalid-config envelope (schema violation in a sibling `issues`
  array) must not read as a missing key either.

The smoke workflow now fails when the test skips. A skipped Go test reports `ok`
at the package level, so the job would have gone green whenever the CLI was
absent or the -run pattern stopped matching — green exactly when nothing was
verified. #6897's Windows step documents the same hazard.

The real-CLI test's doc records the platform, the three resolved versions and
their PASS durations (36.9s / 40.6s / 34.2s), and the hand-run control: dropping
the reset stage leaks `user-only` back into the resolved server map on all three
channels, which is what makes those passes mean something.

* test(execenv): pin the reset-stage/wrapper-mcp pairing the loader depends on

The reset stage is only safe because the wrapper always contributes its
own mcp object under the same condition: OpenClaw merges sibling keys
over the include result, and a null that instead survives to the
resolved root fails schema validation (zod .strict().optional() rejects
null), taking the whole config load down. The pairing held by
construction but nothing named it; this assertion fails in the PR that
breaks it, instead of a week later in the scheduled smoke.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(execenv): match the deadline-budget arithmetic to the constant

openclawMaxCLIDeadlinesPerPreparation dropped from 4 to 3 when the
managed-MCP read step was removed, but the worst-case explanation on
openclawCLIMaxTimeout still said 4 x 60s = 4m. Say 3 x 60s = 3m so the
documented safety arithmetic matches the constant and its test.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: weiweiwei <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-09-03 12:33:39 +08:00
mrlonely 2e29745100 MUL-6870 fix(daemon): require proven task ownership before GC mutation (#7798)
Daemon GC treated every second-level directory under WorkspacesRoot as a task
root and deleted it once it had no .gc_meta.json and went past the orphan TTL,
without ever proving Multica had created it. Pointing workspaces_root at a
directory holding real user content therefore made GC delete that content.

Require valid Prepare-time .task_owner provenance, matching the exact
workspace/task path, before every GC mutation including artifact-only cleanup.
Revalidate after taking the env-root lock and again immediately before
os.RemoveAll. Directories that cannot prove ownership are retained.
2026-09-02 00:44:58 +08:00
61ea48fd2e MUL-6881 fix(daemon): keep one worktree branch per conversation in local worktree mode (#7815)
* fix(daemon): keep one worktree branch per conversation in local worktree mode

Every comment on a local_directory issue started a new task, and worktree
mode gave each one a branch of its own forked from the user's HEAD. Turn two
therefore stood in a tree that did not contain turn one's work, with that work
stranded on another branch and nothing saying so.

Tasks that share a conversation — the turns of one issue, one chat session —
now share a branch, agent/<agent>/<issue>, and a follow-up checks it out at its
tip instead of forking from HEAD. Env roots stay per task, so sibling tasks
still run concurrently; when one already holds the conversation's branch, the
other forks from its tip onto agent/<agent>/<issue>-<task> rather than falling
back to HEAD.

Replaying the user's uncommitted tree onto a continued branch cannot use the
turn-one path: that merge takes the user's HEAD as its base, so it conflicts
exactly when the agent edited the lines the user had left uncommitted. Each
turn now records the snapshot it saw at refs/multica/local-state/<branch> and
the next one replays only the difference — a cherry-pick whose parent is that
snapshot. A genuine conflict leaves the branch as it stands and logs which
files did not come across, rather than stranding the conversation.

Teardown follows the same rule everywhere: a branch this prepare did not
create belongs to the turns before it, so Finalize's read-only cleanup, Discard
and the prepare rollbacks only ever drop a branch they created themselves.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): prove branch ownership and hand replay conflicts to the agent

Review of the per-conversation worktree branch found four ways it could put
the wrong tree in front of the agent. All four came from the same two gaps:
the user's snapshot did not describe their whole directory, and a branch was
recognised by its name.

The snapshot is now one commit covering tracked edits AND untracked files,
built in a private index inside the task's env root. It answers the question a
continued branch actually has to ask — what has the user changed since the
state I already carry — for every file, so a once-untracked file the agent
edited is no longer reverted to the user's older copy each turn, and their
later deletion of one carries. Redirecting GIT_INDEX_FILE also removes the
.git/index.lock race the previous capture had to retry around (#7434).

A conflict between the user's newer edits and the branch's own work is now the
agent's to resolve, per the product decision on the issue: the worktree is
handed over mid-merge, the turn's prompt names the files and says which side is
which, and Finalize refuses to deliver — preserving the worktree — while
anything is still unmerged. The snapshot only advances once the branch really
carries it, so an unresolved edit is offered again next turn instead of being
recorded as synced. Before this, the conflict was reset away and the user's
change was lost from every later turn.

Continuing a branch is decided by an ownership record — workspace, agent and
conversation ids, recorded in the snapshot commit at
refs/multica/local-state/<branch> — never by the branch name. A same-named
branch the user created is left untouched and the task takes
agent/<agent>/<issue>-<fingerprint>, which its own follow-ups then continue.
The same check keeps two workspaces that mint one issue identifier apart.

Those refs are now GC'd: every prepare drops the record of a branch that no
longer exists, and the docs say where they live and how to clear them.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): tie a task branch's record to the branch, and quote untrusted paths

Ownership proved that Multica once wrote a branch of this name, which stayed
true after the user deleted it and created their own under the same name. No
prepare runs in that gap, so the orphan sweep never sees the branch missing and
the next turn continued straight into the user's unrelated work.

The record now also pins the branch tip it was written at, as the second parent
of the record commit, and a branch is only continued while that commit is still
an ancestor of its tip. Deleted-and-recreated, force-moved and rebased branches
all fail that test; committing on top of a delivered branch — the normal case —
passes it and picks the user's commit up. Finalize re-records afterwards,
because a checkpoint written at prepare time sits on the branch's base, which is
exactly where a recreated branch would sit.

Conflicted paths reaching the turn's prompt are quoted rather than wrapped in a
code span. They come from the user's repository and git allows newlines,
backticks and quotes in a filename, so a raw one could close its list item and
continue as an instruction line of its own; the same quoting is applied to the
Finalize error. The list is bounded at 50 names with the remainder counted.

Also drops a duplicated pair of bullets in the Chinese docs and corrects two
file comments that still described the stash-and-copy replay.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): make the branch record part of delivery, and bound the conflict list by bytes

The record could still authorise a branch that was not ours. Finalize wrote it
after removing the worktree and treated a failure as non-fatal, so a failed
update-ref left the ref pointing at the record Prepare had written — whose
checkpoint is the branch's base, which is exactly where a branch the user
deletes and recreates from HEAD sits. The ancestor check then passed on their
work.

Two changes close it. A checkpoint is only written when it is a commit the
branch could not sit at without this conversation's work: Finalize records the
tip it actually delivered, and Prepare records early only once the branch has
moved off the user's HEAD — which is the baseline commit, or a continued
branch's own tip. And the record is now part of delivering: Finalize writes it
BEFORE removing the worktree and fails the task if it cannot, so the worktree is
still there to preserve, exactly as for a commit that could not be made. The
checkpoint is the commit the caller delivered rather than a re-read of the
branch ref, so a branch moved in that window fails the next ancestor check
instead of being recorded as current.

A sibling racing the very first turn of a conversation on a clean tree now finds
no record yet and starts its own line of work rather than forking from a branch
it cannot prove is ours. That is the price of the rule and it is the safe side.

The conflict list in the prompt is bounded by rendered bytes rather than by
entries — a git path is as long as the filesystem allows, so 50 entries bounded
nothing — with the remainder counted and a single oversized path unable to
overrun the budget either.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): give every task branch a commit of its own, and verify what a run delivers

The checkpoint rule — record only a commit the branch could not sit at without
this conversation's work — held in Prepare and not in Finalize. Finalize took
whatever the worktree's HEAD was, so a run that reset its worktree back to the
user's own HEAD had that plain user commit recorded as the branch's checkpoint,
and a branch the user later recreated there passed the ownership check.

Two changes make the rule total. Every branch this mode creates now gets a
baseline commit of its own, empty when the user's tree was clean: without it the
branch sits exactly where the user's HEAD does and nothing tells it apart from a
branch they create at the same place. It also makes `git diff <baseline>..
<branch>` the agent's work on every branch rather than only on the ones that
started dirty, which is what the surrounding comments already claimed.

And Finalize verifies the delivery point before recording it: the tip has to BE
the task's branch — not a detached checkout, not a branch someone moved
underneath the run — and it has to still contain the anchor, which is that
baseline or the checkpoint the previous turn recorded and this one verified. A
delivery that fails either test is not recorded at all: the task fails, the
worktree is preserved, and the error names what is missing.

A sibling racing the first turn of a conversation forks from it again, since
every branch now carries a recordable checkpoint from the moment it is prepared.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): keep the anchor on the commit that carries this turn's user edits

A follow-up turn commits the user's newest edits as its own baseline, but the
anchor stayed on the checkpoint the previous turn had recorded. A run that then
reset its worktree back to the previous tip still passed verification — the old
checkpoint is an ancestor of it — so the turn was recorded as having delivered
edits the branch no longer had. The turn after that computed its replay from a
state the branch never took, and the user's edits were simply absent from the
worktree with nothing to indicate it.

The anchor now follows every baseline this task commits, so it always names the
newest commit carrying the state about to be recorded. Resetting past it fails
the turn and preserves the worktree, as for the first-turn case.

The conflict path had the same hole from the other end: there the branch does
not carry the snapshot until the agent resolves and something is committed. When
a turn that started mid-merge ends with the branch exactly where it began, the
record keeps the state the branch is known to carry instead of advancing, and
the next turn offers those edits again. A resolution in favour of the branch's
own side leaves the same empty trace as discarding the merge, so this trades a
merge that may have to be concluded twice against recording edits as delivered
that may have been dropped.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): measure a delivery against the commit its own turn started from

A turn that starts mid-merge only carries the user's edits once the agent
resolves and something is committed, and the guard for that compared the
delivered tip against the checkpoint an earlier turn had recorded. Those are not
the same commit: the user committing on a delivered branch is supported and
tested, so the branch tip a later turn starts from can already be past that
checkpoint. A resolution that committed nothing then left the tip equal to the
turn's own starting point but not to the older checkpoint, the guard did not
fire, and the edits were recorded as delivered — missing from the turn after
with nothing to indicate it.

Both questions now measure against LocalWorktree.BaseCommit, the commit this
turn actually started from. It is at least as new as the earlier checkpoint in
every case, so the separate anchor field is gone: a delivered tip that contains
this turn's starting point contains everything an earlier turn recorded, and a
tip that does not is a run that reset away work already delivered.

Co-authored-by: multica-agent <[email protected]>

* test(daemon): cover the claim-to-branch wiring with a two-turn Prepare test

Every multi-turn test so far drove PrepareLocalWorktree with hand-filled
params, which skips the step that turns a claim into them: which field becomes
the branch name, and which become the identity the branch is recorded under.
This one runs two turns of one issue through Prepare itself, and a third for
another workspace carrying the same issue identifier. Both halves of that
mapping are load-bearing — blanking the conversation key or fixing the
workspace id makes it fail.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): carry the worktree's own state across the preparation helper

Prepare runs in a short-lived helper process and the Environment it built comes
back to the daemon as JSON. LocalWorktree keeps everything Finalize reasons
about in unexported fields, and ordinary struct marshalling drops those without
a word — so the daemon finalized a worktree whose owner, snapshot, tracksState
and createdBranch were all zero.

Nothing failed; the guarantees were simply absent in production. No delivery
verification ran, Finalize recorded nothing (leaving the checkpoint at the
baseline Prepare had written inside the helper), a conflicted turn could not
hold its snapshot back, and a read-only turn kept its branch. Every in-process
test passed throughout, because they call PrepareLocalWorktree directly.

Custom Marshal/Unmarshal now carry that state. aborted stays out of the wire
deliberately: the daemon sets it after Prepare returns, so it belongs to the
parent. The regression tests run two turns through PrepareIsolated — the real
boundary — and assert the state arrives, that Finalize's record names the tip it
delivered rather than the baseline, and that a read-only turn still drops its
branch.

Found by running the whole stack: a real daemon, a real local_directory in
worktree mode, and two real turns.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-09-01 13:50:52 +08:00
f93855470f MUL-6874 fix(desktop): recover unexpectedly stopped daemon (#7808)
* MUL-6874 fix(desktop): recover unexpectedly stopped daemon

Co-authored-by: multica-agent <[email protected]>

* MUL-6874 fix(desktop): bound daemon recovery retries

Co-authored-by: multica-agent <[email protected]>

* MUL-6874 fix(desktop): queue one-shot daemon operations

Co-authored-by: multica-agent <[email protected]>

* MUL-6874 fix(desktop): reject nested daemon operations

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-31 15:27:30 +08:00
mrlonelyandL 6231962e98 MUL-6840 fix(pi): preserve sessions across workdir changes (#7760)
* fix(pi): resume session across workdir changes

* fix(pi): serialize session transcript writers

* fix(pi): keep busy sessions resumable

---------

Co-authored-by: L <[email protected]>
2026-08-31 13:49:38 +08:00
mikyan fe59262188 feat(agent): add Huawei Cloud CodeArts support (#6985)
* feat(agent): add Huawei Cloud CodeArts support

* fix(migrations): resolve CodeArts prefix collision

* fix(agent): address CodeArts review feedback

* fix(agent): tighten CodeArts integration scope

* fix(agent): resolve CodeArts follow-up review blockers

* fix(agent): redact CodeArts launch arguments

* docs: sync supported runtime counts

* fix(agent): own CodeArts model probe process tree
2026-08-31 12:30:59 +08:00
feig a92e8f6f7e MUL-6689: feat(agents): support MCP config for the Oh-My-Pi runtime (#7565)
Adds MCP configuration support to the Oh-My-Pi (omp) runtime. The MCP tab is
now visible for omp agents, and the managed config is materialised as
`{workDir}/.omp/mcp.json` — omp's highest-precedence project-level path —
before the runtime starts.

Materialisation lives in `execenv` and is recorded in `sidecarManifest`, so it
inherits refuse-to-clobber on a pre-existing file plus daemon-side teardown and
reuse cleanup. `Reuse` declines (returns nil, forcing a fresh Prepare) when the
config cannot be written, matching the Cursor path, so a leftover file from a
crashed run cannot silently carry stale MCP servers into the next task.
`.pi` and `.omp` are added to the repo-cache git excludes so runtime sidecars —
which for MCP routinely embed third-party tokens — cannot be committed by an
agent; `.pi/skills/` was already being written unexcluded before this change.
`listRuntimeLocalMcpServers` reports omp's user-scope inventory from
`~/.omp/agent/mcp.json`, with a comment recording that this is deliberately
narrower than omp's full discovery chain.

Pi itself is excluded by design. Upstream states the position in its README
("**No MCP.** Build CLI tools with READMEs, or build an extension that adds MCP
support."), confirmed against pi 0.67.2: no MCP code in the published bundle,
no MCP flag or subcommand, and a probe server placed in a project config is
never launched. There is no `.pi/mcp.json` convention to write into, so the
negative assertion pinning `pi` out of the allowlist is kept and now carries
that reasoning.

Closes #7558 for omp only; Pi would require authoring a Pi extension for the
daemon to inject, which is separate work.
2026-08-28 15:53:09 +08:00
VvVandweiweiwei 7d128b5a45 fix(daemon): own the openclaw CLI process tree so its deadline is enforceable (MUL-5467, MUL-5630, MUL-6736) (#6275)
* fix(daemon): own the openclaw CLI process tree so its deadline is enforceable (MUL-5467)

openclawCLITimeout has carried a "Known gap (deliberately not fixed here)"
note since #6084: the 5s deadline could not actually bound an
`openclaw config ...` invocation. This closes it, and fixes a second
OpenClaw misbehaviour found alongside it.

## Bug 1 — the deadline was decorative

exec.CommandContext kills only the direct child. cmd.Output() blocks in
Wait() until the output pipes os/exec manages reach EOF, and cancelling the
context does not unblock that io.Copy. So when openclaw leaves a descendant
holding stdout — its `openclaw-config` helper, or cmd.exe → node on Windows
— the call runs for the *descendant's* lifetime.

#6084 measured this on linux/dash (a shim whose backgrounded child slept 6s
took 6.01s against a 150ms deadline), tried a cmd.WaitDelay backstop, and
reverted it on review because it bounds the call by leaving the descendant
running — trading a hang for a process leak that nothing on Unix reaps. The
note left behind names the real fix: process-tree ownership.

Three call sites had the shape:

  - execenv.execOpenclawCLI       on the task's critical path
                                  (Prepare → prepareOpenclawConfig)
  - agent.detectCLIVersion        runs for every provider inside the
                                  daemon's blocking registration preflight
  - agent.discoverOpenclawAgents  four invocations per call

## Bug 2 — the answer was already on stdout

Measured on an OpenClaw host (openclaw 2026.5.27):

  openclaw --version    258ms  exits cleanly
  openclaw config file    60s  correct path printed, then never exits
  openclaw agents list    60s  correct list printed, then never exits

Waiting for exit turns two working commands into a task-fatal error:

  agent_error.process_failure (prepare execution environment: execenv:
  prepare openclaw config: locate openclaw active config:
  openclaw config file: context deadline exceeded (process: signal: killed))

The contract of these commands is "print a value". Once the value has
arrived and nothing more is coming, whether the process tidies itself up is
not the caller's business, and it should not fail a chat task.

## The fix

Two helpers in server/pkg/agent, both built on the process-group primitives
codex/claude/opencode already use — no new platform-specific functions:

  - RunCollect: hands os/exec an *os.File instead of a buffer, so os/exec
    starts no copy goroutine and Wait returns the instant the direct child
    exits. Then signals the child's process group, which reaps the helper
    and releases the last write end, so our own readers see EOF. Unlike
    WaitDelay this reports the CLI's real exit status, which matters because
    a failed `--version` probe skips runtime registration entirely, and
    because openclawShimDiagnostic type-switches on *exec.ExitError.
  - RunCollectQuiet: returns when the process exits, or when stdout has
    produced output that then stayed idle for 400ms — whichever comes first.
    Reports quiet=true on the idle path so callers can log the CLI's failure
    to exit without failing on it.

The idle shortcut deliberately cannot mask a silent CLI: with no output
there is nothing to salvage, so the deadline still governs and the call
still fails. A non-zero exit still fails too, with stderr intact.

execOpenclawCLI keeps its shim diagnostics and its context-attribution
order byte-for-byte; only the exec mechanism changes.
discoverOpenclawAgents keeps its existing 30s function-level budget rather
than gaining a per-attempt one.

Windows: there is no process group to signal, so calls are bounded (by the
drain grace) but a descendant can still outlive one. Owning descendants
there needs a Job Object and is not attempted here.

## Verification

  - Both packages green with -race; 6 consecutive runs, no flakes.
  - All 51 existing Openclaw* tests in execenv pass, including
    TestExecOpenclawCLITimeoutIsNotMisdiagnosedAsMissingInterpreter and
    TestExecOpenclawCLICancellationIsWrapped — their shims produce no
    stdout, so the salvage path is not reachable and the
    errors.Is(err, context.DeadlineExceeded) contract is preserved.
  - 13 new tests. Both mechanisms are mutation-verified:
      * RunCollect reverted to buffers with no group reap → the guard test
        hangs and the dump is the production stack: cmd.Wait →
        awaitGoroutines blocked, writerDescriptor parked in io.Copy.
      * RunCollectQuiet's idle path disabled → both the unit test and the
        execenv end-to-end test fail after a full 60s.

* fix(daemon): address review on the openclaw CLI collector (MUL-5467)

Three blocking items from review of #6275. All three were reproduced before
being fixed, and the first one was a genuine correctness hole rather than a
style objection.

## 1. The deadline branch salvaged partial answers

RunCollectQuiet returned success from the ctx.Done() branch whenever stdout was
non-empty, without requiring the idle grace or any check that the answer was
finished. A CLI still streaming when the deadline arrived therefore had its
truncated output reported as a completed response. Reproduced with a stub
emitting a JSON document forever against a 250ms deadline: 9 runs in 10 came
back as success carrying an unparseable fragment.

The early return now needs two independent conditions, neither sufficient
alone:

  - an OutputComplete rule supplied by the caller accepts the buffer, and
  - the buffer has since been idle for idleGrace.

Reaching the deadline is never success. The captured bytes are still returned
alongside the error so a caller with its own rule can inspect them, but the
runner no longer decides on the caller's behalf. A nil rule disables the early
return entirely, which is the conservative default for a command whose output
shape has no completeness rule.

The rule cannot be inferred inside the runner, which is the point: only the
caller knows whether `{"agents":[{"id":"a"},` is truncated or legitimate.

  - `--json` subcommands -> agent.JSONOutputComplete (whole buffer parses).
  - `openclaw config file` -> openclawConfigPathComplete (last non-empty line
    looks like a path). Deliberately stricter than
    openclawParseActiveConfigPath, which resolves a relative line through
    filepath.Abs and would therefore accept a Doctor warning border as an
    answer. That matters because OpenClaw prints Doctor UI *before* the path
    (MUL-3136), so an early return on idle output alone hands back the banner
    as the config path — and nothing downstream catches it.
  - `agents list` text fallback -> RunCollect (wait for exit). Decorated text
    has no completeness rule and a silently short agent catalog is worse than a
    slow one; this path still gains the reaping and the bounded return.

## 2. quietWriter published bytes before their timestamp

The buffer write and the last-write timestamp were updated in separate critical
sections, so a reader could observe new bytes carrying a stale timestamp and
conclude the stream had gone quiet at the moment it was producing — truncating
an answer mid-write. Both now move in one critical section (outputBuffer).

## 3. The drain-timeout path raced the readers, and could park a goroutine

RunCollect read its buffers after the drain grace expired while io.Copy could
still be appending to them; the deferred Close on the read ends ran only after
the return values had been evaluated. Separately, RunCollectQuiet handed os/exec
io.Writers, so its cmd.Wait goroutine could sit forever on a descendant holding
the pipe — on Windows nothing released it, since there is no process group to
signal.

Both are now structural rather than patched. A single collector owns the pipes
for both helpers (the *os.File ownership RunCollect already had), and finish()
guarantees that when it returns, every goroutine startCollector spawned has been
joined and nothing can still append to the buffers: it reaps the tree, waits
bounded for Wait, and if the readers still have not seen EOF it closes the read
ends outright — which makes the in-flight Read return — and only then joins them.

## Verification

  - Both packages pass with -race under CI's flags (-p 2 -parallel 2).
  - All pre-existing Openclaw* tests still pass, including the timeout
    attribution and shim diagnostic ones.
  - New regression tests, all three named in the review: continuous output until
    the deadline (must not be success), a prompt followed by a delayed body (must
    not return the prompt), and a late non-zero exit within the grace (must be
    reported as the failure it is). Plus the completeness rules per subcommand,
    the banner-then-path case end to end through execOpenclawCLI, goroutine
    collection on both helpers, and the two outputBuffer contracts.
  - Windows contract coverage added (run_collect_windows_test.go) with a scoped
    step in the existing windows-execenv CI job, since the close-the-read-ends
    path is unreachable on Unix where the group kill releases the pipe.
  - Mutation-verified: restoring the unconditional salvage fails both the unit
    and the execenv regression; dropping the completeness rule from
    execOpenclawCLI makes the Doctor banner come back as the config path.

* test(daemon): make the openclaw config-path fixtures hermetic

The two execenv fixtures printed the literal path the host had printed,
`/root/.openclaw/openclaw.json`. openclawParseActiveConfigPath stats what it
parses and tolerates only os.ErrNotExist, so that path resolves differently by
environment: ENOENT on a developer machine, where /root does not exist, but
EACCES on a Linux CI runner, where it exists and is unreadable. The second case
is a hard error, so TestExecOpenclawCLIWaitsForThePathAfterDoctorBanner failed
in CI for a reason unrelated to the boundary it covers.

Both fixtures now print a real file inside t.TempDir(), which stats cleanly
everywhere. The second test only inspects raw stdout today, but a hard-coded
path there would be a trap for whoever next adds a parse to it.

The literal path stays in the completeness-rule table, which calls the
predicate directly and never stats, so it keeps documenting the shape the CLI
actually emits.

* fix(agent): own one-shot CLI process trees on Windows

* fix(daemon): support current OpenClaw config discovery

* Address review, and narrow this branch to the process-tree fix

Blocking items from the review:

1. The deadline branch no longer salvages. It returns an error unconditionally,
   and callers supply a per-subcommand completeness rule (openclawOutputComplete)
   that decides whether the captured bytes are a finished answer. Regression
   coverage for the three shapes named in the review: output continuing right up
   to the deadline, a banner ahead of the real answer, and a late non-zero exit.

   finish() now reports, rather than being wired to a field that was never
   assigned. Two cases do not converge and both cost the caller something it
   would otherwise never learn: a process still outstanding in Wait after the
   tree kill, and a descendant still holding the pipe when the read ends had to
   be force-closed, which can truncate trailing output. collectorError joins that
   with the command's own error, so nothing is displaced.

2. outputBuffer publishes bytes and the write timestamp inside one critical
   section, so a poller cannot see new bytes with a stale timestamp and conclude
   the stream went quiet while it was in fact producing.

3. The drain-timeout path closes the read ends and waits for both absorb loops
   before any snapshot is taken, so no io.Copy can be appending to a buffer the
   caller is about to read. Windows contract coverage runs as its own CI job.

   The goroutine guarantee is stated at its real strength instead of "no
   goroutine outlives the call, on any platform". Convergence holds whenever the
   tree kill takes. When it does not, one goroutine can stay parked in cmd.Wait
   on a process nothing can terminate; that residue is not removable here, so it
   is reported instead of asserted away. On Windows the same case extends the
   call rather than leaking, because an anonymous pipe is not pollable and
   closing the read end waits for an in-flight Read to release it.

Also from review:

- A JSON error envelope is valid JSON, so JSONOutputComplete accepts one and a
  CLI that prints `{"error": ...}` and then lingers past the idle grace hands
  back err == nil with the envelope in stdout — where the exit-status path never
  sees it. All three JSON readers now check for that explicitly. It matters most
  for `config get agents.list --json`, where the envelope is how a 2026.6+ host
  says the key moved to the registry: decoding it as data turned a graceful
  fallback into a failed preparation. For the object-target read the failure is
  silent, since the envelope would be sanitized and written into the task's
  snapshot as if it were the user's config.

- RunCollectCmd selects on ctx.Done(). It takes a command the caller built, so
  enforcement must not depend on that caller having used exec.CommandContext;
  the ordering matches RunCollectQuiet so the two entry points cannot report
  different error shapes for the same situation. startCollector drops its unused
  ctx parameter rather than implying it enforces one.

- checkOpenclawVersion keeps stderr in the parse. It replaced CombinedOutput(),
  and a build that prints its version there would otherwise fail the gate on
  empty output, which skips runtime registration entirely. extractVersionLine is
  bypassed on purpose: parseOpenclawVersion already scans the whole text, while
  picking the first line containing a semver lets unrelated stderr noise answer
  for it. The probe is bounded because the caller's ctx is the task's, and
  ExplainExecError is applied here too so an ENOEXEC shim is still named
  (MUL-6164).

- TestRunCollectQuietWithoutCompletenessRuleWaitsForExit synchronizes on a
  marker the CLI writes after its answer instead of a deadline. Its two
  assertions want opposite budgets, and the reviewer reproduced the resulting
  flake 3/3 under load. Waiting for the marker also proves more than a timeout
  could: that the runner was still blocked at a moment when the answer was
  already fully available.

Scope: the MCP work that shared this branch is reverted to main's behaviour and
will come back on its own, because it needs a discussion this one does not. It
changed which command supplies the resolved MCP settings, restructured the
include chain, and moved where the user's config bytes live — none of which the
deadline fix depends on. Preparation for a managed-MCP agent behaves exactly as
it does on main here.

$OPENCLAW_HOME path expansion stays: openclawConfigPathComplete calls
openclawHomeRest directly, so the completeness rule for `config file` cannot
tell whether that shape is a finished answer without it.

* fix(agent): converge the collector's tree kill and stop failing calls on cleanup (MUL-5467)

Review follow-up on #6275. All three findings share one root cause: whether the
caller got its answer depended on whether cleanup converged, and cleanup
convergence depended on a single kill(-pgid) landing.

- Retry the tree kill across collectReapWindow. One pass loses a descendant
  whose fork completes between the kill's enumeration of the process group and
  the signal's delivery — measured 3 misses in 10 runs of the forking stub, each
  leaving a `sleep 300` reparented to init and stalling the call until the drain
  budget expired. The window is deliberately short so it does not widen the
  pid-reuse window reapProcessTree already documents.

- Replace the 5s EOF budget with a 400ms settle. Once the direct child has
  exited, at most one pipe buffer of its output can still be unread — a child
  that had written more would have blocked in write() and could not have exited
  — so a short cap cannot truncate a well-behaved CLI's answer. What it cuts
  short is a surviving descendant's trailing output, which is not the answer.

- Stop reporting cleanup residue as a call error. finish() now logs and returns
  nothing: a probe whose output arrived and whose helper the kernel would not
  kill is exactly the case #6084's cmd.WaitDelay got wrong, and a failed
  version probe skips runtime registration entirely. This drops finishErr,
  collectorError and the drainForced/waitPending split, which the four call
  sites were interpreting two different ways by accident.

- Fix the reaping tests. They asserted on `$$` captured inside `( )`, which
  POSIX keeps at the invoking shell's pid, so they named the direct child that
  cmd.Wait reaps regardless — all of them passed with reapProcessTree removed,
  while the run leaked 7 orphans. Record `$!` instead, and add
  TestRunCollectRetriesTheTreeKill, which injects a missed pass because the race
  lives inside one syscall and cannot be forced from a stub.

Verified: collector group 0/10 failures (was 3/10) with 0 orphans, 0/5 under
-race, full ./pkg/agent -race green, execenv Openclaw -race green, and both
mutations — retry removed, reaping disabled — fail the tests that now cover
them, on their own assertions rather than on a cleanup error.

* refactor: move the `$OPENCLAW_HOME` expansion out of this branch

It is not process-tree work. `openclaw config file` printing
`$OPENCLAW_HOME\...` instead of the expanded path is the same class of bug as
#6630 — a path the daemon cannot stat, reported as a fresh install, wrapper
without the user's `$include` — and #6643 shipped the tilde half of it as its
own change. This half belongs there too, not folded into a branch about
owning the CLI's process tree.

Removed here: openclawHomeRest, its branch in expandOpenclawPath, the unit
test, and the completeness-rule row that depended on it. Neither PR now
depends on the other.

openclawConfigPathComplete therefore does not recognize the variable shape,
which is correct in isolation: `main` cannot expand it either, so a rule that
accepted the line would hand the caller a path the parser then fails on.
Such a host keeps `main`'s behaviour — no rule match means RunCollectQuiet
waits for exit — so it loses the hang tolerance and nothing else. The comment
on that function says so and names the change that should close it, because a
gap nobody wrote down is one a rebase re-opens silently.

* fix(daemon): teach the config-path rule the `$OPENCLAW_HOME` shape (#7310 hand-off)

#7310 landed the parser side of this, so the deferred half is now due — and it
was recorded in the code precisely so a rebase could not drop it silently.

While expandOpenclawPath could not resolve `$OPENCLAW_HOME\...`, this rule had
to refuse the shape: accepting it would have reported a finished answer and then
handed the caller a path the parser failed on. The cost was that a host with that
variable set lost the early return entirely and went back to waiting for the CLI
to exit — which is the hang this branch exists to survive. With the parser
fixed, the refusal was the only thing left standing between those hosts and the
tolerance.

Resolved through openclawHomeFromEnv rather than read raw from the environment.
The value may itself be a tilde path that upstream expands before printing, so
`filepath.IsAbs` on the raw string answers false for `OPENCLAW_HOME=~/svc` and
silently withholds the early return on exactly the configuration #7310's review
was about. Mutation-checked: the raw-env version fails the new
`tilde-valued OPENCLAW_HOME` row with `rule(...) = false, want true`.

TestOpenclawOutputCompleteRules becomes subtests so a row can carry the
environment it is about, and gains three: an absolute OPENCLAW_HOME, a
tilde-valued one, and an unset one — the last staying false, so a line with
nothing to resolve it against still waits for exit and lets the parser report
the real error instead of this rule guessing.

* docs(agent): site the collector against outputOwned, not cmd.Output()

#7531 moved every one-shot probe in this package onto launch.go's
runOwned / outputOwned / combinedOutputOwned, which makes three claims in
this branch stale rather than wrong-in-detail:

- RunCollect called itself "the safe replacement for cmd.Output()". There
  are no cmd.Output() call sites left in pkg/agent. The comparison a
  reader needs is against outputOwned, which owns the same process tree
  and differs only in who owns the pipes — so that is what the doc
  compares, including why the probeWaitDelay bound is the right default
  for the probes it serves and the wrong one here.
- RunCollect's path-taking form advertised itself as the migration entry
  point for "the remaining cmd.Output() call sites (models.go's catalog
  probes, codex.go, deveco_models.go, thinking.go)". #7531 migrated all
  four to the owned helpers. It stays as the form for a caller holding
  only a path, and for a probe that turns out to need pipe ownership.
- collector's doc now says outright which of the two properties launch.go
  cannot provide, since "os/exec owns the draining" now describes
  in-package code rather than a stdlib call nobody here makes.

Also adds the `if: needs.changes.outputs.backend == 'true'` guard the new
Windows CI step was missing. Every other step in that job has it; without
it the step ran on frontend-only changes.

* docs(agent): cite upstream for the hang tolerance, not just the timings

The measured "prints its answer and then never exits" for `config file` and
`agents list` came from one host on openclaw 2026.5.27, which invites the
obvious objection: this is an upstream bug, so why compensate for it here
rather than wait for a fix.

Read at openclaw v2026.7.1, it is not a bug in a build — it is the exit
model. `src/cli/one-shot-exit.ts` provides an explicit opt-in,
`requestExitAfterOneShotOutput`, which `runCli` flushes after both streams
drain. In the shipped 2026.7.1 tarball exactly three modules take it:
`models list`, `models status`, and the hooks CLI. The commands this
package invokes — `config file`, `config get`, `agents list` — do not:
their success paths only print, and `runtime.exit` appears solely on their
failure paths, so termination is whatever the event loop happens to do.
A version that exits promptly is not promising the next one will.

Also pins openclawHomeRest's citation forward. `runConfigFile` still
prints shortenHomePath at v2026.7.1, and resolveHomeDisplayPrefix there
still selects `$OPENCLAW_HOME` on a non-empty trimmed variable and `~`
otherwise. Worth recording that the separator comes from the original path
rather than being inserted by the prefix, since that is what the rest-slice
in this function relies on.

* fix(daemon): size the config-file idle grace to the real warning gap

E2E on a real OpenClaw host (2026.7.1-2, plus 2026.6.8 and 2026.7.2-beta.7)
falsified two claims this branch was making. Both are corrected here; one
needed a code change.

**The 400ms idle grace was sized against the wrong gap.** The claim was
that a one-shot response arrives in back-to-back writes, so 400ms is
"orders of magnitude longer than the gap between those writes". The
first half is confirmed — 0.012-0.033ms between writes. The gap that
matters is a different one: with a config that produces Doctor and plugin
warnings, `openclaw config file` spread its stdout over 3289ms, of which a
single 3285ms silence sat between the end of the warning block and the
path. The default grace is eligible to fire inside that silence, on
whatever the warnings left in the buffer.

Why it lands on `config file` alone: upstream routes incidental console
output to stderr when argv carries `--json`
(withConsoleLogsRoutedToStderrForJson, src/cli/json-output-mode.ts at
v2026.7.1), so every `--json` caller here gets a stdout that is the JSON
document and nothing else, and a partial document cannot parse however long
the writer pauses. `config file` has no `--json`, so the warnings share its
stdout with the answer.

openclawConfigPathComplete is still the guarantee — a box-drawing border is
not an absolute path — and a grace can only be defence in depth, since the
gap is a property of the host's plugin and Doctor work. But it should not be
defence that loses by three seconds, so openclawQuietIdleGrace gives
`config file` 5s and leaves `--json` on the default. The cost is paid only
by a CLI that hangs: `config file` then returns in path + 5s rather than
path + 400ms, against a 30s deadline.

**RunCollect guarantee 2 overstated what a group kill can reach.** The
helper was measured holding the same stdout pipe as its parent (both
`pipe:[135202]`) while running with its own PGID and SID. `kill(-pgid)`
never reaches that, and neither does #7531's ownership, which uses the same
group. "Invoking a CLI on a timer cannot accumulate orphans" was therefore
wrong on Unix, and the three comments that repeated it are corrected. What
holds regardless is guarantee 1: it is pipe ownership, not the kill, that
makes Wait return and the deadline enforceable. Windows is unaffected — a
Job Object owns the tree irrespective of process groups.

Tests: TestOpenclawQuietIdleGraceCoversTheWarningGap pins the per-command
grace and asserts the `config file` value exceeds the measured gap;
TestExecOpenclawCLISurvivesTheWarningGapBeforeThePath drives a stub with a
warning block, a gap past the default grace, then the path, and requires
the path back.

* fix(agent): make pipe EOF the completion signal, and bound what is kept

Second review round found three blockers on b9b39eaea. All three reproduce
exactly as reported, and all three are cases where this branch was *worse*
than the launch.go helpers it replaced — which is the bar a replacement has
to clear, so the fix narrows the branch rather than patching around them.

**1. Leader exit was treated as answer completion (worst of the three).**
RunCollect*Cmd reaped the process group as soon as the direct child exited.
A wrapper can exit 0 while the real CLI — its descendant, holding the
inherited stdout — has not printed yet, which is the normal shape for an npm
or PowerShell shim. Measured here: the wrapper exits 0, its child prints the
version 500ms later, and this head returned an empty version with a *nil
error* in 427ms where outputOwned returns the version in 517ms. Empty-and-nil
is the worst available shape, and detectCLIVersion routes all 23 providers
through it.

Pipe EOF is the only signal that means "no more output is coming", so:

- detectCLIVersion, checkOpenclawVersion and discoverOpenclawAgents go back
  to launch.go's outputOwned / combinedOutputOwned, i.e. back to os/exec's
  own EOF wait. What this branch still fixes there is the *reporting*: a
  lingering descendant makes Wait report exec.ErrWaitDelay over an answer
  that arrived, and a failed --version probe skips runtime registration
  entirely (#6084 reverted a WaitDelay backstop over exactly that). So
  salvageProbeAnswer drops the error when, and only when, the caller's own
  parse found the answer — never on a non-zero exit, never on a deadline.
- The collector keeps its reason to exist (execenv's task-critical path) and
  gains awaitOutputAfterExit: after the direct child exits it waits for pipe
  EOF, bounded by collectDrainGrace (2s, matching probeWaitDelay), unless the
  caller's completeness rule says the answer is already in — so a CLI that
  prints and exits with a helper on the pipe still pays nothing.
- RunCollect / RunCollectCmd are deleted. With the probes back on
  outputOwned they had no production caller, and an exported wait-for-exit
  collector is exactly the API that invited this bug.

**2. A path-shaped warning could be returned as the config path.**
openclawConfigPathComplete accepted any absolute-looking last line, and the
previous commit's answer — a 5s grace — was the wrong dimension, as the
review pointed out by quoting this branch's own comment that no fixed grace
can bound the host's plugin work. Reproduced: a CLI printing an existing
plugin-cache.json path, pausing 6s, then printing the real path returned the
warning path after 5.51s.

Fixed by not asking a question content cannot answer. `openclaw config
validate --json` reports the path in a named `path` field, on every branch
(valid / invalid / file-not-found / error), in every version from v2026.5.5
— which is minOpenclawVersion — through v2026.8.1-beta.3, and `--json` makes
upstream route incidental output to stderr so stdout is the document alone.
openclawActiveConfigPath asks that first and keeps `config file` as a
fallback with no completeness rule at all: it waits for exit and fails closed
on the deadline. Upstream runs the same readConfigFileSnapshot() for both
commands, so preferring the JSON form costs no extra work; it costs one extra
invocation only on a CLI too old for either, which is pinned in
TestPrepareOpenclawConfigFallsBackWhenConfigFileUnsupported.

openclawConfigPathComplete, openclawQuietIdleGrace and
openclawConfigFileIdleGrace are gone. `--json` is now the only shape with a
rule, and the doc says why that is the design and not a gap.

**3. Retention was unbounded.** absorb appended without limit, where
outputOwned keeps the last probeStderrSampleBytes. Measured: 13,107,400 bytes
of stderr retained from a CLI writing continuously, ~400x the bound it
replaced. stderr now keeps its tail at collectStderrTail (= 32 KiB, so moving
a call site between mechanisms cannot change what a failed probe reports) and
stdout is capped at collectStdoutLimit and reports overflow as an error —
deliberately asymmetric, because a head-truncated answer is how a partial
catalog becomes a confident empty one.

Every new guard was mutation-verified by restoring the mechanism it covers:

| Mutation | Test | Failure |
|---|---|---|
| collector + reap on leader exit | TestDetectCLIVersionWaitsForAWrapperDescendant | `version = ""` in 0.42s |
| awaitOutputAfterExit returns immediately | TestRunCollectQuietWaitsForAWrapperDescendant | `stdout = ""` |
| drop the rule short-circuit | TestRunCollectQuietDoesNotWaitWhenTheAnswerIsIn | pays the full 2s |
| unbounded buffers | TestCollectedStderrKeepsOnlyItsTail | retained 13,107,417 bytes |
| unbounded buffers | TestCollectedStdoutOverflowIsReportedNotTruncated | 524,296 bytes, nil error |
| shape rule for `config file` | TestOpenclawActiveConfigPathIgnoresAPathShapedWarning | returns plugin-cache.json |

The new fallback test also caught a bug in this commit before it shipped:
openclawValidatedConfigPath accepted upstream's `CONFIG_PATH ?? "openclaw.json"`
literal, because expandOpenclawPath turned that relative name into a confident
path under the daemon's cwd. It now requires the reported value to be absolute
before expansion, allowing only the `~` and `$OPENCLAW_HOME` forms.

* fix(agent): repair the Windows-only collector test call sites

The mechanical conversion of the deleted RunCollect call sites over-widened
three tuples in run_collect_windows_test.go, which already used
RunCollectQuiet's four results. Host `go build` and `go vet` never compiled
them — the file is `//go:build windows` — so the break surfaced on the
windows-execenv job as `assignment mismatch: 5 variables but RunCollectQuiet
returns 4 values`.

Verified this time the way it should have been the first time:
`GOOS=windows go build ./...` and `GOOS=windows go vet ./...`, plus darwin and
linux. That is the check to run whenever this package's exported signatures
move, since a third of its process-lifecycle tests only compile on Windows.

* test(execenv): pin the config-path payload shapes E2E measured

E2E on OpenClaw 2026.7.1-2 confirmed `config validate --json` as the config-path
source and corrected two things this branch had inferred from source.

**The exit status is load-bearing in the wrong direction, and this was untested.**
Two of the three real states exit *non-zero* while carrying the answer: a missing
config file gives `{"valid":false,"path":"…","error":"file not found"}` and an
invalid one `{"valid":false,"path":"…","issues":[…]}`, both exit 1 with stderr
empty. A fresh install is the missing-file case, so reading a non-zero exit as
"no answer" would break first run. openclawValidatedConfigPath already ignored
the status, but nothing pinned it — writeOpenclawConfigStub could only exit 0, so
the tests covered the rarest branch. It now takes an exit code, and
TestOpenclawActiveConfigPathReadsThePathFromANonZeroExit drives all three
measured payloads.

**Two source-based claims corrected.**

- "Preferring the JSON form costs nothing extra" understated it. Measured over
  three runs each on the same host and config: 1.65/1.66/1.65s for
  `config validate --json` against 6.36/4.16/4.06s for `config file`. The JSON
  form is ~2.5-4x faster, which tracks the output it does not render — 715 bytes
  of JSON against 2663 bytes and 28 lines of warning UI.
- The reason a `--json` stdout is clean was attributed to upstream's
  console-log reroute (`withConsoleLogsRoutedToStderrForJson`). That function
  exists, but it is not what was observed doing the work: the Doctor and plugin
  warnings arrive as a `warnings` array *inside* the payload. The distinction
  matters for why JSONOutputComplete is a real signal — the stream is
  structurally one document, not merely quieter — so the comments now describe
  the measurement rather than the mechanism inferred from it.

Unrelated and pre-existing: `./pkg/agent`'s ACP timing tests (1-6s wall-clock
budgets) flake under load, and which ones fail varies per run. Control run of
`origin/main`'s whole package on this machine, same conditions: fails
TestCodexExecuteSemanticInactivityAllowsContinuousMessages and
TestCodexExecuteLegacyFirstTurnMessageSatisfiesProgress. Not introduced here.

* fix(agent): require a recognised version before salvaging a probe answer

The ErrWaitDelay salvage in detectCLIVersion was gated on `version != ""`,
and extractVersionLine falls back to the trimmed raw output when no line
carries a semver token — so any non-empty text satisfied it, including
whatever a wrapper printed before the real version existed.

Review reproduced it with a stub that prints a banner, exits 0, and has a
descendant print the version past the 2s WaitDelay: detectCLIVersion
returned "initializing plugins" with a nil error, and logged "CLI answered
but left its output pipes open" — the opposite of what happened. That value
is then persisted as the runtime version, for every provider, since
DetectVersion routes all 23 through here.

extractVersionLine now reports whether the semver scan actually matched, and
only that answers the salvage question. The trimmed-raw fallback still
stands on the success path: a CLI that exits 0 with an unusual version
format is reporting its version (#2516), and it is only unusable as evidence
that a bounded, incomplete read already holds the answer.

Mutation-checked: with the old gate,
TestDetectCLIVersionDoesNotSalvageABannerAsTheVersion fails with exactly the
reviewed shape — version="initializing plugins", nil error, misleading warn.

* test(agent): derive the collected-stdout cap from the largest answer

collectStdoutLimit argued for why a fail-closed cap is needed but not for
its value, and where it falls is a product compatibility boundary rather
than only a memory bound: a legal config past the cap stops a task from
starting at all.

The derivation is now recorded and executable. Measured answers on 2026.7.1-2
are 715 B (`config validate --json`) and 2663 B (`config file`); the largest
answer any call site asks for is the resolved config from `config get --json`,
which upstream puts no ceiling on. So the worst case is constructed — 1000
agents and 250 MCP servers with the fields OpenClaw carries, 547,291 bytes,
already orders of magnitude past a real deployment — and 8 MiB leaves 15x on
top of it while matching what the daemon already holds for a comparable
per-task payload (maxLocalSkillBundleSize).

Two tests pin it: the constructed high-water mark must round-trip through the
collector byte-identically with the stated headroom, and the boundary itself
is exact — at the limit the answer is returned whole, one byte past it fails
closed with errCollectStdoutTooLarge.

* fix(execenv): share one CLI deadline across both path-resolution attempts

openclawActiveConfigPath asks `config validate --json` first and falls back
to `config file`, and the fallback carried a fresh full deadline. That made
the worst case five budgets against a ceiling derived from four: at the 60s
override ceiling, 5m of CLI time alone, landing exactly on
daemon.defaultTaskPrepareTimeout — so the specific, non-retryable
ErrOpenclawCLITimeout collapses back into the generic retryable prepare
timeout, which is the outcome openclawCLIMaxTimeout exists to prevent.

Both invocations answer the same question, so they now share one context.
The multiplier is renamed to openclawMaxCLIDeadlinesPerPreparation because
that is what it always measured — the budget is per step, not per invocation.

The consequence is deliberate and asserted: a validate that burns the whole
budget leaves the fallback none, os/exec reports the expired context on Start,
and the failure still carries ErrOpenclawCLITimeout. A CLI that cannot say
where its config is within the entire deadline will not answer the same
question on a fresh one.

TestPrepareOpenclawConfigWorstCaseCLIBudgets now drives the real worst case
(validate fails, config file answers, registry fallback, managed MCP) and
counts distinct ctx deadlines rather than calls — the old test synthesized a
validate success from the `config file` response, so the two never fired in
the same run. Mutation-checked: with separate deadlines it reports 5 budgets
against a constant of 4.

---------

Co-authored-by: weiweiwei <[email protected]>
2026-08-28 14:04:10 +08:00
cd169947b5 MUL-6686 feat(daemon): use readable workdir paths (#7316)
Create new task environments under sanitized, bounded readable segments:
<workspace-slug>-<workspace-short>/<issue-key>-<task-short>/workdir.

The readable name is the visible part; the substance is moving task identity
off the directory name. A human-readable segment is mutable — workspace slugs
and issue prefixes change — so workspace/task identity now lives in
.task_owner, .gc_meta.json and a stable ID-keyed index under .task_roots that
freezes one physical root per task for its lifetime. GC and disk-usage read
that authoritative identity instead of inferring a workspace from a path
string, which also fixes active and preparation-crashed roots being attributed
to a nonexistent workspace.

Existing workdirs are not renamed or migrated, legacy roots are adopted into
the index, and both layouts render privacy-safe relative paths. Labels are
lowercased ASCII with separators and traversal collapsed, segments are capped
at 24 characters so the two together stay within the previous 49-character
Windows path budget, and stable ID suffixes drawn from the UUIDv7 random tail
keep roots distinct across renames and case-insensitive filesystems.

Closes #6063

Co-authored-by: iiwish <[email protected]>
Co-authored-by: J <[email protected]>
2026-08-26 16:34:10 +08:00
YYClaw 8c563b49be MUL-6555 feat(issues): preserve source context for sub-issues (#7461)
* feat(issues): preserve source context for sub-issues

* fix(issues): address source context review findings

* fix(migrations): guard source context rollback preflight
2026-08-25 12:00:49 +08:00
8a5a6adbf7 feat(agent): add ZeroClaw as a native ACP runtime (MUL-6511) (#7351)
* feat(agent): add ZeroClaw as a generic ACP agent runtime

Add ZeroClaw (a Rust-based, single-binary generic agent CLI) as a
first-party runtime, driven over the standard ACP JSON-RPC transport via
`zeroclaw acp`, mirroring the Dim/QwenPaw/Grok ACP backend shape. Only the
binary, launch args, and blocked-flags policy are ZeroClaw-specific; the
backend reuses the shared hermesClient ACP transport and deliverable
tracker.

No provider-specific quirks (permission-preset injection, minimum-version
gate, or a separate authenticate step) are assumed without evidence — those
were verified against real Dim/Grok binaries and would need the same
hands-on verification against a real ZeroClaw binary before being added
here.

Backend: SupportedTypes/New/launchHeaders wiring, model discovery via
session/new's advertised catalog, daemon probe with
MULTICA_ZEROCLAW_PATH/MODEL overrides, AGENTS.md context delivery,
default-command-name registration, metrics label, and a migration widening
the runtime_profile.protocol_family whitelist.

Frontend: provider union, MCP-config support flag, and a placeholder
provider-logo mark (no official ZeroClaw brand asset exists yet).

Tests mirror the existing ACP backend conventions: fresh-session,
resume-via-session/load, resume-not-found, transient-load-error, blocked
launch args, timeout, and the shared ACP deliverable-boundary regression
suite.

* fix(agent): renumber ZeroClaw's migration to 378 to avoid a same-day collision

Both this branch and a concurrently-implemented Junie runtime branch
independently picked migration 377 off the same origin/main tip.
Renumbering ZeroClaw to 378 up front avoids opening two PRs from the
same author that claim the same migration number.

* fix(agent): align the ZeroClaw ACP backend with the real 0.8.4 runtime

The backend was written against an assumed vanilla ACP handshake and never
checked against a ZeroClaw binary. Driving a real zeroclaw 0.8.4 over stdio
shows five of those assumptions are wrong, and the test fake encoded the same
assumptions, so the suite stayed green against a contract the runtime does not
have.

- Drop the session/set_model request. It is not in ZeroClaw's dispatch table
  (-32601) and no ACP handler reads a model param at all, so it could never
  succeed; because its failure was fatal, any agent with a model configured
  failed before session/prompt was reached. The model comes from the ZeroClaw
  agent profile, so opt zeroclaw out of ModelSelectionSupported and stop
  reading MULTICA_ZEROCLAW_MODEL rather than leaving the UI offering an
  override that is silently ignored.

- Label token usage from initialize's _meta.zeroclaw.defaultModel, the only
  model identity the ACP surface exposes. session/new returns just
  {sessionId, workspaceDir}, so the two extractACPCurrentModelID reads were
  dead code and the model-catalog discovery they fed could only ever return an
  empty fallback while paying an ACP subprocess per catalog read. Return an
  empty catalog directly, as qwenpaw/mcode do.

- Resume through session/resume instead of session/load. Both restore the
  transcript into the agent, but load also replays every retained message back
  as session/update notifications, which fed the previous answer into this
  turn's deliverable. Add the acceptNotification turn gate every other ACP
  backend carries, so out-of-turn chunks are dropped even if a runtime flushes
  them early (#1997).

- Send agentAlias on session/new when the operator names one. ZeroClaw
  auto-selects an agent only when its config holds exactly one entry, so
  multi-agent installs failed with -32602 and had no way out: `zeroclaw acp`
  has no --agent flag, and passing one kills the process at argument parsing.
  The alias is consumed from custom_args and travels as a param; it is omitted
  when unset, because a hardcoded guess breaks the single-agent case that
  works today. The refusal now names both remedies.

- Stop advertising MCP support. No ZeroClaw handler reads params.mcpServers;
  acp_enable_mcp gates that agent's own mcp_bundles, not the client list, so
  MCP is operator-side only. Hide the MCP tab and warn on a stale mcp_config
  instead of failing the task.

Also teach isACPSessionNotFound about ZeroClaw's custom -32000
SESSION_NOT_FOUND, without which a stale session id was retried forever
instead of restarting fresh. The wording check still decides, so a transient
error under the same code stays non-rejecting.

Tests now encode the observed handshake — _meta default model, session/new
without a catalog, -32000 for an unknown session, -32601 for set_model — and
cover the replayed-history, alias and MCP paths.

* fix(agent): make ZeroClaw integration merge-safe

Co-authored-by: multica-agent <[email protected]>

* fix(agent): tighten ZeroClaw ACP fallbacks

Co-authored-by: multica-agent <[email protected]>

* fix(agent): preserve ZeroClaw retry semantics

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-24 14:39:08 +08:00
2284420966 MUL-6622: fix(server): authorize squad activity by task provenance (#7489)
* MUL-6622: fix(server): authorize squad activity by task provenance

`multica squad activity` rejected every issue that was not itself assigned
to a squad, so a leader woken by an `@squad` mention on an agent-owned issue
or running a leader task bound to a child issue could not record its
evaluation. Because the injected `no_action` rule makes that call the
substitute for a comment, the decision left no trace at all.

The claim path already keys the squad briefing and the mandatory-recording
instruction off the task row (`is_leader_task` + `squad_id`), not off the
issue's assignee. `RecordSquadLeaderEvaluation` now uses the same source:

- load the `X-Task-ID` row first and require it to be a leader task with a
  stamped squad; resolve the squad from `task.squad_id`;
- drop the `issue.assignee_type == "squad"` precondition;
- authorize against `task.agent_id` rather than the live `squad.leader_id`,
  and record `activity_log.actor_id` as `task.agent_id`. A mid-run leader
  change no longer discards a real evaluation, and no longer misattributes
  it in a way that silently desyncs the `no_action` comment suppression
  lookup (which matches on `task.agent_id`);
- name the task's issue in the cross-issue rejection, since a stage-barrier
  wake runs on the parent and reaching for the child id is the common slip.

Leader agents running a NON-leader task are now rejected: they are not
running as the leader, and the runtime only mandates the call for leader
tasks. This is the one behavior narrowing, covered by a test.

The injected instructions also gain a failure fallback. The comment
prohibition is already conditional on the activity existing
(comment.go:1851), so a leader whose recording call errored may comment —
it just was not told to. It now is, closing the silent-drop path for any
remaining failure cause.

Fixes #7487

Co-authored-by: multica-agent <[email protected]>

* MUL-6622: fix(server): close review findings on squad activity authorization

Addresses the four items from PR review.

1. Tenant isolation. `GetAgentTask` is a global lookup by id and the
   cross-issue rejection quotes the task's issue id, so an unrelated task
   probed through a readable issue echoed back a foreign workspace's issue
   id. The task is now loaded with `GetAgentTaskInWorkspace`, and check
   order is explicit: tenant scope, then "caller owns this task", and only
   then any message naming a task-derived id.

2. Claim-time role divergence. `is_leader_task` on the row is enqueue-time
   intent: when the leader is swapped before the claim, the claim path
   clears `resp.IsLeaderTask` and runs the task as an ordinary agent turn
   while the row keeps the flag set. Trusting the row alone let such a
   downgraded run write a leader verdict and suppress its own comment, so
   the live `squad.leader_id == caller` gate is restored on top of the task
   ownership gate. `activity_log.actor_id` stays `task.agent_id`, which is
   what the no_action suppression lookup matches on. Removing the live gate
   later requires persisting the role the claim actually delivered.

3. Failure fallback vs. one comment per turn. The new "comment if the
   recording call fails" instruction contradicted the exactly-one-comment
   rule on the `action` path, where a delegation comment already exists. All
   four injection sites now scope the fallback to turns that have not
   commented yet and cap it at one comment. Pinned by
   TestSquadOperatingProtocolRecordsAgainstTheTurnsIssue and
   TestBuildPromptSquadLeaderNoActionFailureFallback.

4. Shared test fixtures. The new handler tests are rebuilt on
   `internal/testutil` (`dbfx.Issue` / `dbfx.Task` / `dbfx.Squad`,
   `testutil.Call(...).Want(...)`) instead of open-coded
   `INSERT ... RETURNING` and recorder quartets, per CLAUDE.md. The shared
   `runningSquadLeaderTaskFixture` moved over too.

New negative coverage: foreign-workspace task and foreign-agent rejections
both assert the response body does not contain the other issue's id, and
a leader change before recording is now asserted to be refused.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-24 14:38:07 +08:00
Bohan Jiang 0a54725fe6 MUL-6567 fix(execenv): lock a local_directory repo's git section across processes (#7462)
The lock meant to serialise git admin work on one repository was an in-process
sync.Mutex, and no two contenders were ever in one process: a daemon prepares
every task in a short-lived helper, and worktree mode deliberately skips the
per-path task mutex, so N concurrent tasks on one local_directory were N
processes issuing git commands at the same repo with nothing between them.

`git stash create`, which captures the user's uncommitted work before the
worktree is built, needs the repository's index lock and lost that race
routinely — reproducibly in about two runs out of three for two concurrent
prepares on a dirty repo. git reports the loss as exit status 1 with nothing
on stderr, and nothing retries a failed task, so the run died undiagnosable
and the issue rolled back to todo.

- lockGitRoot now takes an advisory file lock in the repository's COMMON git
  dir alongside the mutex, reusing the flock/LockFileEx primitives the env-root
  claim relies on. The common dir is what makes one lock cover one repository:
  the guarded section contends both for the per-worktree index.lock and for the
  refs / worktrees/ state every linked worktree shares. The file lock is taken
  before the mutex so waiting is not itself serialised. A git dir that cannot
  hold a lock file falls back to the mutex; a BUSY lock fails the caller.
- The capture retries, 5 attempts over ~1.5s, for the index-lock races owned by
  the user's own tools. `stash create` writes a commit object and returns its
  sha without touching the index, refs or working tree, so retrying repeats
  nothing.
- runGitStdout renders git's stderr into its error instead of collecting it
  into ExitError.Stderr and dropping it, and the capture names .git/index.lock
  when git itself says nothing.

Finalize and Discard take the same lock, so a prepare in a helper and a
finalize in the daemon parent no longer overlap. Finalize reports its worktree
as preserved if it cannot get the lock.

Seven tests, each verified to fail against the code it fixes, including a
second PROCESS holding the lock and two concurrent PrepareIsolated runs on one
repo. The timeout message is pinned never to advise deleting a held lock file:
the lock binds to an open file description, not a path, so unlinking it would
let two tasks into the same section at once.

Refs #7434
2026-08-24 01:12:39 +08:00
8f9c766e40 MUL-6460: feat(brief): inject the workspace status catalog into the agent brief (#7306)
Agents could not see custom issue statuses (MUL-6243): the brief's status
command line hardcoded the seven built-in keys, so a workspace's Human
Review / Rework statuses were invisible even when instructions asked for
them, and the CLI offers no catalog read an agent could fall back on.

Ship the catalog on the claim payload, the same path WorkspaceContext
already rides: buildClaimedTaskResponse reads the workspace's ACTIVE
CUSTOM statuses (built-ins stay off the wire — their keys, names and
semantics are locked) and the daemon copies them into TaskContextForEnv.
The brief's status bullet then renders the workspace's statuses grouped
by category, with each custom status's name and description — category
anchors the inherited platform behavior, name is what users call the
status in instructions, and description is the admin's disambiguator
when a category holds more than one status. A bridge bullet in the issue
workflow connects the existing category-level status rules (which stay
untouched) to the concrete key choice.

With no custom statuses — every old-server pairing included — both
renders are byte-identical to before, keeping the prompt-cache prefix
stable for existing deployments (MUL-5377). The catalog is durable
workspace configuration like WorkspaceContext, not per-turn state, so it
belongs in the brief rather than the per-turn prompt. The claim read is
not gated on the custom_issue_statuses flag: the flag only guards
creation, and a catalog written before a flag flip must stay visible as
long as issues can sit on it. Name/description are user-authored and
pass through sanitizeNameForBriefMarkdown; a key failing the code-token
guard drops its entry. A 30-entry cap with an explicit omitted count
keeps a scripted catalog from flooding the brief while disclosing the
truncation.

Also update the built-in skills that document status semantics
(multica-working-on-issues, multica-squads) and their source maps:
statuses beyond the built-ins inherit their category's behavior in full,
with the two literal-key exceptions (failed-task rollback writes todo,
merged close-intent PR writes done) called out.

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-21 17:40:27 +08:00
520359a2c9 MUL-6518 fix(daemon): reclaim orphaned per-task temp dirs in the GC (#7391)
* refactor(daemon): give the lock and dir-stat helpers neutral names

openEnvRootLockFile, releaseEnvRootLock and codexStoreStat are all
generic: they take a path, and nothing in them knows about env roots or
Codex stores. The next commit reuses the same execution lock for per-task
temp directories, where the old names would read as a bug at the call
site.

No behaviour change.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): reclaim orphaned per-task temp dirs in the GC

Every task gets a private temp dir (multica-task-*) under the system temp
base, exported to the agent as TMPDIR/TMP/TEMP. Its only exit was the
RemoveAll deferred at the end of runTask, which does not run when the
daemon is killed and does not succeed while a file inside is still open —
the Windows case reported in #7364, where one machine had accumulated 174
leftover directories. The GC never covered them: it scans WorkspacesRoot,
and the temp base is a different root, so multica-task- had exactly one
create site and zero reclaim sites.

Sweep the temp base as a fourth out-of-root pruner. Liveness is decided by
the directory's .task_lock — the same OS advisory lock an env root uses —
not by age: the sweep removes a directory only once it has itself acquired
the lock the owner would still be holding, which the kernel grants only
after that owner is gone.

Using the lock rather than a marker or a TTL is what makes this correct
rather than probabilistic. It is held by an open file description, so it
answers for a live task in this very process as well as one owned by a
different daemon sharing /tmp, which no in-memory active set could see.
And it needs no upper bound on task runtime — there is none to assume,
since DefaultAgentTimeout is 0.

Directories left by daemons predating the lock carry no lock file, so age
is the only signal available for them; they are reclaimed after
MULTICA_GC_TASK_TEMP_LEGACY_TTL (72h). That branch exists to clear the
existing leftovers and can be dropped in a release or two.

The end-of-run RemoveAll stays exactly as it was, and nothing was added to
the task-completion path: the run releases the lock before removing, so a
removal that fails there costs nothing and the next GC cycle finishes the
job.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): keep the temp dir marker when cleanup cannot finish

Two fixes from review.

1. A failed cleanup destroyed the marker the next sweep needs.

   os.RemoveAll keeps walking after a failure, so removing a directory
   whose payload is still open deleted the .task_lock sitting next to it
   and then returned the error. The directory came back as one with no
   marker — indistinguishable from a pre-lock leftover, so it was no
   longer reclaimable on liveness at all. That is exactly #7364's failure
   path, and it made the claim this change is built on ("a failed removal
   costs nothing, the next cycle retries") false.

   RemoveTaskTempDir removes contents first and stops at the first one it
   cannot remove, leaving the marker behind; the lock file goes last, once
   everything else is gone. Both the task-completion path and the GC use
   it. A cleanup that fails now leaves a directory that is still
   lock-bearing and still unlocked, so the next cycle takes the lock and
   retries — for as many cycles as the holder needs.

2. The legacy TTL could delete a live task's TMPDIR.

   Pre-lock directories were reclaimed on age after 72h by default, but
   age cannot establish liveness: DefaultAgentTimeout is 0, so a task may
   legitimately run far longer than any TTL; a daemon on another profile
   can still be running the old binary during an upgrade; and every daemon
   on the machine shares one temp base. The default is now 0 — leave them
   alone — and reclaiming them is an operator's explicit opt-in. Each
   cycle logs how many were left in place so the choice stays visible
   rather than silent.

   Classification also fails closed: only os.ErrNotExist means "no lock
   file". Any other stat error (another user's dir under a shared /tmp)
   now reads as in-use instead of legacy.

Regressions for both: a Windows test that makes a real sharing violation
with CreateFile minus FILE_SHARE_DELETE, asserting the marker survives the
failed cleanup and the directory goes once the handle closes (wired into
the Windows CI job, which runs targeted filters rather than whole
packages); and unix equivalents driving the same paths through an
unlinkable payload, plus fail-closed coverage for an unreadable directory.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): publish the temp dir marker atomically, restore it on rmdir failure

Two more windows in the marker's lifecycle, from review.

1. A directory could be swept between marker creation and lock acquisition.

   LockTaskTempDir created .task_lock and locked it as two steps, so there
   was an instant where the marker existed unlocked. A sweep landing there
   reads exactly what a dead owner leaves behind: it takes the lock,
   concludes the owner is gone, and deletes the directory — after which
   the starting task's own lock call succeeds and it runs with a TMPDIR
   that no longer exists.

   The marker is now locked under .task_lock.claiming and renamed into
   place once held. Rename within one directory is atomic and the lock
   rides on the open file description, not the name, so the marker becomes
   visible and held in the same step.

   Before that rename the directory carries no marker, which classifies as
   legacy — and legacy only reclaims what is OLDER than legacyTTL. A
   directory created microseconds ago is younger than any positive TTL,
   and a TTL of 0 disables the branch outright, so no configuration can
   sweep the pre-publish state either.

2. A failed rmdir left a directory with no marker.

   The marker has to be deleted before the directory can be removed, so a
   failure at that last step — a Windows process holding a handle to the
   directory, or content an orphaned child recreated — left a directory
   nothing could classify again. With the legacy branch disabled by
   default that is a permanent leak, and it was the one path where cleanup
   got furthest. The marker is now put back when that removal fails, so
   every failure mode leaves the retry available.

Regressions: the publication order and the mid-claim on-disk state (spared
under a disabled TTL and under positive ones), a sweeper running flat out
against 200 publish/use/cleanup cycles, and the rmdir-failure branch —
which fails without the restore, verified by removing it.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): decide the legacy sweep on content, not on age alone

The publication window was still open. The claim-then-rename ordering
stopped .task_lock from ever existing unlocked, but a directory mid-claim
carries no .task_lock at all, so the sweep still reaches it through the
legacy branch — and the argument that protected it there was wrong.

That argument was "a directory created microseconds ago is younger than
any positive TTL". MULTICA_GC_TASK_TEMP_LEGACY_TTL takes any duration,
down to a nanosecond, and an owner stalled between MkdirTemp and the
rename outlasts a large TTL just as easily. Reproduced at 1ns, 1ms, 1h
and 72h alike: the sweep deleted a directory whose claim was held.

Age cannot separate a pre-lock leftover from a directory being published,
so stop asking it to. Content can: a directory being published holds
nothing but its own lock files, because the task has not been handed the
path yet and cannot have written anything, while a leftover worth
reclaiming is by definition one with something in it. The legacy branch
now reclaims only directories that hold task content, which covers both
halves of the window — the empty directory before the claim exists, and
the claim-only directory after — at every TTL value, with no timing
assumption left in the argument.

The cost is that a pre-lock daemon which crashed before its task wrote
anything leaves an empty directory nothing reclaims. That is a few bytes
against deleting the temp dir of a task that is starting.

Tests: the mid-claim cases now run at 1ns/1ms/1h/72h with now pushed PAST
the TTL, so they fail if anything reintroduces a timing argument; the
pre-claim (empty directory) half is covered the same way; and the
invariant itself is pinned directly, so relaxing it breaks a test rather
than a race. The existing legacy TTL test now models a real leftover by
giving it content. Verified all of these fail with the content rule
removed.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): re-check the lock immediately before removing a legacy dir

The legacy branch's decision is several separate observations — classify,
then walk for content, then walk for mtime — and a directory can finish
publishing in the middle of them. Classified as legacy while its marker
was still unpublished, then published and written to by its task, and the
removal went ahead without ever looking at the marker that had appeared:
the sweep deletes a live task's TMPDIR. What was accidentally holding this
together was that the task's own write refreshes the mtime — a timing
crutch, in the branch whose whole point is not to rely on one.

Re-read the classification immediately before removing, and skip unless it
is still legacy.

That closes the window rather than narrowing it, because of what content
means: a task only writes into the directory after it has been handed the
path, which happens only after LockTaskTempDir returns and therefore only
after the marker is published and held. So content observed at the top of
the branch, plus no marker seen at the bottom, proves no live task owns
this directory — and none can arrive later either, since MkdirTemp only
ever hands out a fresh empty directory under a new name.

The regression drives that exact interleaving through a barrier: the sweep
commits to removing the directory, the owner then publishes and its task
writes, and the sweep must notice. `now` is far past the TTL so age cannot
mask it. Verified it fails without the re-check.

Also from review: drop a stale test comment that still claimed a positive
TTL can only be configured far above a directory's age, and record in the
config and operator docs that a directory holding no task content is never
reclaimed on age — including a shell left by a CURRENT daemon that died
between creating the directory and publishing its lock, not just an old
daemon's empty leftover.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-21 17:38:44 +08:00
Bohan Jiangandmultica-agent d2532f766b MUL-6491 fix(daemon): fence env-root resets on a live execution, not a task id (#7356)
* fix(daemon): fence env-root resets on a live execution, not a task id

Follow-up to #7347. The identity marker answers WHO owns an env root, not
whether that owner is still running, so Prepare read "owner == my task id"
as "my own rerun, safe to reset".

That is reachable rather than theoretical. ReclaimStaleDispatchedTaskForRuntime
re-delivers a task row whose prepare lease expired using the SAME task id,
and a failing lease renewal only logs — it does not cancel the Prepare still
in flight. The re-delivered execution then wiped the running one's workdir,
config and worktree: the cross-execution deletion the env-root claim exists
to prevent, arriving through the one door it left open.

Add a second signal alongside the marker: an OS advisory lock on the env
root, held for the life of the Environment and released by Cleanup. The
kernel drops it when the holder exits for any reason, so it answers "is the
previous execution still alive?" across processes with no heartbeat, no PID
table and no stale-state cleanup path — a crashed execution's directory is
recoverable on the next dispatch, a running one's is not.

Taking the lock first also serialises the claim, which replaces the
Mkdir/O_EXCL arbitration with something simpler and stronger: no other
execution can be mid-claim, so the checks below it cannot race.

That in turn fixes the torn-marker case from the same review. The marker was
created empty and written a moment later, so a crash in between left a
zero-length file that read back as "no owner" while still counting as
directory content — the env root could then be neither adopted nor reset,
and stayed wedged until someone deleted it by hand. Under the lock an
unnamed marker is simply rewritten.

Tests, each verified to fail without its fix: an overlapping execution of one
task id is refused and the live work survives; the same id recovers once the
prior execution released the root; a torn marker is repaired instead of
wedging.

Refs #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): release the env-root lock at the end of the task run

Windows CI caught that the lock outlived the work it guards. It was released
only by Environment.Cleanup, which production never calls — the GC reclaims
env roots on its own schedule — so the lock was effectively held until the
daemon exited. Two consequences: every later dispatch of that task would
fail closed as "held by a running execution", and on Windows the open handle
pinned the directory so nothing could remove it:

    TempDir RemoveAll cleanup: unlinkat ...\.task_lock:
    The process cannot access the file because it is being used by another process

Release it where the execution actually ends. The daemon now defers
ReleaseLock alongside unmarkActiveEnvRoot, which is the same lifetime: the
task run. Cleanup still releases too, and both are idempotent.

Also open the lock file with FILE_SHARE_DELETE on Windows. os.OpenFile does
not request it, and without it Windows refuses to delete a file anyone holds
open — the lock is meant to coordinate executions, not to pin a directory
against the GC. Unix already allows unlinking an open file; this makes
Windows behave the same.

Refs #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): hold the env-root claim in the parent, not the prepare helper

Review found the lock never applied in production. Real daemons always
prepare through PrepareIsolated, which runs a short-lived helper process:
the lock was taken inside that helper, the kernel released it the moment the
helper exited, and Environment.lockFile is an *os.File that cannot cross the
helper's JSON response. The parent got back a nil lock, so ReleaseLock was a
no-op and the agent ran with no protection at all — the exact re-dispatch
window this was meant to close.

Every test added with the lock went through the in-process Prepare, where
the "helper" never exits, so none of them could see it.

Move the claim to the daemon parent, whose lifetime IS the task run:

- ClaimEnvRoot / EnvRootClaim.Release are now exported, and runTask takes
  the claim alongside markActiveEnvRoot and releases it on every exit.
- PrepareParams.EnvRootPreclaimed tells preparation the caller already holds
  the claim and performed its reset, so it does not try to take a lock the
  parent is holding. Direct in-process callers still claim for themselves.

Also cover the reuse path, which took no claim at all: a task continuing in
a PRIOR task's env root now excludes on that root through
LockEnvRootForReuse. Identity there belongs to the earlier task, so this is
the exclusion half of a claim only — without it two continuations of one
task could refresh and run the same workdir concurrently. Guarded to roots
under the workspaces root, since a local_directory task's PriorWorkDir is
the user's own directory.

Tests now exercise the production path: one drives PrepareIsolated through
the real helper harness and asserts the parent still holds the claim after
the helper exits, the other covers reuse exclusion. Against the previous
arrangement the first fails with "a second execution claimed the env root of
a task that just prepared".

Refs #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): lock a prior env root only after proving it is a managed one

Review found the reuse guard wrote its lock file before it had established
where it was writing. runTask locked filepath.Dir(task.PriorWorkDir) up
front, gated only by a lexical filepath.Rel containment check — which does
not resolve symlinks. A link inside the workspaces root pointing anywhere
else passed that gate, and .task_lock was created in the target: a user's
own directory, or a path outside the root entirely. Eligibility was not
settled until much later, in shouldReusePriorWorkdir.

Reorder so the proof comes first. shouldReusePriorWorkdir already resolves
symlinks and verifies the {workspace}/{task}/workdir shape, managed
provenance and the task-context marker; it now returns the canonical path it
validated, and that is the only path ever opened. The lock is re-confirmed
against the same check while held, closing the gap between proving
eligibility and acting on it.

Declining is not fatal on this path: a busy root, a vanished directory or a
failed re-check falls back to a fresh Prepare, which costs session
continuity rather than correctness. ErrEnvRootBusy makes that distinguish-
able from a real I/O failure. The lexical isUnderWorkspacesRoot helper is
gone — it promised containment it could not deliver.

The canonical path deliberately stays internal. Reuse still receives
task.PriorWorkDir, so the workdir reported to the server and handed to the
next task keeps its existing shape.

Tests: negative cases for a symlink escaping the root, a plain outside path
and a managed-looking path without provenance, each asserting no .task_lock
appears outside — against the previous ordering the symlink case fails with
"prior-workdir guard wrote the lock outside workspaces root". A positive
case pins that a provenanced root IS locked, in the right directory, and
excludes a concurrent continuation. And a helper-process test pins that a
caller who holds the claim but forgets EnvRootPreclaimed fails immediately
and says so, instead of preparing while believing it is protected.

Refs #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): claim a prior env root by identity, not by name

Review found the remaining TOCTOU: the canonical path validation returns is
a string, not a handle. Between proving eligibility and opening the lock,
the validated env root can be renamed away and a symlink to somewhere
outside dropped in its place — an ordinary open follows it and creates
.task_lock out there, and no later re-check can undo a write that already
happened. A swap to a different but equally provenanced directory at the
same path is worse still: every name-based check agrees, and the daemon ends
up holding a lock on one directory while running in another.

Resolve the lock through an os.Root pinned at the workspaces root. Root
refuses any component that resolves outside its tree, so the lock file
cannot land outside no matter when the swap arrives — containment stops
being a check that races and becomes a property of the open.

Root still follows symlinks that stay inside the tree, so containment alone
cannot answer "is this the same directory?". Chain identity instead: stat
the directory validation approved, require the lock to have landed on that
same inode, and require the directory handed to Reuse to be it as well.
os.SameFile compares identity; comparing canonical path strings cannot tell
a directory apart from its replacement at the same name.

Reuse now receives the canonical path that was locked, so the object locked
and the object used are the same one. Two consequences that fell out:

- The workspaces root has to be resolved before measuring the env root
  against it, or a symlinked root (macOS /tmp, a home on a linked volume)
  makes them look unrelated and every reuse is refused.
- gateResumeToReusedWorkdir compared workdirs textually, so a canonical
  env.WorkDir silently dropped the prior session. It now compares directory
  identity, which is what it meant all along.

Tests use a deterministic hook to swap the directory between validation and
the lock rather than racing it. Against the previous code they fail with
"validated canonical root was retargeted and the lock was written outside"
and "accepted reuse after the validated directory was replaced at the same
path".

Refs #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): pin the workspaces root before validating, and lock from one handle

Three findings from review, all in how os.Root was being used rather than in
the choice of it.

Pin the workspaces root BEFORE validating anything. Opening it afterwards,
from a name validation had just approved, re-resolved that name: rename the
whole root aside, leave a symlink to a look-alike tree, and os.Root
faithfully pins the replacement. Root promises you cannot escape the tree it
opened — not that it opened the tree you meant. Holding the handle first
makes that ordering impossible.

Take the directory's identity and create its lock file from ONE sub-Root
pinned on the env root. Resolving the env root's relative path twice from
the workspaces Root — once to stat, once to create — allowed A on the first
resolution and B on the second, reporting A's identity while holding B's
lock.

Close the last window by detection rather than by claiming it is closed. A
file descriptor cannot cross into the preparation helper process, so Reuse
can only be handed a name, and the gap between the final identity check and
Reuse's own opens cannot be pinned away. The environment Reuse produces is
now checked back against the directory the lock is held on, so a
substitution ends the run in a fresh environment instead of executing in a
directory nothing holds. What remains uncovered is stated in the code: the
writes Reuse itself performs inside that window.

Also drop sameExistingDir's string fast path, which returned true without a
stat and contradicted the identity contract the function documents. Its
table test used synthetic paths that never existed; they are real
directories now, which is what the comparison was always about.

Tests, each verified to fail without its fix: a workspaces-root swap must
not let the lock be written into the replacement tree; reported identity
must be the directory the lock file is actually in; and a swap after the
claim, before Reuse, must end in a fresh environment rather than the
substitute.

Refs #7326

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: multica-agent <[email protected]>
2026-08-21 14:49:27 +08:00
55c7cf0575 fix(daemon): add the reference fact to the Mentions brief — @-as-attribution is not a mention need (MUL-6528) (#7379)
MUL-6417 replaced the prescriptive "Default: NO mention" rule with facts
that invalidate each false prior from human @-culture, but only covered
two of the three: notify-for-visibility and courtesy/thank-you. The
third prior — the @-form used merely to write someone's name — was left
standing, and an agent attributing a product decision to "@Steve Jobs"
in prose enqueued a run for the agent it was crediting.

Add the missing fact in the section's established style: crediting or
citing someone is prose about them, not work for them; the link form
dispatches whoever it names, so a reference stays plain text. Pin it in
TestInjectRuntimeConfigMentionLoopHardening alongside the other facts.

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-21 13:41:21 +08:00
Bohan Jiangandmultica-agent 3622db21cf MUL-6491 fix(daemon): give each task an exclusively claimed env root (#7347)
* fix(daemon): derive task env roots and branches from the full task id

Task ids are UUIDv7, whose leading 8 hex chars are the high 32 bits of a
48-bit millisecond timestamp: they only advance once every 2^16 ms
(~65.5s). Deriving the env-root segment from that prefix meant every task
created inside one such window landed on the same directory.

Prepare removes an existing env root before recreating it, guarded only by
the comment "task IDs are unique". That premise held for the id but not for
the truncation, so the second task's Prepare ran os.RemoveAll over a live
sibling's env root — taking its workdir (including a worktree with
uncommitted work), output/, logs/ and the 0700 multica-config/ with it.
Overwritten CLAUDE.md / AGENTS.md identity files were the visible symptom;
the deletion was the actual damage.

Use the whole id for the env root and for the agent/<name>/<task> branch
names, which truncated the same way and collided for concurrent tasks of
one agent. shortID stays for logs and display only. Prepare now derives its
root through PredictRootDir so the two can no longer drift apart.

Existing short-prefix directories need no migration: the GC enumerates task
dirs with ReadDir and reads .gc_meta.json, so it still reclaims them.

Fixes #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): take the task path segment from the id's random tail

The first attempt used the whole 32-char task id, which overflowed Windows
MAX_PATH: a branch name becomes a path under .git/refs/heads/ inside an
already-deep task checkout, and CI failed with

    cannot lock ref 'refs/heads/agent/windows-codex/<32 chars>':
    Filename too long

Length was never the fix. The bug was which end the segment came from: a
UUIDv7 leads with a 48-bit millisecond timestamp, so its first 8 hex chars
are the high 32 bits and only advance once every ~65.5s. Read from the tail
instead, where the id is random, and 12 chars are enough — 4 more than the
original segment rather than 24.

That trades a certainty for a probability, so make the destructive step
prove itself instead of assuming: Prepare stamps a .task_owner marker into
the env root and refuses to run os.RemoveAll over a root another task owns.
A rerun of the same task still resets its own directory. A task that fails
to start is recoverable; one that deletes a running sibling's uncommitted
work is not.

Two existing fixtures used synthetic ids differing only in the head and so
shared a tail. The guard caught them; they now differ where a real UUIDv7
does.

Fixes #7326

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): make the env-root claim atomic instead of check-then-delete

Review caught that the ownership guard did not cover the case it was added
for. It read .task_owner, then deleted, then wrote the marker — three steps,
so two tasks sharing a taskKey could both observe "no owner", and the slower
one would still os.RemoveAll the faster one's live directory. The guard only
held when a foreign marker was already durably in place, i.e. serially.

Replace it with a claim protocol built on two atomic filesystem primitives:
os.Mkdir fails if the directory exists, and O_EXCL fails if the marker
exists. Exactly one racing caller wins each, and a caller that wins neither
never reaches the destructive path.

The claim is then held for the rest of Prepare. A rerun clears the env
root's CONTENTS and leaves the marker in place rather than removing and
recreating the directory, so there is no window in which the root looks
unowned to a racing task.

A directory that holds files but names no owner now fails closed instead of
being deleted as abandoned. The marker is written before any content, so the
only unowned directory that is safe to adopt is an empty one — the residue
of a crash between Mkdir and the marker write, which would otherwise wedge
the task permanently.

Tests: a barrier-synchronised concurrent Prepare asserting exactly one task
starts and the winner's tree survives (fails against the previous sequence
with "directory not empty" / "invalid argument" — the deletion racing the
create), plus fail-closed and empty-adoption cases. repocache carried a
third copy of the task-segment rule with no test; it now has the same
contract test as the handler.

Fixes #7326

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: multica-agent <[email protected]>
2026-08-21 00:36:59 +08:00
VvVandweiweiwei ad2bdd3e38 MUL-6476 fix(execenv): expand $OPENCLAW_HOME in the openclaw active config path (#7310)
* fix(execenv): expand `$OPENCLAW_HOME` in the openclaw active config path

#6630 was the same bug in the tilde shape: `openclaw config file` prints a
path the daemon cannot stat, the miss is indistinguishable from a fresh
install, so prepareOpenclawConfig omits the `$include` and every task on
that host runs without the user's model providers and auth profiles. #6643
fixed `~\`. This is the other shape.

With OPENCLAW_HOME set, current releases print the variable name rather than
its value:

    $OPENCLAW_HOME\.openclaw\openclaw.json

Nothing expands it, and it is not absolute, so filepath.Abs joins it onto
the daemon's working directory:

    <daemon-cwd>/$OPENCLAW_HOME\.openclaw\openclaw.json

which can never exist. The user sees a task that starts and then behaves as
if they had never configured OpenClaw.

openclawHomeRest accepts `$OPENCLAW_HOME` and `${OPENCLAW_HOME}`, bare or
followed by either separator, keying on the character rather than
runtime.GOOS so the Windows form is exercised from the ordinary Linux and
macOS test jobs — the same trade openclawTildeRest documents. It is checked
before the tilde branch, and an empty OPENCLAW_HOME is an error rather than
a fall-through: resolving the literal variable name against the working
directory would hand back a confident absolute path to a file that cannot
exist, which is the failure this change is about.

Tests: the two path shapes, the empty-variable error, and an end-to-end
prepare guard on the reporter's banner-then-path output shape, mirroring
TestPrepareOpenclawConfigExpandsWindowsTilde. Each was mutation-checked by
disabling the new branch — the unit tests then report the path resolved
against the test's own directory, and the end-to-end one reports a wrapper
with no $include at all.

* fix(execenv): resolve a tilde-valued OPENCLAW_HOME, per review

The branch this PR adds joined the remainder onto the raw environment value, so
a documented OPENCLAW_HOME reproduced the very failure the PR exists to remove.

Upstream accepts a tilde-valued OPENCLAW_HOME — `docs/help/environment.md` at
`v2026.5.27` ("can also be set to a tilde path (e.g. `~/svc`), which gets
expanded using the same OS home fallback chain before use"), implemented in
`src/infra/home-dir.ts:41-47` — and expands it *before* computing the home that
`config file` then shortens. So on such a host the printed `$OPENCLAW_HOME`
stands for `<os-home>/svc`, and landing on the same file means resolving it the
same way. Measured before this commit:

    OPENCLAW_HOME=~/svc, input "$OPENCLAW_HOME\.openclaw\openclaw.json"
      -> "<daemon-cwd>/~/svc/.openclaw\openclaw.json"   err=nil

No error: filepath.Abs turns the embedded `~` into a confident absolute path,
the stat misses, and the wrapper goes out with no `$include` — silent
fresh-install, reached through the new branch.

The file also disagreed with itself: openclawFallbackConfigCandidates already
ran the value through expandOpenclawPath, so the fallback discovery route
resolved `OPENCLAW_HOME=~/svc` correctly while the new branch did not. Two
routes, same variable, different answers. They now agree — verified directly:
the fallback yields `<os-home>/svc/.openclaw/openclaw.json` and
openclawHomeFromEnv yields `<os-home>/svc`.

openclawHomeFromEnv expands only the tilde in the value, deliberately not the
variable form, so a self-referential value cannot resolve against itself.

Tests, both levels because a unit assertion alone would not have caught this —
the value's `~` survived into a path that *looks* absolute, so only following it
to the wrapper shows the `$include` going missing:

- unit: tilde value with either separator, bare `~` value, and the bare variable
  against a tilde value;
- `prepareOpenclawConfig`: `OPENCLAW_HOME=~/svc`, CLI printing
  `$OPENCLAW_HOME/...`, asserting `$include` and IncludeRoot land on
  `<os-home>/svc/.openclaw/openclaw.json`;
- a negative case (`$OPENCLAW_HOMEX/y`, `$OPENCLAW_HOME_EXTRA/y`,
  `${OPENCLAW_HOMEX}/y`, `$OPENCLAW/y`), which is what actually guards the risk
  section's claim that no path working today changes.

Mutation-checked by returning the raw value: the unit cases report the literal
`~` left in the path, and the prepare-level case reports `wrapper has no
$include`.

Also per review: both expansion errors now name the path with %q, not just the
variable, since the path is what makes a daemon log line actionable.

---------

Co-authored-by: weiweiwei <[email protected]>
2026-08-21 00:26:22 +08:00
3268d01172 fix(daemon): move the in_progress start write into workflow step 3 (MUL-6417 follow-up 2) (#7295)
* fix(daemon): move the in_progress start write into workflow step 3; define ancillary by output (MUL-6417 follow-up 2)

Field evidence from MUL-6460: a run that verifiably received the #7283
brief (its workdir CLAUDE.md carries the two-moment rule) walked steps
1→2→3 for over an hour and never issued a single status write. Two
compounding causes, both in the prompt:

- Placement. The start-moment rule lived in the status block BELOW the
  numbered steps. At the moment its condition triggers the model is
  executing the list, and a rule outside the list does not fire — the
  pre-MUL-6417 opening write was reliable precisely because it was an
  explicit step. The conditional write now opens step 3 itself, at the
  read→work boundary.
- The research example. "A todo issue you were asked to research stays
  todo" was written for consult pull-ins, but the MUL-6460 turn's work
  WAS research toward its own issue's ask — the example pattern-matched
  the exact case it was never meant to cover. Ancillary is now defined
  by output (the turn produced none of the issue's own deliverable),
  and research/design explicitly count as work when they are the ask.

Guard tests pin the step-3 placement and the research-counts-as-work
clause, and ban the retired example. Skill, source maps, and user docs
updated to match.

Co-authored-by: multica-agent <[email protected]>

* refactor(daemon): state the status rule as continuous, anchored at the moments that fire (MUL-6417)

Bohan's review of #7295: 'at the end of your work, write the state it
reached' still read as restricting writes to fixed checkpoints. The lead
now states the invariant — keep status true at every point in the turn,
write whenever the work changes it, mid-turn included (a blocker is
recorded when hit) — and the end of the turn becomes a verification
('do not exit with a stale value') instead of the write moment.

The anchors stay. A free-floating 'write when necessary' with no
attachment points is exactly the shape that produced zero writes in the
MUL-6460 incident: permission without a trigger moment does not fire.
Step 3 keeps the start write; the exit check keeps the guarantee that a
turn never ends with a lying board.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): drop activity-word skip-lists; ancillary is decided by output alone (MUL-6417)

Elon's #7295 review: 'review' still sat in step 3's skip clause and the
no-write bullet's example list, replaying the research incident's exact
failure class on an issue whose ask IS reviewing a PR. Activity words
carry no deliverable information in either direction, so both lists are
gone: step 3 names forms of work (code, research, a design, a plan, or a
review when reviewing is the ask), the no-write case is stated purely by
output (the turn produced none of THIS issue's deliverable), and the
rule now says so explicitly — the kind of activity never decides, only
whether the output is part of what the issue asks for.

Guards pin the review-as-work clause and the never-decides sentence, and
ban both retired skip-lists. Skill, source map, and docs synced.

Measured brief delta vs main (claude, production-length UUID): ordinary
13,362 → 13,971; leader 14,467 → 15,076 (+609 each, cached prefix);
per-turn messages unchanged.

Co-authored-by: multica-agent <[email protected]>

* refactor(daemon): adopt J's review — one criterion, anchors in steps, category-scoped skip (MUL-6417)

J's review of #7295, all four points taken:

- The positive form-list that replaced the banned skip-list was the same
  failure shape read as exhaustive (a triage or reproduce-the-bug turn
  finds itself in no list). Both directions of activity-word lists are
  gone; the never-decides sentence moves INTO step 3 — the position that
  fires — instead of the status block, the position this PR itself
  proved dead.
- The exit-side check is anchored inside step 5 ('Before exiting, ...'),
  making the PR's own placement argument self-consistent.
- The step-3 skip is scoped to the in_progress CATEGORY, so a custom
  status like Planning already counts as recorded once MUL-6460 puts the
  status catalog in front of agents — no rewording needed then.
- Tense: 'if any part of what this turn will produce ...' — step 3 is a
  prediction; mispredictions self-heal under the continuous rule.

Plus J's meta-point on guards: presence-pins cannot tell where a
sentence lives, and both field incidents were correct sentences in dead
positions — the anchors are now pinned positionally (must appear inside
the step-3 / step-5 lines), and the retired positive list joins the
banned set. Kept the questions/discussion/acknowledgements clause (J's
conservative option): acknowledgements are not covered by 'answered a
question' and the sentence is the MUL-6300-era invariant other tests
pin.

Measured (claude, production-length UUID): ordinary brief 13,685,
leader 14,790 — +243 vs main, down from +609 at the previous commit.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-20 16:09:32 +08:00
4ff37edf91 fix(daemon): record in_progress when work on the issue's ask starts, not only at turn end (MUL-6417 follow-up) (#7283)
Post-merge report from Bohan: a todo issue assigned to an agent sat in
todo for the whole first work turn — half an hour of active work the
board attributed to nobody. The end-of-turn-only rule conflated when the
agent can JUDGE with when the FACT changes: a turn that advances the
issue's own ask makes "being worked" true the moment it begins. The
activity indicator shows the run, but columns, filters, and sorting read
status — the indicator alone is not the surface people watch.

The status rule now has two write moments, same fact anchor:

- start: the moment the turn is known to advance the issue's own ask →
  in_progress (only if it differs — rework on an in_review issue flips
  it back the same way);
- end: the state the work reached (in_review / in_progress-continuing /
  blocked).

An ancillary turn (research, answers, review, discussion) still writes
nothing at either moment, so the research-stays-todo case and the
concurrent-convergence property from the original MUL-6417 change are
unchanged. This is the pre-MUL-6417 timing with the fact anchor's
conditionality — not a revert to the unconditional lifecycle flip.

Docs, skill reference, and source maps updated to the two-moment rule;
guard tests pin the start moment and ban the end-only phrasing.

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-20 14:17:18 +08:00
e1be1625cb MUL-5959: feat(agent): add Dim (DimCode) ACP runtime (#6675)
* feat(agent): add Dim (DimCode) ACP runtime

Add Dim (dimcode, the `dim` CLI) as a first-party agent runtime, driven
over the ACP (Agent Client Protocol) transport via `dim acp`.

Key integration points:
- New dim backend (pkg/agent/dim.go): spawns `dim acp`, performs the
  ACP initialize/session/new handshake, and raises the runtime's
  hardcoded read-only permission preset to full-access (plus agent mode)
  via session/set_config_option before the first prompt — without it every
  file write is denied by a capability rule. Model override uses
  session/set_model; the model catalog is read from session/new.
- Session resume is intentionally skipped: Dim binds sessions to the
  creating process, so a later process's session/load is rejected with
  "held by another process" even after a clean session/close. The backend
  always starts a fresh session and reports ResumeRejected so the daemon
  classifies the run correctly. A best-effort session/close keeps Dim's
  own session list free of orphaned entries.
- Registration: SupportedTypes whitelist, New() factory, launch header,
  daemon probe (MULTICA_DIM_PATH / MULTICA_DIM_MODEL), default agent
  command name, protocol_family CHECK migration (255), model discovery,
  MCP config support, metrics label, and runtime display.
- Docs/UI: provider logo, landing i18n (en/zh/ja/ko), providers and
  install-agent-runtime docs, README, CLI_AND_DAEMON, SELF_HOSTING.
- Tests: dim backend unit tests (fresh session + resume behavior), shared
  ACP deliverable case, logo and MCP-support tests.

* feat(views): use official DimCode app icon for Dim provider logo

Replace the placeholder inline SVG with the official DimCode desktop
client app icon (from /opt/DimAgent/resources/build/icon.png, resized
to 128px), imported as a static asset the same way the Qwen Code mark
is handled.

* test(agent): add real dim ACP smoke tests (agentintegration)

Two gated tests behind MULTICA_RUN_REAL_AGENT_SMOKE=1:

- TestDimRealACPSmoke: full end-to-end against real `dim acp` —
  initialize, session/new, set_config_option (permission/mode), prompt,
  and assert completed output.
- TestDimRealResumeRejected: pass a fake ResumeSessionID, assert the
  backend starts a fresh session (no session/load), and reports
  ResumeRejected=true so the daemon classifies the run correctly.

Verified against dimcode 0.3.2 and 0.3.8.

* fix: renumber dim migration 265 → 271 (upstream added 265-270)

* fix: renumber dim migration to 272 (upstream added 271)

* fix(agent): dim cross-run resume via session/load + review fixes

Address review feedback on the Dim ACP runtime:

- #1 Deliver runtime brief to Dim: add dim to the AGENTS.md provider
  list (verified dim 0.3.8+ reads AGENTS.md from the session cwd).
- #2 Cross-run session continuity: dim 0.3.10+ releases its per-process
  session lock ~5s after the owning process exits, so resume now goes
  through the standard ACP session/load (same as traecli/kiro/grok)
  instead of always starting fresh. A loaded session retains its
  permission/mode, so set_config_option runs only on fresh sessions.
  Add a two-run regression (TestDimRealCrossRunResume) proving run B
  recalls context established only in run A.
- #3 Process lifecycle races: the deferred cleanup now cancels the run
  context before cmd.Wait (a child ignoring stdin EOF no longer hangs
  Result delivery) with a bounded force-kill fallback; the success path
  waits for the final prompt notification with a grace window instead
  of a non-blocking read that could miss the last message.
- #4 Isolate model discovery by executable path (discoveryCacheKey).
- #6 Real smoke test now writes a sentinel file to prove full-access is
  effective; a best-effort session/close is sent before teardown.
- #7 gofmt.

* test(agent): add dim process-lifecycle regressions (review #3)

- TestDimCleanupKillsHangingChild: a child that ignores stdin EOF and
  SIGTERM after an early failure is force-killed within
  dimProcessWaitTimeout, so Result still closes.
- TestDimPromptMissingNotificationStillCompletes: when session/prompt
  returns without stopReason (onPromptDone never fires), the bounded
  final-notification wait falls through and Result completes instead of
  hanging.

* fix(migrations): renumber dim runtime_profile migration 272 → 273 (upstream added 272)

* fix(agent): review round 2 — process tree, quiescence, fail-closed, version check

Address all remaining blockers from the second review:

- #1 Require dim >= 0.3.10 (version check at initialize); bounded retry
  on session/load when the lock is not yet released instead of silently
  starting fresh; integration test no longer sleeps before resume.
- #2 Process-tree cleanup: configureProcessGroup + signalProcessGroup +
  waitProcessGroupGone; cmd.Cancel returns nil so we own all signalling;
  regression asserts the descendant PID is gone.
- #3 Notification quiescence: onActivity + waitForACPNotificationQuiescence
  (same as hermes); Dim equivalent of the late-final-notification test.
- #4 Permission fail-closed: set_config_option runs on BOTH fresh and
  resumed sessions; on config failure, session/close is sent before
  returning so a partially configured session is not resumed; regression.
- #5 Migration renumbered 273 → 274 (upstream added 273).
- #6 AGENTS.md mapping regression, two-executable cache isolation test,
  session/close unit assertion, smoke test now executes a command.
- #7 README.md + CLI_AND_DAEMON.md updated with 22 CLIs including Dim.

* chore: remove temporary review actions doc (not for PR)

* fix(migrations): renumber dim migration 274 → 310 (upstream added 274-309)

* review: fix retry break scope, dedup isACPSessionNotFound comment, update stale notes

* fix(agent): pass *exec.Cmd to signalProcessGroup/waitProcessGroupGone (upstream signature change)

* fix(agent): close session on set_model failure + resume regression test

Audit-found gaps from self-review:
- set_model failure now sends session/close before returning (same as
  set_config_option failure) — reviewer #4 said 'permission, mode, or
  model'.
- Add TestDimConfigFailThenResumeReestablishes: run A config fails →
  session/close sent → run B resumes and re-applies set_config_option
  (fail-closed), completing successfully.
- Fix two stale comments that contradicted the code (config block now
  runs on both fresh and resumed sessions).

* fix(agent): add WaitDelay, use labeled break in retry loop

Self-audit improvements:
- Add cmd.WaitDelay=10s for consistency with claude.go (hard backstop
  if a process somehow survives SIGKILL).
- Use labeled break (break loadRetry) so runCtx cancellation during the
  retry delay exits the for loop directly, not just the select.
- Update PR description: migration 273→310, set_config_option now
  re-applied on both fresh and resumed sessions.

* fix(migrations): renumber dim migration 310 → 313 (upstream added 310-312)

* fix(migrations): remove stale 313 dim migration (replaced by 314 after upstream added dsh at 313)

* fix: DSH compatibility + thinking levels + reviewer round 3

Systematic fix of all 39 items from the compatibility gap analysis:

Rebase + migration:
- Rebase to latest upstream/main (resolves all DSH conflicts)
- Migration 314_runtime_profile_add_dim (whitelist includes both dsh + dim)
- Remove stale 313 dim migration

DSH + Dim coexistence (provider lists, counts, docs):
- SupportedTypes, config.go, metrics labels: both dsh + dim
- i18n (4 files): count 23, lists include DSH + Dim + Oh-My-Pi
- README.md/README.zh.md: count 23
- CLI_AND_DAEMON.md: 23-row table
- environment-variables.mdx (4 langs): MULTICA_DIM_PATH/MODEL callout
- display.ts, mcp-support.ts, types/agent.ts, provider-logo.tsx: both dsh+dim

Thinking levels (was MISSING — dim supports thought_level):
- dim.go: call applyACPEffortOption after set_model
- thinking.go: add dim to acpCatalogThinkingProviders
- dim.go: retain sessionResult for effort option

Reviewer round 3:
- Version check fail-closed: empty/malformed → reject (not allow)
- Cache test through ListModels call site with fake executables
- set_model failure regression test
- Test companions: sidecar_manifest_test, runtime_config_test add dim

Code quality:
- agent.go: fix unreachable duplicate return (rebase artifact)
- dim.go: labeled break in retry loop, WaitDelay, session/close on set_model fail

* fix: deliverable test fake version + provider-logo rebase artifact

* fix(migrations): renumber dim migration 314 → 315 (upstream added 314_workspace_mcp_config)

* fix(migrations): renumber dim migration 315 → 319 (upstream added 315-318)

* fix: Windows process tree, MinVersions, retry tests, migration 327

Address all 5 remaining blockers from review round 4:

1. Windows process-tree ownership: use startOwnedProcessTree instead of
   cmd.Start(), releaseProcessGroup in cleanup defer. This attaches the
   child to a Job Object on Windows (no-op on Unix), ensuring descendants
   are captured and terminated.

2. Migration renumbered 319 → 327 (upstream added 319-326).

3. Add dim: 0.3.10 to MinVersions in version.go so the daemon registers
   old Dim binaries as offline and refuses triggers (defense in depth on
   top of the ACP agentInfo.version check in dim.go).

4. Session-lock retry contract tests: success after bounded retries,
   exhaustion without falling through to session/new. Fake script
   supports DIM_LOAD_HELD_N (held for N calls then succeed) and
   DIM_LOAD_HELD_ALWAYS (always held).

5. README.md:206 20→23 runtimes. PR description updated.

* test: add missing reviewer-requested regressions (round 4)

- Windows Job Object regression: dim_windows_test.go proves the Dim
  backend captures and terminates descendants via startOwnedProcessTree
  (Windows-only build tag; companion to TestStartOwnedProcessTree).
- MinVersions registration: add dim test cases to TestCheckMinVersion
  (0.3.10 ok, 0.3.9 rejected, invalid rejected).
- Retry cancellation: TestDimSessionLoadRetryCancelled cancels the
  context during the retry delay, asserts no session/new fallback.

* fix: sync upstream Command signature changes + restore dim additions

Upstream changed ListModels/discoverXxxModels/detectCLIVersion to accept
Command (struct with Path+Prefix) instead of string. The previous rebase
kept our old-signature versions, causing widespread compile failures.

Restored all affected files from upstream, then re-applied dim-specific
additions:
- agent.go: dim in SupportedTypes, New(), launchHeaders
- hermes.go: isACPHeldByProcess + -32002 in isACPSessionNotFound
- thinking.go: dim in acpCatalogThinkingProviders
- models.go: dim case in ListModels + discoverDimModels
- version.go: dim in MinVersions
- All dim test files preserved (dim_test.go, dim_integration_test.go,
  dim_windows_test.go, models_test.go dim cache test)

* fix: rebase to latest main, migration 327→341, resolve DetectVersion conflict

* fix: remove unused os/exec import in dim_windows_test.go

* fix(migrations): renumber dim migration 341 → 342 (upstream added 341)

* fix: use Command.exec instead of exec.CommandContext (upstream GH #7046)

Upstream's TestOnlyLaunchGoSpawnsRuntimeProcesses requires all backends
to build processes through Command.exec (launch.go), so a custom runtime's
fixed_args are carried into the subprocess. Dim was the only backend still
using exec.CommandContext directly.

* fix: launch prefix policy + remove empty test files + deterministic retry tests

Address all 4 findings from review round 5:

1. Add "dim": dimBlockedArgs to launchPrefixBlockedArgs so protocol-breaking
   flags (--help/--auth-setup/--remote) are filtered from fixed_args.
2. Remove 77 zero-byte *_test.go files accidentally added at repo root.
3. Make retry tests deterministic: TestDimSessionLoadRetryCancelled waits
   for the first session/load request before cancelling (no fixed sleep);
   TestDimSessionLoadRetryExhausted asserts exactly 4 load attempts.
4. PR description will be updated separately.

* fix: rebase to latest main, migration 342→343 (upstream added mcode at 342)

* chore: trigger CI

* chore: refresh PR

* fix: restore mcode that was lost during merge conflict resolution

Merge took 'ours' side which predated mcode. Restore mcode in:
- SupportedTypes, New() factory, launchHeaders
- agent_supported_types_test.go want map
- metrics/labels.go
- config.go defaultAgentCommandNames
- migration 343 up/down whitelists

* fix: restore mcode probe in agents_probe.go + agent-cli-command-names.txt

* fix: restore all remaining mcode references lost during merge

Files fixed:
- README.md: mcode row in runtimes table
- mcp-support.test.ts: mcode assertion
- config.go: mcode in Agents comment + error message
- runtime_config.go: mcode in AGENTS.md case
- version.go: mcode in MinVersions
- version_test.go: mcode test cases

Verified: no file has fewer mcode references than upstream.

* fix: restore mcode in environment-variables docs + CLI_AND_DAEMON ACP list

- environment-variables.{mdx,ja,ko,zh}: restored 'MiniMax Code' in the
  QwenPaw model-variable sentence
- CLI_AND_DAEMON.md: added MiniMax Code to ACP-family list + loadSession
  fallback description

Verified: every changed file now has >= mcode references vs upstream.

* fix(migrations): renumber dim migration 343 → 344 (upstream added 343)

* fix(migrations): renumber dim migration 344 → 348 (upstream added 344-347 plugin migrations)

* fix(migrations): update down migration comment 344 → 348

* chore: retrigger CI (flaky TestOpenclawDiscoveryCacheConcurrentPreparations — upstream test, passes locally x5)

* fix(migrations): renumber dim migration 348 → 352 (upstream added 348-351)

* fix: Dim launch-prefix regression test + version.go comment repair (review #6)

- Add TestDimLaunchPrefixFiltersBlockedFlags: proves allowed prefix
  reaches command before acp, and --help/--auth-setup/--remote/-h are
  stripped from Dim's launch prefix.
- Add dim to TestLaunchPrefixReachesACPFamilies family list.
- Repair version.go: dim's cross-run session/load comment was appended
  to mcode entry during a rebase conflict; restore two independent
  accurate comments.

* fix(migrations): update down migration comment 348 → 352

* chore: retrigger CI (backend-tests stuck 50+ min)

* fix(migrations): renumber dim migration 352 → 362 (upstream added 352-361)

* fix: use logAgentCommand for dim argv logging (upstream redaction requirement)

Upstream's TestOnlyLaunchGoLogsAgentCommandArgs enforces that all
runtime argv logging goes through Config.logAgentCommand so sensitive
args are redacted. dim.go was still using Logger.Info directly.

* fix(migrations): renumber dim migration to 370

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-20 12:54:46 +08:00
4f56785b02 refactor(daemon): merge Reply/Ownership turn modes into one fact-driven workflow (MUL-6417) (#7245)
* refactor(daemon): merge Reply/Ownership turn modes into one fact-driven workflow (MUL-6417)

The Reply/Ownership split dated from PR #205 and had already been merged
in substance by MUL-5377 (one brief section + mode router) and MUL-6300
(reply turns own the same status arc). What remained was a per-turn
marker plus two mode blocks restating information the per-turn message
already carries as data. This finishes the merge:

- Status is judged once, at the END of the turn, from what the work
  actually changed about the issue — not from the trigger type, not from
  the run lifecycle, and not gated on being the assignee. No opening
  in_progress write: the board's in-flight signal is the issue activity
  indicator, and a todo issue the agent was only asked to research now
  correctly stays todo (the old unconditional arc got that wrong twice).
  Lifecycle writes oscillate under concurrent runs; fact writes converge,
  which is what the retired assignee gate existed to protect.
- Delivery routes on data: a triggering comment in the per-turn message
  (reply in that thread with THIS turn's --parent, one reply per thread)
  or none (post a new top-level comment).
- The blocked rule and the squad-leader dispatch case become end states
  of the same judgment instead of mode-block special cases; the leader
  keeps one bullet (dispatching members is not delivery). The reply-mode
  mention pointer is gone — the discipline lives in ## Mentions.
- The Turn mode markers are removed from the per-turn prompts, deleting
  the marker/router-drift failure class (1ea3cf1d7) outright.

squad_briefing.go's Squad Operating Protocol text is deliberately
untouched: it does not reference the retired modes, and its guest-leader
prohibition is a squad-protocol product decision, not workflow routing.

Guard tests now pin the fact anchor: conversational turns write nothing,
research on a todo issue leaves it todo, assigned deliverables land in
in_review (stage barriers and parent notifications key off that write),
and concurrent agents converge instead of flapping the board.

Co-authored-by: multica-agent <[email protected]>

* test(handler): align squad parent-status contract test with the fact-judgment brief (MUL-6417)

Co-authored-by: multica-agent <[email protected]>

* refactor(daemon): replace the prescriptive mention default with the facts behind it (MUL-6417)

"Default: NO mention" told agents what to do without why. The mention
syntax hides its semantics — it reads like a free social gesture but is
a spawn/notify operation — and every real incident was an agent acting
on a false need: "they should know" (comments already reach followers;
completion wakes are platform-owned) or courtesy (a thank-you run whose
only reply is another thank-you run). The section now states those facts
plus the cost asymmetry (a missed mention is one follow-up ask; a stray
one is a paid run), from which the old default is derivable.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): scope the mention notify-fact to followers; sync docs to the new status contract; compress (MUL-6417)

Review fixes from #7245 (Elon):

- "A mention routes work — it is never how someone finds out" was false
  for non-followers — a mention is exactly how a human who does not
  follow the issue finds out, and the absolute wording could suppress
  necessary escalation. The notify-fact is now scoped to followers, and
  a guard pin bans the overreach alongside the old prescription.
- Every surface that still taught the old status contract is synced to
  end-of-turn fact judgment: issues.mdx/zh (agent flips in_progress on
  start), assigning-issues.mdx/zh (todo → in_progress → in_review as the
  default arc), and working-on-issues-source-map.md:177 (reply turns
  gated on assignee — the exact gate this PR removes).

Also a compression pass over the PR-touched brief text (−474 bytes):
drop the intro signpost sentence (steps and status block are
self-contained), tighten the delivery routing and delivery bullet, and
compress the concurrency rationale to one clause. Ordinary brief is now
13,181 bytes vs 13,345 on main (−164), leader 14,286 vs 15,131 (−845);
with the per-turn marker deletion (−139/−142 per turn) every prompt
surface is a net reduction from the first turn.

Co-authored-by: multica-agent <[email protected]>

* docs(squads): retire the grant-routing ledger and status-first dispatch ordering (MUL-6417)

Review nit from #7245 (Elon): squad_briefing.go's design comment still
described the reply-mode grant routing and assignee-scoped arc this PR
removed. It now records the current mechanics — the workflow judges
status at end of turn, the leader's brief-side special case is dispatch
leaves the parent in_progress, and this section's job is the
owning/guest permission boundary at the Agent Identity layer. squads.mdx
(en/zh) stops describing a status-write-then-dispatch ordering: the
status point is now an end-of-dispatch-turn fact, consistent with the
assigning-issues docs.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-20 11:32:17 +08:00
Wu Changming 7fdc854c26 fix(issues): copy durable local path for worktree tasks (MUL-6378) (#7176)
A worktree-mode local_directory task runs in a disposable git worktree that
Finalize removes on every exit path, so the task's `work_dir` pointed at a
directory that no longer existed. "Copy local workdir path" handed the user a
path they could not `cd` into.

The daemon now reports a `durable_work_dir` handoff instead of having clients
infer one:

- `removeLocalWorktreeDir` returns an error and confirms removal with `Lstat`,
  so a broken symlink cannot be mistaken for an absent directory. Finalize
  fails when removal cannot be confirmed.
- `durable_work_dir` is written only after Finalize succeeds and the worktree
  is verifiably gone. A preserved worktree, an in-place run, a running task, a
  squad-leader task, and any older daemon all leave it unset, keeping the real
  `work_dir` authoritative.
- The field travels on the complete, fail, and cancel-ack callbacks and is
  persisted on the task row (migration 362, additive nullable column). Writes
  use COALESCE for replay idempotency; the cancel-ack path CASes on
  `status = 'cancelled'` so a late ack cannot touch a completed or failed row.
- The server derives `relative_durable_work_dir` through the same
  home-stripping helper as `relative_work_dir`; the absolute value is reserved
  for explicit clipboard actions and is never rendered.
- Clients select the durable path only for a terminal task that carries the
  field. The issue actions menu and the transcript dialog share one resolver,
  and the label and toast say the task worktree was reclaimed, naming the
  delivery branch when one exists.

The stored path is a point-in-time delivery snapshot: later renames or
detachments of the project resource do not rewrite historical tasks.
2026-08-20 01:30:58 +08:00
eb2a94e860 MUL-6368: Prevent cross-agent task and workdir contamination (#7205)
* fix(daemon): isolate task identity and workdir reuse

Co-authored-by: multica-agent <[email protected]>

* test(llm): use validated retry override in contract

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): address task isolation review

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-19 15:30:19 +08:00
728ba9c58e fix(daemon): stop concurrent tasks evicting each other's OpenClaw discovery cache (#7204)
loadOpenclawDiscoveryCache rejected any entry stamped later than the reader's
clock sample, treating it as a clock jump. Callers sample time.Now() once and
pass it down, so on a daemon starting several tasks at once a peer routinely
commits a valid entry dated microseconds after the reader sampled — and the
reader, whose own store just succeeded, threw it away and re-ran discovery for
nothing. TestOpenclawDiscoveryCacheConcurrentPreparations flakes on CI for
exactly this reason; it reproduces locally in a few hundred runs.

Tolerate a bounded skew (1s) instead of any future dating at all. That is far
above the interleaving window and far below the clock jump the guard exists to
catch, and it bounds the cost of being wrong: an entry dated ahead outlives its
TTL by at most the tolerance.

TestOpenclawDiscoveryCacheFutureDatedEntry pins both edges — a concurrent
writer's entry is a hit, a jumped clock is still a miss — so the tolerance
cannot be widened into 'never expires' or narrowed back into the flake.

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-19 14:59:40 +08:00
Bohan Jiang 4d5a679b9b fix(openclaw): unblock the OpenClaw runtime on slow hosts (MUL-6321) (#7142)
Fixes #7112.

Task preparation ran `openclaw config file` and `config get agents.list --json` with a hardcoded 5s deadline; on a 2020 Intel MacBook Pro those take 8.4-10.9s and 4.3s every time, so the OpenClaw runtime was unusable there with no way to raise the limit.

- Deadline 5s -> 30s, overridable via MULTICA_OPENCLAW_CLI_TIMEOUT / backends.openclaw.cli_timeout, clamped to [1s, 60s] so the worst case (4 serial calls) stays inside the 5-minute preparation budget.
- Config discovery cached per daemon profile (on disk, since preparation runs in a one-shot helper process), invalidated by binary identity, OpenClaw path env, active config stat, and a 60s TTL. Only complete successes are cached; any cache fault degrades to a live CLI run.
- The timeout is classified structurally into a new platform-side, non-retryable reason (runtime_cli_timeout) instead of being text-matched into agent_error.provider_network, which showed "check your network" copy and auto-retried a deterministic local failure. Copy added for web/desktop/mobile; a NormalizeDaemonReason shim upgrades reports from older daemons.
2026-08-18 18:33:23 +08:00
4e10d6805a fix(execenv): handle OpenClaw JSON errors on stdout (#7133)
Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-18 16:05:27 +08:00
de902a4aab MUL-6273: feat(agent): add MiniMax Code ACP runtime (#7035)
* feat(agent): add MiniMax Code ACP runtime

* fix(agent): terminate mcode process trees

* fix(agent): address mcode review blockers

* test(agent): keep mcode model contract API-stable

* fix(migrations): resolve mcode prefix collision

* fix(agent): launch mcode through runtime command

Assisted-by: MiniMax Code

* fix(migrations): renumber mcode migration

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-18 12:44:27 +08:00
212ecfb8dd MUL-6300: fix(daemon): let reply turns own the status arc for their own issue (#7083)
* fix(daemon): let reply turns own the status arc for their own issue (MUL-6300)

A comment-triggered run was forbidden from touching issue status: "Do NOT
change the issue status unless the comment explicitly asks for it", written
in PR #205 (2026-03-31) on the day on_comment became the default trigger. It
was aimed at conversation — questions, thanks, agent-to-agent chatter should
not churn the board — but it also covered the most common real trigger, a
comment asking for rework on a delivered issue. The agent reworked the issue
with its status frozen, and a human had to move the card by hand (MUL-5165).

Reply mode now owns the same arc Ownership mode does — in_progress when the
work starts, the status the work is actually in when the turn completes — but
only for turns that carry work on an issue assigned to this agent. The two
properties the old prohibition really protected are kept and pinned by tests:

- a purely conversational turn never writes status;
- a run that is a guest on someone else's issue (@mention pull-in) never
  writes status, so an agent pulled in to answer a question cannot push
  another assignee's in-flight issue to in_review.

Squad leaders keep routing on the Squad Operating Protocol's "Own the parent
issue status" grant, which the server injects only when the issue is assigned
to that squad — so the guest-leader path (MUL-3724) stays closed, and the
grant no longer has to be phrased as an exception to a prohibition.

Also refreshes the two built-in skills that documented the old rule.

Supersedes #5781, whose one-line exception was written against brief text that
MUL-5377 has since rewritten.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): compress reply-mode status rule, cover unassigned issues (MUL-6300)

Review round on #7083. The ordinary reply-mode status bullet drops from
103 to 70 words and the squad-leader bullet from 110 to 92, with the
conversational-turn sentence now identical in both branches.

The no-write invariant broadens from 'assigned to someone else via
@mention' to 'not assigned to you': an @mention can also land an agent
on an UNASSIGNED issue (triage), which the old blanket prohibition
covered but the first draft of the positive rule left undefined.

Guard-test pins and the fallback pin in reply_instructions_test.go are
synced to the new wording; the arc-trigger substring is unchanged so its
two pins survive as-is. SKILL.md carries the same broadened phrasing.

Co-authored-by: multica-agent <[email protected]>

* docs(daemon): purge stale no-status-unless-asked semantics from ledger surfaces (MUL-6300)

Elon's review round on #7083: four surfaces still explained current
behavior with the pre-MUL-6300 rule. The squads source map (agent-
readable) now says the status-ownership grant, not the system comment's
ask, authorizes the leader's wrap-up write; prompt.go's turn-mode
comment, squad_briefing.go's grant rationale (which also still pointed
at the long-gone writeWorkflowComment), and the child-done stage test
comment now describe the conditional arc. Past-tense history quotes
(contract-test design note, MUL-6300 replacement note) stay verbatim.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-18 02:38:18 +08:00
8b1acfd19e fix(execenv): fold redundant metadata-list read into the issue-get step (#7016) (#7042)
Issue-triggered runs paid two reads for the same data: the runtime brief
mandated 'issue get' (whose JSON always carries the metadata bag) and then
a separate 'issue metadata list'. Fold the read guidance into step 1,
renumber shared steps 1-6 to 1-5, and update the brief tests to pin the
new wording and ban the retired standalone read step.

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-17 00:16:41 +08:00
Xichang(Seacen) Zhao cc2aea3878 MUL-6104: fix(daemon): tell the brief's reader not to merge stderr into parsed output (#6870)
Both brief builders now state that `--output json` writes JSON to stdout while confirmations and warnings go to stderr, and that merging them (`2>&1`) into anything that parses the output makes a successful write look failed and invites a duplicate retry.

Adds a regression test anchored on the rule's wording — premise, prohibition and consequence — asserted exactly once per rendered brief, so a reversed or duplicated rule fails the test.

234 bytes per rendered brief; a run renders one of the two builders.
2026-08-14 18:39:13 +08:00
19155e41f9 refactor(prompts): compress duplicate --no-start guidance from #6956 (MUL-6168) (#6971)
PR #6956 stated the same rule — use --no-start when the write only records
ownership/status of work already underway — five times across the always-
injected brief, the sibling-runs block, and the working-on-issues skill.
State it once per surface and keep the flag in the command signatures.
Prompt-text only; no behavior change.

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-14 17:52:04 +08:00
b5a48eca13 fix(agent tasks): prevent duplicate self-assignment work (MUL-6168) (#6956)
* fix(agent tasks): avoid duplicate self-assignment runs

Co-authored-by: multica-agent <[email protected]>

* fix(agent tasks): address duplicate-run review

Co-authored-by: multica-agent <[email protected]>

* fix(agent tasks): resolve sibling-run nits

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Sol-Boy <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-14 13:57:09 +08:00
ceb6c6845c MUL-6132 fix: stop stranding daemon task markers in user directories (#6917)
* fix(daemon): roll back local_directory sidecars when prepare fails (MUL-6132)

Prepare writes the daemon task marker and the rest of the sidecar tree into
the workdir early, but only persists the manifest that records them at the
very end. Every error return in between left that tree on disk with no record
of what to remove, and since the caller gets no Environment on those paths,
none of the teardown defers that normally undo it were ever registered.

For a local_directory task the workdir is the user's own repository, so the
leftover marker disabled every human-local multica command for that whole
directory tree — silently, and until someone deleted the file by hand. No
crash was needed to reach this state: a failed provider setup was enough, and
writeSidecarManifest failing was only a warning, so a disk or permission
hiccup produced the same permanent residue.

Roll back in place from the in-memory manifest whenever Prepare fails after
writing context files, and treat a manifest write failure as fatal in place so
that rollback runs while the record still exists. Worktree and cloud envs are
untouched: the former discards the whole worktree, the latter is wiped by GC.

Co-authored-by: multica-agent <[email protected]>

* fix(cli): retire stale daemon task markers instead of refusing forever (MUL-6132)

A daemon task marker left behind in a user's own directory made every
human-local command (daemon start/stop/restart/logs, login, logout, setup,
workspace switch, runtime profile set-path/unset-path) fail anywhere in that
directory tree, permanently and with a message that named neither the file nor
a way out. The reported instance sat undetected for five weeks.

Retire the marker automatically, but only on positive evidence that nothing is
running: every profile's daemon must answer and report zero active tasks.
Silence is not absence — an unreachable daemon is what a crashed one looks
like, and a task orphaned by that crash keeps running with this marker as its
only remaining guard, so any unreachable or unparseable profile keeps the
command refused. A minimum marker age closes the window where a daemon that
reports zero is claiming a task and about to write this very marker.

Two things stay out of scope by construction: markers without an agent and
issue id, which is the permanent node-wide guard at the workspaces root rather
than a task leftover, and any invocation carrying MULTICA_* task identity,
where the daemon really did launch this process and no file may override that.

When staleness cannot be proven the command still fails closed, but the error
now names the marker path, matching what newAPIClient has reported since
MUL-3922 and replacing a message that sent the user to the source.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): arm the in-place rollback before the first sidecar write (MUL-6132)

The rollback was registered after writeContextFiles returned, but that function
writes the daemon task marker as its very first act and can then fail on any
later step — .agent_context, skill files, project resources. Those failures
returned before the defer existed, so the case the fix was written for still
stranded a marker in the user's repository with nothing beside it.

Arm the defer immediately after the manifest is allocated, before any write.
Rolling back an empty manifest is a no-op, which is what makes arming it that
early safe.

Adds a regression test whose induced failure lands inside writeContextFiles
(a plain file where .agent_context must be a directory), one step after the
marker is written. It fails on the previous commit and passes here.

Co-authored-by: multica-agent <[email protected]>

* fix(cli): drop CLI-side marker deletion, keep the actionable message (MUL-6132)

The self-heal could delete the fail-closed guard of a running task. The daemon
increments active_task_count only after a claim returns, so a probe can read
zero for a task that is already claimed and about to write the marker at this
very path; the marker's age says nothing about a file written after the probe.
Serial probing across profiles widened the window further. Separately, the
"every profile answered" proof did not hold: profiles were matched by health
port, and that port is a hash that can collide, so one idle daemon could be
counted as two profiles while a crashed one kept an orphan task running.

Both are properties of doing this from outside the daemon. Removing a guard
needs synchronization with the claim path that only the daemon has, so
retirement moves there and the CLI keeps the half it can do soundly.

What remains is the message, now shared by both refusal paths. Previously only
newAPIClient named the marker file, so whether a user could act on the refusal
depended on which command they happened to run first; requireHumanLocalCommand
sent them to the source instead. Both now resolve the leftover through one
helper and report it identically.

Co-authored-by: multica-agent <[email protected]>

* fix(cli): report leftover markers on every refusal path, never the root marker (MUL-6132)

Two gaps from the previous round's review.

requireTaskLocalConfigRoot is the third path a leftover marker can refuse
through — config show, config set and auth status all call it — and it still
returned a message that named no file. Whether the error was actionable
depended on which command the user happened to run first, which is exactly what
unifying the other two paths was meant to end. It now appends the same suffix
when a marker is the only daemon signal.

The leftover helper also could not tell the two markers apart, because
daemonTaskContextMarkerPath matches on managed_by alone. Running from the
daemon workspaces root therefore described the permanent node-wide guard as a
leftover to delete — advice that closes the hole it exists to cover, aimed at
whoever reads the error, including an agent subprocess that lost its
environment. The helper now requires task identity, defined as agent_id OR
issue_id: a chat task has no issue, so requiring both would misfile its marker
as the root marker, while the root marker has neither field.

chdirWithDaemonTaskMarker was writing the bare managed_by form, which under
this rule models the root marker rather than the workdir marker its tests are
about; it now writes a task-scoped one.

Also corrects two comments the earlier commits left stale: cmd_agent.go still
described an automatic retirement that no longer exists, and
writeSidecarManifest still claimed every caller treats a write failure as
non-fatal, which stopped being true when the in-place path was made fatal.

Co-authored-by: multica-agent <[email protected]>

* docs(cli): correct the refusal-path count in leftover-marker comments (MUL-6132)

Both comments still said "both refusal paths" from when the suffix was shared by
newAPIClient and requireHumanLocalCommand only. requireTaskLocalConfigRoot
joined them in e02a393, so the count is three; list them by name so the next
addition has somewhere obvious to register.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-14 02:23:44 +08:00
Jiayuan Zhang 4f10a944b1 feat(runtime): add DeepSeek Harness support (#6923)
* feat(runtime): add DeepSeek Harness support

* docs(runtime): reflect public DSH release
2026-08-13 23:18:17 +08:00
85045228a1 MUL-6102: fix(daemon): surface which HERMES_HOME a Hermes task actually read (#6892)
* fix(daemon): surface which HERMES_HOME a Hermes task actually read

A Hermes task runs against a per-task HERMES_HOME overlay, seeded from a
source home the daemon resolves from its own process environment. When
that resolution lands on a home holding no config.yaml, the overlay is
built anyway from nothing: the derived config keeps only
skills.external_dirs, so the user's provider and credentials are gone and
Hermes refuses every session/new with "No LLM provider configured".

Nothing on that path said so. The overlay was seeded silently, no line
logged the resolved source home, and the failure surfaced Hermes' own
remedy -- run `hermes model` -- which edits whichever home the user's
shell points at, not the one the task read. GH #6872 is what that costs:
eight documented workarounds, none of which could have worked, and a root
cause filed against an unrelated resume bug.

Three additions, no behaviour change:

- Warn when the source home is missing, or exists without a config.yaml.
  Kept a warning rather than a hard failure because config-less is a
  legitimate setup: an image that ships Hermes and injects OPENAI_API_KEY
  through the environment resolves a provider fine.
- Log the resolved source home once per task, at Info.
- Append the overlay and source homes to a "no LLM provider configured"
  failure, so the task itself names the directory that was read.

The annotation runs after every classifier has read the error text. It
embeds two user-chosen paths and Classify matches substrings anywhere, so
annotating earlier would let a directory name pick the failure_reason --
a home under /srv/token-cache/limit/ satisfies rule 1 (context overflow),
which is evaluated before rule 2 (missing config) and feeds retry
eligibility and resume blacklisting.

The phrase rule 2 already matched is now a shared const so the new
predicate and the classifier cannot drift apart.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): keep the Hermes hint out of resume-guard input

Review caught that the annotation did not stop at the daemon. It travels
to the server as the task's error, is persisted in
agent_task_queue.error, and is re-scanned there for the life of the row
by service.ResumeUnsafeFailure and by the ILIKE/regex guards in
GetLastTaskSession / GetLastChatTaskSession.

Both interpolated paths are user-controlled -- HERMES_HOME comes from the
agent's custom_env, the overlay root from MULTICA_WORKSPACES_ROOT -- so a
legal directory name got a vote on session recovery. Measured, with a
source home under /srv/400-invalid_request_error/:

  raw error                  ResumeUnsafeFailure = false
  annotated with the paths   ResumeUnsafeFailure = true
  annotated with this hint   ResumeUnsafeFailure = false

That true is a healthy chat session pointer being cleared on a failure
that has nothing to do with it, so "no resume semantics change" was not
true as written.

The hint is now fixed prose with nothing interpolated, and names the
daemon log line that does carry the paths. This removes the vector rather
than containing it: no wire or schema change, and it is correct against
old servers too, so there is no mixed-version window where an un-upgraded
server misreads a new daemon's text.

Tests cover the boundary the previous ones missed: classification AND
service.ResumeUnsafeFailure agree with the unannotated text across five
real failure shapes, plus a check against the SQL guard phrases, which no
unit test can execute.

Also softens the missing-config warning, which asserted the task runs
without credentials when the environment may well supply them -- the
config-less-but-working setup this PR deliberately keeps supported.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-13 16:05:06 +08:00
c9727e6b2b feat(daemon): worktree mode for local_directory resources (MUL-5707) (#6759)
* feat(daemon): worktree mode for local_directory resources (MUL-5707)

Local directory resources serialise every task on a per-path mutex, so two
tasks on one folder queue behind each other. This adds an opt-in worktree
mode: each task gets its own git worktree of the user's repo inside the
daemon's env root, so tasks run concurrently and deliver their work as a
branch instead of editing the user's working copy.

Opt in per resource with execution_mode=worktree (default stays in_place,
so existing resources are unchanged). Requires a git repo with at least one
commit; a non-git directory fails with an actionable message rather than
silently falling back to serial execution.

Design points that make the mode safe to use:

- The agent starts from what the user sees, not HEAD. Tracked edits are
  captured with `git stash create` (which writes a commit object without
  touching the index, working tree, or stash list) and replayed into the
  worktree; untracked non-ignored files are copied, bounded at 2000 files /
  200MB with the skipped count logged at warn level.
- That replayed state is committed as a baseline, so "did this task change
  anything?" has an exact answer and `git diff <baseline>..<branch>` is
  precisely the agent's work.
- Nothing is silently discarded: leftovers are committed to the branch
  before the worktree is removed, including when the task fails partway.
- A task that changes nothing leaves no branch behind.
- Sidecars stay out of the branch by running the existing
  CleanupRuntimeConfig + CleanupSidecars pass over the worktree before
  finalizing. The .git/info/exclude approach repocache uses is not usable
  here: a linked worktree resolves info/exclude to the user's own common git
  dir, so it would change what `git status` hides in their checkout.
- Worktree-mode env roots do not get the local_directory GC exemption, so
  they age out normally instead of accumulating one env root per task.
- `git worktree prune` on create self-heals registrations orphaned by a
  crashed daemon.

Adds --execution-mode to `project resource add/update`, and updates the
docs and the projects-and-resources built-in skill.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): close data-loss and isolation gaps in worktree mode (MUL-5707)

Review follow-up on #6759. Six issues, all on failure or skew paths.

1. Preserve work when the final commit fails. Finalize logged a warning and
   then ran `git worktree remove --force`, destroying the agent's changes.
   commit.gpgSign with no key available to the daemon triggers this, and
   --no-verify does not disable signing. Finalize now returns an error and
   deliberately keeps the worktree — it stays registered, so `git worktree
   list` points at the work — and the daemon fails the task instead of
   reporting success with a branch that is missing the changes.

2. Fail closed on an unsupported execution_mode. Treating an unknown mode as
   in_place was wrong: execution_mode is how a user asks for ISOLATION, so
   the "safe" fallback would edit the working copy they asked us to stay out
   of. An unrecognised mode now fails the task naming the version skew.

3. Keep Codex conversations alive across turns. The per-issue session store
   was keyed on LocalWorkDir != "", so worktree tasks — which also never
   reuse an env root — got a fresh empty CODEX_HOME per turn and silently
   lost the thread. Covered by a two-turn regression test that fails without
   the fix.

4. Fail closed on an incomplete snapshot. A failed stash create/apply, a
   failed untracked copy, or hitting the copy bounds all degraded to "agent
   sees HEAD" with only a daemon log line. A half-replayed tree looks like a
   working checkout, so nothing downstream questions it while the agent reads
   different code than the user has. All of these now abort the prepare and
   tear the partial worktree back down.

5. Do not snapshot a directory mid-mutation. The same real path can be
   attached to another project as an in_place resource; snapshotting under a
   running in_place task captured a half-written tree plus that task's
   in-flight .agent_context/.multica sidecars, which then reached the branch
   and could feed the agent another issue's brief. Worktree prepare now takes
   the per-path mutex for the snapshot alone (released before the run, so
   tasks still overlap), and the untracked replay skips Multica's own
   sidecars.

6. Stop the test helper from masking regressions. gitRun skipped on any git
   failure, including post-finalize assertions, so a lost branch could report
   as a skip. Git availability is now checked once at repo setup; every later
   git failure is fatal.

Also rebased onto main, keeping both MulticaConfigRoot and LocalWorktree in
the Environment initialiser.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): close sidecar-commit and wait-visibility gaps in worktree mode; gate worktree saves on daemon version (MUL-5707)

- runTask: register the sidecar-cleanup defer immediately after the Finalize
  defer. Previously two early returns (temp-dir setup, StartTask failure) sat
  between them, and on those paths Finalize auto-committed the sidecars
  Prepare had just written — delivering a branch whose only content is
  Multica's own runtime files (in_place: leaving them in the user's tree).
- runTask: give the worktree snapshot wait the same plumbing as the in-place
  acquire — waiting_local_directory status, resourceWaitTasks accounting, and
  a cancellation poller. The holder can be an hours-long in_place task; the
  wait was invisible and a user cancel went unnoticed until the 5-minute
  prepare timeout.
- isMulticaSidecarPath: match sidecar dirs as whole path segments at any
  depth, not only at the repo root. An in_place resource pointed at a
  SUBDIRECTORY leaves its sidecars below that subdirectory; replaying them
  committed another issue's brief into the delivered branch.
- handler: refuse saving execution_mode=worktree while the owning daemon's
  registered cli_version is below MinLocalWorktreeCLIVersion (422,
  daemon_version_unsupported). An old daemon json-skips the field and runs
  tasks IN PLACE — the daemon-side unknown-mode refusal cannot protect a
  daemon that predates the field, so the server has to. Residual (documented):
  a daemon downgraded after the save needs a claim-time gate.
- copyUntrackedFiles: read the -z listing raw instead of TrimSpace-ing it,
  which corrupted filenames beginning/ending with whitespace into paths that
  silently vanished from the replay.
- docs + skill: describe the save-time version gate; drop the stale claim
  that old runtimes fail the task themselves.

Co-authored-by: multica-agent <[email protected]>

* feat(views): UI switch for local_directory execution mode (MUL-5707)

Worktree mode shipped CLI/API-only, which for its target user — someone
running several tasks at once from Desktop — means it does not exist. This
adds the switch to the resources panel.

The choice is framed by what the user gets back, not by the mode
identifiers: "Edit this folder directly" (one task at a time, changes land
in your working copy) vs "Run in parallel, isolated" (tasks run at the same
time and each hands back an agent/… branch). `in_place` / `worktree` stay
visible as a secondary hint for anyone cross-referencing the CLI or docs.

Two entry points, matching where the decision is actually made:

- The add-a-folder flow now asks for the mode after the folder is picked and
  validated, instead of creating the resource and leaving the mode to be
  discovered later.
- Every local_directory row has a mode control. It is deliberately NOT gated
  on being the owning machine — switching the mode only rewrites a field, so
  it works from the web app too, unlike rename or the folder picker.

Both blocked states are handled where the user chooses, not after they
commit:

- Non-git folder: the desktop validator now reports whether the path is
  inside a git working tree (walking up for `.git`, so a subdirectory of a
  repo counts), and the option is disabled with that reason. Unknown — an
  older desktop build, or an existing row — stays permissive; the daemon
  re-checks authoritatively.
- Daemon too old: the version floor is mirrored from the server as
  MIN_LOCAL_WORKTREE_CLI_VERSION and checked against the runtime for the
  resource's OWN daemon, not the machine the browser happens to be on. A
  server rejection is rendered inline in the dialog rather than as a toast,
  so the dialog stays actionable.

A "Parallel" badge on the row is always visible (not hover-only): without it
there is no way to tell whether tasks on a folder edit it directly or hand
back a branch, which is the first thing anyone asks when a task queues.

Also adds `execution_mode` to LocalDirectoryResourceRef — the field existed
server-side but had no TypeScript counterpart — and brings the zh/ja/ko
project-resources docs in line with the English ones, which were the only
locale updated when the mode landed.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon,handler): close worktree isolation and delivery gaps (MUL-5707)

Second review round. Five must-fix items, all on paths where the mode's
promises could still break.

1. A failed sidecar cleanup no longer ships Multica's own files as the
   user's branch. The cleanup errors were logged and Finalize then ran
   `git add -A`, so a permission/disk/lock failure could deliver a branch
   whose entire content was the runtime brief and issue context. Worktree
   mode now escalates a cleanup failure to an abort: nothing is committed,
   the worktree is kept for inspection, and the task fails with the
   preserved path. In place it stays a warning — no commit, no branch, and
   the leftovers are visible in the user's own tree.

2. The untracked replay no longer drops files silently. `Lstat` failures
   and symlinks were `continue`d without counting, so the caller read a
   partial snapshot as complete. Both now count as skipped, which the
   existing fail-closed check turns into a refused prepare. Non-content
   entries (sockets, FIFOs, devices) stay uncounted deliberately.

3. Prepare rolls back a worktree it created. Any later failure — context
   files, provider home, MCP config — returned without an Environment, so
   nothing downstream knew a worktree existed, leaving a registration and
   a branch no task ever ran in. A deferred Discard now runs unless Prepare
   reached its successful return.

4. The daemon-version gate moved to where it can actually hold. Save-time
   validation cannot see a machine downgraded afterwards, and an old daemon
   json-skips execution_mode entirely — it would run the task in place,
   editing the working copy the user asked to isolate. Claims are now
   checked against the runtime that is actually claiming, and a blocked
   task is cancelled with a reason rather than left to be redelivered to
   the same too-old runtime forever.

5. branch_name is delivered end to end. The daemon sent it, but
   TaskCompleteRequest had no field so it vanished at decode, and the
   failure path never sent it at all. It now has a column, travels on both
   terminal callbacks, and renders as a copyable row in Run details. The
   failure path matters most: worktree mode commits the agent's leftovers
   before tearing the worktree down, so a run that died partway still has
   work worth finding.

Docs (all four locales) and the projects-and-resources skill are updated
for the claim-time gate and the branch surface.

Co-authored-by: multica-agent <[email protected]>

* fix(handler,daemon): migration renumber, cancel reasons, branch on every terminal path (MUL-5707)

Third review round.

1. Rebased onto main and renumbered the migration to 285 — main had taken
   273 and is now at 284. sqlc regenerated on top of the rebased queries;
   the conflicts were confined to generated files.

2. The claim gate now persists why it cancelled. It called CancelTask,
   which writes only status='cancelled', and returned the reason as a 4xx
   that reaches the daemon's log and nothing else — batch claim drops the
   task from its response entirely. A run refused for a durable reason the
   user has to act on cannot present as a bare "cancelled", so this adds
   CancelAgentTaskWithReason and records error + failure_reason on the row.

3. branch_name now survives every terminal path, not just the two direct
   callbacks. Three were dropping it:
   - the context-exhausted complete→fail reroute did not copy it;
   - the daemon's complete→fail fallback (server rejected the complete,
     agent had succeeded) did not set it;
   - both cancellation paths discarded the result wholesale, even though
     the worktree is finalized — and its work committed — before the daemon
     learns of the cancel. The branch now rides the cancel-ack and is
     recorded by SetAgentTaskBranchName, which never overwrites a name a
     terminal callback already wrote.

4. Rollout/rollback compatibility. Isolation is enforced by two server-side
   gates, so a daemon downgraded at any point after the resource was saved
   is caught. The gap they cannot close is rolling the SERVER back past this
   change while sub-floor daemons are still connected: an old server has no
   gate and an old daemon ignores execution_mode. That constraint is now
   documented where an operator will meet it (the migration and the docs),
   and the version floor is pinned across server and frontend by test so the
   two gates cannot silently drift apart.

Co-authored-by: multica-agent <[email protected]>

* fix(server,views): route claim-gate cancels through TaskService, make cancel reasons visible, harden cancel-ack branch delivery (MUL-5707)

Closes the fourth-round review findings on worktree mode's cancellation
chain:

- Claim gate: cancel through a new TaskService.CancelTaskWithReason instead
  of a raw CancelAgentTaskWithReason query, so a gate-cancelled task gets the
  full cancellation side effects — audit capture, chat settle, agent status
  reconcile, task:cancelled broadcast, NotifyTaskFinished. Added REAL claim
  integration tests: singular claim (422 + row cancelled with reason), batch
  claim (task omitted + row cancelled with reason), and a current-runtime
  control.
- Cancel reasons are now user-visible: execution log rows, agent activity
  rows, and the transcript dialog label a SERVER-cancelled task (persisted
  error/failure_reason) like a failed one, with the actionable text on hover
  and a Reason row in Run details. User-initiated cancels stay a plain
  "Cancelled". New cancelReasonLabel helper + local_directory_error label;
  details_reason locale key in en/zh-Hans/ja/ko; widened
  AgentTask.failure_reason to the open string the wire actually carries.
- Cancel-ack is now a terminal delivery: the daemon retries it on transient
  errors (same schedule as complete/fail), the server fails LOUD (5xx) when
  persisting the branch/error fails instead of warn-and-200, and re-broadcasts
  task:cancelled after a successful write so clients that already refetched a
  branchless row pick up the delivery. Replays are idempotent (never
  overwrite).
- Cancel + Finalize-abort no longer swallows the preserved-worktree pointer:
  the finalize error is wrapped in worktreePreservedError (joined onto an
  existing run error, never displacing it), extracted on the cancel path, and
  delivered via the ack into agent_task_queue.error through the new
  SetAgentTaskErrorIfEmpty query — never overwriting a reason recorded by a
  fail callback or the claim gate. Other run errors on a cancelled run stay
  discarded as before: they are expected noise.
- Docs: the self-hosted rollback constraint callout now exists in zh/ja/ko,
  not just English.

Co-authored-by: multica-agent <[email protected]>

* fix(handler): guard cancel-ack writes to cancelled rows; requeue when the claim gate's cancel fails (MUL-5707)

Fifth-round review fixes:

- SetAgentTaskBranchName / SetAgentTaskErrorIfEmpty now carry a
  status='cancelled' CAS. The daemon acks on EVERY terminal status it
  observes, so a late or replayed ack from a stale run could previously
  backfill its branch or preserved-path error into a completed/failed row
  whose own callback — the authoritative channel — recorded nothing, without
  any event invalidating the change. A CAS-refused write is a deliberate
  no-op (still 200: nothing to retry), and the rebroadcast stays guarded by
  the same status check. Regression tests: a late ack against a completed row
  with empty fields and against a failed row leaves both untouched.
- When the worktree claim gate's CancelTaskWithReason fails, the claimed row
  no longer strands in dispatched (daemon refused, nothing to release it but
  stale reclaim). The gate requeues via RequeueTaskAfterClaimFailure — the
  next claim re-runs the gate and retries the cancel — and reports 5xx so the
  singular daemon reads a transient server problem, not a claim refusal; the
  batch path omits the task as before, now with the row requeued. Fault
  injection tests (row-scoped trigger raising on the cancel UPDATE while
  letting the requeue through) cover singular and batch.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-13 14:52:01 +08:00
28a7176328 MUL-6053: fix(daemon): give Hermes conversations a session that survives the task (#6845)
* fix(daemon): give Hermes conversations a session that survives the task

Hermes keeps every ACP session in `<HERMES_HOME>/state.db`. Because the
daemon takes over HERMES_HOME to inject bound skills, that database lived
inside the per-task overlay, so a conversation lasted exactly one task.

The failure was silent, which is what made it expensive. `session/resume`
against a database that does not hold the session does not fail: Hermes
creates a fresh session and answers with an ordinary success frame, and
ACP's ResumeSessionResponse has no `sessionId` field to contradict it. The
daemon therefore believed it had resumed, stored the same dead id again,
and every turn restarted from zero with nothing in the logs (GH #6806).

Three changes, in the order they matter:

- The backend now reads `_meta.hermes.sessionProvenance.acpSessionId`, the
  only place Hermes reports the session it actually served. A turn that
  landed on a different session continues under the new id and carries the
  existing ResumeContinuityNotice, so the agent can read the transcript
  back instead of pretending it remembers.

- `state.db` is linked to a per-conversation store at
  `<profile dir>/hermes-sessions/<agent>/<hermes profile>/<conversation>/`.
  Sharding per conversation is what makes this safe where #6693 left it out
  of scope: tasks of one conversation are serial, so a shard has a single
  writer, while two issues never share a database. SQLite resolves the link
  when deriving the WAL paths, so the journal sidecars live in the store and
  a task teardown cannot take the write-ahead log with it. Windows without
  symlink privileges keeps the database task-local rather than copying it.

- `gateResumeToReusedWorkdir` no longer treats a matching workdir as proof
  the session is reachable. The two keys came apart in the local_directory
  flow, where workdir reuse is disabled but envWorkDir still equals
  PriorWorkDir, so the gate forwarded an id that could never resolve.

Stores are GC'd on their own retention (`MULTICA_GC_HERMES_SESSION_TTL`,
default 14d, matching the Codex session store) and held against the GC for
the duration of a task.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): never destroy a Hermes session database on a failed mount

Review of #6845 found three ways the new session store could lose or
misreport a conversation. All three are on failure and reclaim paths that
the original tests did not reach.

- **The degradation path was destructive.** The mount migrated the
  task-local state.db into the store and deleted it, and only then tried
  to create the symlink. On a host that cannot symlink, that turned a
  conversation which previously survived via workdir reuse into an empty
  one — a regression on exactly the hosts the fallback exists to protect.
  The link is now created under a staging name first, and nothing
  destructive runs until it exists; a host that cannot link is left byte
  for byte as it was found.

- **The migration was not atomic.** It copied state.db and its journal
  sidecars straight into the store, so a failure after the main database
  landed left a store that looked migrated. The next attempt skipped the
  migration, deleted the source, and took the un-checkpointed tail of the
  conversation with it. It now stages the whole family and publishes with
  one rename, reusing the memory store's staging helpers (renamed to drop
  their `memory` prefix now that both stores share them).

- **"Mounted" was read as "resumable".** A store the GC reclaimed between
  turns, a switched Hermes profile, an operator's `rm`, or a dangling link
  from an older overlay all mount cleanly onto nothing, and the resume gate
  forwarded a dead session id into them — the same silent restart this
  change set out to fix. The mount now reports two separate facts, and the
  gate reads whether the store actually holds a transcript, not whether the
  plumbing succeeded. A zero-length database counts as no history.

Tests cover each path with injected failures rather than host-dependent
skips: a link failure preserves the database and its WAL and still mounts
once linking works again, a migration that dies between the database and
its WAL publishes nothing and loses nothing on retry, and a mounted-but-
empty store (fresh, reclaimed, dangling, zero-length) reports no history.
Verified non-vacuous — reverting each fix reproduces the reviewed symptom.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): make the Hermes session store agree with itself on "empty"

Review of the previous commit found a certain data-loss branch left between
the migration and its publish step. The two used different definitions of an
occupied store:

- the migration asks hermesStoreHasSessionDB — a zero-length state.db, or
  journal sidecars with no database, carry no transcript, so it proceeds;
- the shared promote asked hermesStorePopulated — any directory entry at
  all — so the same remnants read as "a competitor published first".

With a non-empty source and a zero-length state.db in the store, the staging
copy completed, os.Remove(storeDir) failed on the non-empty directory,
promote reported a lost race, the migration returned success, and the caller
deleted the source database and its un-checkpointed WAL. The link then
pointed at a database with nothing in it.

Occupancy is now the caller's predicate: the memory store keeps "any entry",
the session store passes its own "holds a real database". The session publish
clears the remnants it has already classified as nothing before the atomic
directory rename, and a store it cannot clear fails closed — the migration
returns the error and the source stays put — rather than passing for a lost
race.

The regression test drives the whole matrix through prepareHermesHome: a
zero-length database, orphan sidecars, a real database that must never be
overwritten, and an unclearable store that must fail closed with the source
intact. It fails on the previous commit with the reviewed symptom
(HistoryPresent=false after the source was deleted).

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): never delete a competitor's freshly published Hermes transcript

publishHermesSessionStaging decided the store held no history, then deleted
the state.db family by path name. Between those two steps a competing task
could publish its real transcript, and the stale decision would remove the
winner's database — after the winner had already reported success and
discarded its source.

The check, the remnant cleanup and the promote now hold one process-wide
mutex. In-process exclusion is the real thing here, not an approximation:
the daemon is the store tree's only writer (even the GC guard is in-memory
refcounts on the Daemon), so two publishers can only ever be two goroutines
of this process. A deterministic barrier test parks a publisher inside the
critical section and proves a competitor cannot enter the window.

The family cleanup also stops using RemoveAll: regular files and symlinks
are unlinked (never followed), while a directory or any other irregular
type under a state.db name is content this code cannot identify, so it
fails closed and the caller keeps its source.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: Steve Jobs (Multica Agent) <[email protected]>
2026-08-13 14:20:52 +08:00
8d292ef7ce MUL-5963: feat(server): let web chat read back history via multica chat history (#6680)
* feat(server): let web chat read back history via `multica chat history`

When an agent's provider session resume fails on a web chat / Feishu task, the
daemon injected SessionContinuityNoticeUnrecoverable, making the agent reply
"this is a new session, no memory". But the conversation was never lost — it is
persisted in chat_message, and the agent just had no command to read it back
(only Slack had a history reader).

Make `multica chat history` serve the stored chat_message transcript for any
non-Slack session (web chat, Feishu), reusing the existing task-token
authorization and the shared response shape. Route web chat / Feishu continuity
notices to a new variant that tells the agent to read the transcript back
instead of scripting a "new session" disclosure, and teach the Feishu channel
prompt the read-back command.

- handler/chat_history.go: GetChatChannelHistory falls back to chatMessageHistory
  (ListChatMessages, oldest-first, default recent 30) on ErrNoSlackSession.
- execenv: add SessionContinuityNoticeChatTranscript; keep Unrecoverable for
  channels Multica stores no transcript for (e.g. WeCom).
- prompt.go: route web chat / Feishu to the transcript notice; Feishu channel
  awareness teaches `multica chat history`.
- tests: update surface/notice matrix, Feishu prompt policy, add handler
  transcript fallback tests.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(server): fix transcript read-back test to insert a real assistant row

The insertChatVisibilityMessage helper hardcodes role='user', so the
"assistant reply" row in TestGetChatHistory_NoSlackBindingReadsStoredTranscript
was actually stored as a user message and the handler (correctly) returned
role "user". Add an insertChatMessageRole helper and use it for the assistant
row so the role-mapping assertion is meaningful.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(server): treat WeCom as a readable transcript surface for session continuity

WeCom is fully wired on main: it persists the conversation to chat_message and
stamps ChatChannelType="wecom", so `multica chat history` reads it back just
like Feishu's. Stop routing it to the Unrecoverable fallback; give it the
transcript notice and the `multica chat history` history command, symmetric
with Feishu (no thread reader, no upload).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(server): make transcript read-back reachable and honor the paging contract

Addresses review on the web-chat history read-back feature.

- GetChatChannelHistory no longer dead-ends on "no channel integration" when
  SlackHistory is nil: a no-Slack deployment (the exact target of this feature)
  now serves the stored chat_message transcript directly, and Slack-backed
  sessions still go through the Slack reader.
- chatMessageHistory swaps ListChatMessages for ListChatMessagesPage, honoring
  the ?before cursor (encoded as created_at|id) and clamping ?limit (default 30,
  max 50), and advertises NextCursor on a full page so an agent can page back
  without re-reading the recent window. Author now uses the channel vocabulary
  (Bot / User) instead of the raw role string.
- Adds a single SurfacePersistsTranscript predicate (web chat, Feishu, WeCom,
  DingTalk) as the one source of truth for "which surfaces are readable", shared
  by the continuity-notice router, the chat-prompt history copy, and the surface
  list — closing the DingTalk gap where the notice said "read it back" but the
  prompt said "no history reader for dingtalk".

Tests: nil-reader-with-rows regression, transcript paging without duplicates or
gaps, Author/TS pins, and DingTalk cases in the surface/notice and prompt tables.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(server): fix transcript paging test assertion

The paging test wrongly asserted messages are strictly oldest-first ACROSS
pages, but paging to older messages means each later page is older than the
previous one — the sequence is not monotonic. The handler was correct; the
assertion was wrong. Now it checks the real invariants: each page is
oldest-first, and the union of all pages is exactly the transcript with no
duplicates or gaps.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(server): stop telling transcript surfaces their history is not in Multica

The channel-awareness block opened with "This conversation and its history
live in <platform>, NOT in Multica" for every channel type, and the very
next line told a Feishu/WeCom/DingTalk agent that Multica stores the
conversation and hands it `multica chat history` to read it back. An agent
that believes the first sentence has no reason to run the command in the
second.

Only the useful half — do not go hunting through issues and comments — is
unconditional now. Where the conversation actually lives moved into each
branch: Slack keeps the original wording (true there), transcript surfaces
say the conversation happens on the platform and Multica stores a
transcript of it, and the defensive fallback keeps both claims for a
surface that really has no reader.

Co-authored-by: multica-agent <[email protected]>

* fix(server): name the channel a served transcript came from

HistoryPage.ChannelType is documented as empty ONLY for a session bound to
no channel, but the transcript branch never set it. A WeCom/Feishu/DingTalk
session that HAD messages therefore reported channel_type "" — telling the
agent it was in a web-only chat — while the same session's empty read
already named the platform. One endpoint, two answers, decided by whether
the session happened to have messages.

Reuses the existing sessionChannelType helper, so the transcript path
inherits its refusal to guess: a binding read that fails for any reason
other than "no such row" is reported rather than silently answered as
web-only. That failure now returns the same status as the empty-read path
does for the same cause, instead of the 502 reserved for a failed channel
read.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: qiushihao279-cloud <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-12 15:36:39 +08:00
Wu Changming 84dc02cd65 MUL-6034: fix(cursor): normalize MCP approval server shapes (#6776)
Cursor normalizes an MCP server config into a fixed field set and order before
hashing it into an approval key, so equivalent configs written in a different
field order produced keys Multica never matched, leaving the server unapproved.

Serialize stdio servers as {type?, command, args?, env?, cwd?} and remote
servers as {type?, url, headers?}, dropping unknown fields, and marshal without
Go's HTML escaping so the bytes match Cursor's JSON.stringify output.

Approval keys verified against cursor-agent 2026.08.04-aaa8809 and
2026.07.20-8cc9c0b via `mcp enable`; expected hashes in the tests are captured
from a real Cursor install.

Reported and fixed by @wuchangming.
2026-08-12 14:29:12 +08:00
Xichang(Seacen) Zhao b904e6b71c MUL-6029: docs(daemon): correct two comments #6604 made false, and enforce the Slack/Lark brief policy (#6771)
Three follow-ups to #6604: two comments the merged diff made false, and one policy the tests stated but did not enforce.

- `handler.go` said the brief turns `chat_channel_delivers_files` into upload-or-describe copy. After #6604 the per-turn prompt does, and the brief states no verdict at all — it is the prompt cache prefix, and a per-turn verdict there renders two briefs (MUL-5377).
- `outbound_media.go` cited `TestDeliverAttachments_AdmissionBoundsTheLookupStage` for a sentence about turns carrying no file; that test's turns all carry one. The paragraph now states both ways admission is held without a pending slot and cites the one the test drives.
- `TestBriefSurfaceDeliveryPolicy`'s `chat_slack` and `chat_feishu` rows denied two phrases where the WeCom rows deny four, so a denial worded around "does NOT apply" passed. Both rows now carry the same four.

Review follow-up (tests only): `TestBriefChannelDeliveryCopyIsPlatformNeutral` holds the same policy structurally — with the display name substituted out, every channel-backed brief must be byte-identical, so a per-platform position fails whatever wording it uses. Slack/Lark `mustHave` reaches parity with WeCom, `mustNot` failures quote the real match instead of a section it may not be in, and the admission test asserts `pending == 0` rather than implying it.

No behaviour change: two comments and test coverage.
2026-08-12 01:26:03 +08:00
Xichang(Seacen) Zhao 90eadd940a MUL-5905: feat(wecom): send the files an agent produced into the chat (#6604)
* feat(wecom): send the files an agent produced into the chat

An agent that produced a file and answered in WeCom delivered only the
sentence. `multica attachment upload` had already run, the object was in
storage, and CompleteTask had bound the row to the assistant message — but
nothing downstream of that bind knew how to reach a WeCom conversation, so
the file stopped there. The user read "here is the forecast" and got no
forecast, with no error anywhere to explain it.

Worse when the agent said nothing at all: an empty completion with a file
bound to it returned early, so the artifact was thrown away silently.

This adds the last hop. media_upload.go carries a file up the long
connection — WeCom has no REST endpoint for this, so it goes as
aibot_upload_media_init / _chunk / _finish over the same socket, and all
three read their verdict through the request() layer #6590 generalized.
outbound_media.go is the caller: after the answer is out, it reads the bound
attachment out of object storage, decides what to call it, and pushes it in
as its own message.

Three decisions worth naming.

The answer goes first and the file never blocks it. An upload is megabytes
and round trips and it can fail; delivery runs after the words are out, on
its own goroutine and a budget of its own, and its worst outcome is one
extra line saying a file did not make it.

A lost ack and a refusal are opposite failures. A chunk whose verdict never
came is offered once more — the protocol makes re-sending idempotent, and
losing one slice of a hundred must not cost the file. A chunk the server
refused is not, because the refusal is its answer and will be its answer
again. The push of the finished media follows the same rule in reverse: a
timeout is reported as-is rather than retried, because the same media_id
sent twice puts the file on the user's screen twice with nothing to undo.

WeCom validates bytes against the msgtype, so what to call a file is a
decision. A kind past its ceiling is demoted to a plain file rather than
sent and refused — a card the user can open beats a photo the server
rejected.

WithAttachments is what turns this on, and router.go passes it only when the
deployment configured object storage. Without it the adapter behaves exactly
as it did before.

* fix(daemon): stop telling a WeCom agent its conversation is text-only

The per-turn chat prompt and the runtime brief both decided file delivery by
asking "is there a channel at all". Any non-empty ChatChannelType got the
text-only paragraph: `attachment upload` does not apply here, describe the
file in words, never write its local path. That was true of every IM channel
when it was written, and it stopped being true for WeCom, whose adapter now
reads the bound attachment out of object storage and sends it into the room.

So an agent on WeCom was instructed not to use the one command that would
have delivered its file. The capability shipped and the agent was told it
did not exist.

The delivery question is per-adapter, not "is there a channel", and
ChannelCarriesFiles is where that answer now lives. Both call sites branch
three ways instead of two.

The new copy is deliberately built from main's existing web-chat branch
rather than written fresh. Both open on the same clause — "To include a file
or image you produced in your reply, run `multica attachment upload
<local-path>`" — and diverge exactly where the platforms diverge: web chat
says the file "appears as an attachment card below it" and offers a markdown
snippet to place it inline; WeCom says Multica "sends it into the WeCom
conversation as a separate message right after your text" and that "there is
no way to place it inline". That last clause is the one worth having. An
agent told only that files work here writes "see the chart below" and then
nothing appears below, because the long connection has no msg_item and a
picture cannot be embedded in the reply. Slack and Lark keep their existing
text-only wording untouched.

Two comments are rewritten rather than carried over, because they asserted
the binary the same commit falsifies — "keys off 'is there a channel at
all'" in prompt.go, and "any non-empty channel type means the reply leaves
Multica for an external IM platform, where `attachment upload` has nothing
to bind to" in the brief. A comment that contradicts the code beneath it is
worse than none.

ChannelCarriesFiles names every channel type this package knows rather than
leaving Slack and Lark to the default, so a fourth adapter surfaces here as
a decision to make. An unrecognized type answers false: the agent is told to
describe its file in words, and the worst case is a deliverable that could
have been sent was not. False the other way would have it promise a delivery
nothing performs.

* fix(wecom): stop claiming more certainty than the system has

Three review blockers, one shape: a promise made in one place that another
place cannot keep.

Capability came from the channel type. The daemon answered "this conversation
takes files" from `chat_channel_type == "wecom"`, but the last hop only exists
where the server wired object storage — so a WeCom deployment without storage
had its agents told to send files nothing would carry, and a new daemon on an
older server inferred a capability that build has no code for. The server now
answers it per turn on the claim (`chat_channel_delivers_files`), declared by
the same `if store != nil` branch that gives the adapter the storage, and
absent/false everywhere else.

Upload limits came from the framing. 50 MB is what 100 chunks of 512 KB can
describe; WeCom's own OpenClaw plugin puts the hard file ceiling at 20 MiB, so
that is now the cap, enforced against the attachment's recorded size before any
byte is read. Concurrency was a fixed 4 regardless of size; WeCom's own SDK
steps it down — all at once up to 4 chunks, 3 up to 10, 2 past that, because
their backend answers a burst of chunks on a large upload with a system error.

Failure handling had two words for three outcomes. A send whose ack never came
was reported as a definite failure although the file may well be in the chat,
and the local failures — a full pending queue, a slot wait that expired, a
lookup that errored — were reported to nobody at all. There are now three
states: delivered says nothing, definitely_failed keeps the definite wording,
and unknown gets wording that holds either way and is never resent, since a
duplicate file cannot be taken back. The attachment lookup moved ahead of the
rationing so a shed delivery knows there was a file to apologise for, and a turn
with nothing attached still says nothing.

* fix(wecom): bound the attachment lookup, and stop calling an attempted write a failure

Two gates, not one better place for one gate. The pending counter is claimed
after the lookup so a shed can name a real file, which is also why it cannot
bound the lookup: at the point it would have to be claimed, whether the turn
carries a file is exactly what is not yet known.

admitAttachmentDelivery is claimed before the spawn and bounds the goroutines
and the queries they run. Its cap is twice the pending cap, so a backlog meets
the honest post-lookup shed first and only reaches the silent one when the
system is already well past it. A refusal there is logged and not spoken —
telling a user their file was dropped on a turn that may have carried none is
the false alarm the post-lookup gate exists to prevent.

Separately, a WebSocket write error stopped being read as proof of
non-delivery. wsSender.write already distinguished the stages for tracing; it
now carries that out in the error. Past WriteMessage the frame may be at the
peer — a half-closed connection reports "broken pipe" to the writer for bytes
the reader has — so those classify as unknown and are never resent. What fails
before the write is provably local and stays definite.

Tests drive the real path rather than the counters: one blocks the lookup,
submits past the cap, and counts the goroutines and queries that actually
happen; one hands the frame to a connection that records it and then fails.
Both fail without the change. fakeObjectStore takes a lock, because it is no
longer only ever driven inline.

* docs(wecom): cite the size limits to WeCom's docs, not a third-party constant

The upload ceilings were sourced to Tencent's OpenClaw plugin. That file
carries the right numbers but cites nothing itself, so it corroborates rather
than establishes them. WeCom documents all four on aibot_upload_media_init's
body.total_size row, and repeats them on the classic media upload API. Point
at those.

* fix(wecom): drop the two media helpers #6605 brought in ahead of this branch

This branch carried its own cleanShort filename and extension helpers because
nothing else in the package had them when it was written. #6605 has since
merged, and it brings both — so the package now declares each twice and does
not compile against current main. GitHub still reported the branch mergeable
and CI was green, because both were measured against a main that predated that
merge by six hours.

Upstream's copies are the ones to keep: its cleanMediaFilename also strips
control characters out of a name, and its mediaExtension drops a charset
parameter before matching. Neither of those was in the copies here.

* fix(daemon): keep the file-delivery verdict out of the cached brief

chat_channel_delivers_files arrives on every claim and answers a deployment
question: does this server carry a file the last hop into the room. Upgrading a
server so it starts sending the field, or turning object storage on or off,
flips it under a chat session that is already running — and the brief branched
on it, so one resumed session rendered two different briefs. The brief is the
prompt-cache prefix (MUL-5377), which makes that a miss on every turn after the
flip. The two rows in the delivery test asserting different briefs for the two
verdicts were the exposure written down: they are what one session sees in
sequence.

The brief's channel-backed chat copy now names the platform and says the answer
is stated per turn. It holds on either verdict and contradicts neither. The
verdict has a home already — the per-turn chat prompt, whose branch was correct
and is untouched — and that message is emitted on every turn, so nothing is
lost by the brief declining to answer.

Slack and Lark take the same copy. Scoping it to WeCom would put a channel-type
decision back into the brief, which is what ChannelCarriesFiles exists to
prevent, and would hardcode a denial a server-side change can falsify.

Coverage moves rather than goes. TestBriefByteIdenticalAcrossRunsForEveryKind
gains a WeCom kind and a variant that flips the field; both fail without this
change, and the existing Slack kind fails on the variant too. The delivery
test's two WeCom rows assert the inverse property now — one brief for both
verdicts — and the upload/describe split they used to hold is pinned by
TestBuildChatPromptTwoLayerChannelPolicy on the per-turn prompt, which has
covered both branches all along.

* docs(wecom): correct what the admitted cap implies, and note that delivery cannot answer back

The comment on the two counters said reaching the admitted cap means the
pending cap is full and as many turns again are still in their lookup. It does
not. Admission is held for a goroutine's whole life, including turns whose
lookup finds no file and which therefore never claim a pending slot —
TestDeliverAttachments_AdmissionBoundsTheLookupStage fills admission with
pending at zero. The two-counter split and the ordering it buys are unchanged:
a backlog of file-carrying turns still meets the honest post-lookup shed first.

The package doc gains the fact that an agent cannot learn its delivery was
refused. `multica attachment upload` returns once the object is in storage and
bound to the reply, while the send into the room runs on EventChatDone, after
the run has ended, so everything the adapter knows about a failed delivery goes
to the person in the chat and to nobody else.
2026-08-11 19:01:34 +08:00
e0d0b38153 fix(daemon): keep the runtime owner's Reasonix deny rules in a task (MUL-6021) (#6764)
* fix(daemon): keep the runtime owner's Reasonix deny rules in a task

The per-task reasonix.toml denies the `ask` tool, but Reasonix resolves
the project file over the user config, so `deny = ["ask"]` replaced the
runtime owner's own deny list instead of extending it: an owner who had
denied `bash` globally got it back inside every Multica task.

The task config is now rendered from the owner's own [permissions] table
with `ask` merged into deny. The whole table is restated, not just deny,
so the policy survives whether Reasonix layers these files per key or per
table, and the table is read from the same REASONIX_HOME the child gets
(the agent's custom_env override, else the daemon's env, else the
default).

When that config cannot be read or restated faithfully — unreadable,
malformed, or a deny list that is not an array of strings — the daemon
writes no project config at all rather than one that would drop the
owner's rules. The task then runs with `ask` available, exactly as it
already does when a repository ships its own reasonix.toml.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): resolve the Reasonix user config the way Reasonix does

Restating the owner's permissions only helps if the daemon reads the file
the Reasonix child actually loads. The first cut assumed
$REASONIX_HOME/config.toml with a ~/.reasonix default, which misses:

  - Windows, where the home is %AppData%\reasonix (falling back to
    %USERPROFILE%\AppData\Roaming\reasonix), not %USERPROFILE%\.reasonix;
  - the legacy OS-support and XDG locations Reasonix reads when the
    primary config does not exist and REASONIX_HOME is unset;
  - an agent that sets REASONIX_HOME to empty, which sends the child to
    the platform default while the daemon kept reading its own.

Each miss reads "no owner permissions" and writes a task config holding
only deny = ["ask"] — the exact widening this change set exists to stop.

reasonix_user_config.go now ports Reasonix's own resolution (upstream
internal/config/paths.go): REASONIX_HOME with ${VAR} / ${VAR:-default}
expansion, ~ handling and absolute normalization, the per-platform home
defaults, and userConfigLoadPath's legacy fallbacks with the isolation
rule that switches them off once REASONIX_HOME is set. The lookup runs
against the sanitized custom_env layered over the daemon's environment —
the same env the child is launched with — so presence, not just value,
decides where to read.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-11 18:15:53 +08:00
8e96329196 refactor(daemon): drop the MULTICA_HERMES_TASK_MEMORY rollback switch (#6760)
The switch let an operator restore the pre-MUL-5932 behaviour of a fresh
task-local memories/ per task. Hermes agent memory migrated correctly, so
it no longer earns its keep — and it never covered the failure it looked
like it covered: the overlay already depends on directory links to mirror
the user's ~/.hermes, so a host that cannot create them fails at the
mirror step regardless of this env.

Flipping it was also lossy in both directions: with the switch on the
daemon stopped marking the store in-use and refreshing its mtime, so the
GC could reclaim the agent's memory after GCHermesMemoryTTL; flipping it
back discarded whatever the task-local dir had accumulated, because a
populated store is never migrated into.

The task-local path itself stays — it is still what a task with no agent
to key on, or an unresolvable Multica profile dir, gets.

Co-authored-by: J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-11 17:28:13 +08:00
807b8706bb MUL-5992 fix(daemon): deny the Reasonix ask tool per task (supersedes #6745) (#6746)
* Revert "fix(agent): keep Reasonix off the ask tool in unattended tasks (#6745)"

This reverts commit 8eaa0d229f.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): deny the Reasonix ask tool per task

`ask` puts a multiple-choice question to a human mid-turn. An unattended
task has no human, and Reasonix wires an asker for every ACP session, so
its own "no interactive user — decide for yourself" fallback is
unreachable: the daemon can only refuse the question, and Reasonix reads
a refusal as a dismissal and cancels the whole turn.

Write a project-scoped reasonix.toml into the task workdir that denies
the tool. Reasonix resolves config as flag > project reasonix.toml > user
config.toml, rooted at the session cwd, so this binds to the task and
leaves the runtime owner's interactive sessions alone. It also covers the
whole turn: deny rules are checked before the read-only allow
fallthrough, and the executor, the planner — which keeps `ask`
deliberately — and sub-agents all decide against the same policy. The
model gets "denied by permission policy" back as an ordinary tool result
and keeps working.

A reasonix.toml that came with the repository is left untouched, since
sidecar cleanup must stay a pure deletion of paths the daemon created;
that task keeps today's fail-closed question handling.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): stop excluding reasonix.toml from managed checkouts

The exclude was at the wrong layer and hid the wrong file. The daemon
writes reasonix.toml at the WorkDir, while a managed checkout is a
directory inside the WorkDir, and this list only reaches the checkout's
.git/info/exclude — so it could never hide the daemon's own copy. What it
did hide, for every provider, is a project config an agent legitimately
creates inside the repository: invisible in git status, impossible to
commit.

The sidecar needs no exclude. For a repo task it sits outside the
checkout entirely; for a local_directory task it is untracked in the
user's repo for the duration of the run and removed by CleanupSidecars,
which is how AGENTS.md and the other WorkDir sidecars already behave.

Also stop the deny-list comment implying that --workspace-only and the
ACP permission policy make the replaced global deny list equivalent —
they don't; it is an accepted widening.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-11 15:15:06 +08:00
a1da8e536f MUL-6000 fix(daemon): link user Codex skills into codex-home instead of copying them (#6742)
* fix(daemon): link user Codex skills into codex-home instead of copying them

Every Codex task got a full recursive copy of ~/.codex/skills/ inside its
per-task CODEX_HOME. For a user with npm-backed skills that is ~100 MB per
task directory, re-copied on every task start — hydrateCodexSkills wipes and
re-seeds on both the Prepare and the Reuse path — and never reclaimed: the GC
artifact sweep only matches node_modules / .next / .turbo, and whole-directory
reclaim needs the issue to reach a terminal status first. Total cost scales
with the number of live task directories.

Link instead. The same per-task home already links its other two shared
resources, sessions and the plugin cache, and a skill directory is read-only
input to the CLI, so the write isolation a copy incidentally bought has no
requester. EvalSymlinks still runs first, so an installer-shipped symlink
(lark-cli into ~/.agents/skills/) resolves to the real directory rather than
producing a link to a link.

The three paths that could reach through the new link are unchanged in
behavior: os.RemoveAll deletes a link and not its target, writeSkillFiles
probes with os.Lstat so a workspace skill colliding with a linked user skill
lands in a `-multica` sibling, and the GC refuses to walk into links. Tests
pin all three, plus a windows-tagged test for the junction form of the link.

Co-authored-by: multica-agent <[email protected]>

* fix(daemon): stop GC walks from descending into Windows directory junctions

The GC's artifact sweep and its size accounting both refuse to follow links
out of a task directory, but they tested for os.ModeSymlink alone. That misses
the link shape Windows actually produces: createDirLink falls back to a
directory junction (mklink /J) whenever os.Symlink is denied, which is the
default without Developer Mode, and since Go 1.23 os.Lstat reports a junction
as ModeDir|ModeIrregular with no ModeSymlink bit while its DirEntry still
answers IsDir() == true. filepath.WalkDir therefore descends straight into the
link target, and the sweep would delete a node_modules / .next / .turbo
directory that lives inside the user's real home.

Match both mode bits in all three walks. The task directory links user content
in three places today — the Codex session store, the plugin cache, and now the
user's skills — so this is reachable on any Windows host running Codex tasks.

Windows-tagged tests create the junction with mklink /J directly, so the
junction shape is covered even on a runner where symlinks are permitted, and
they run in the existing windows-execenv CI job.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Bohan-J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-11 13:51:50 +08:00