recoverInterruptedMergingTasks searched for landed commits by grepping
commit subjects for the task ID. Users with includeTaskIdInCommit=false
have commit subjects like `feat: ...` (no task ID), so if the merger
crashed after committing but before storing mergeDetails, recovery would
silently fail to find the commit and incorrectly retry the merge.
Three layered defenses:
1. Emit a Fusion-Task-Id: <id> trailer in every Fusion-managed merge
commit body. The 4 fallback commit invocations now include
`-m "Fusion-Task-Id: ..."`. After the AI agent commits, an
idempotent ensureTaskIdTrailerOnHead() amends the trailer in via
`git interpret-trailers` (no-op if already present).
2. findLandedTaskCommit now tries three sources in order:
a. task.mergeDetails.commitSha (if reachable from HEAD)
b. Fusion-Task-Id trailer grep (anchored regex)
c. Subject grep (legacy commits)
3. Trailer grep uses an anchored regex `^Fusion-Task-Id: <id>$` so
it doesn't false-match task IDs appearing as substrings.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two cases where mergeDetails.commitSha was wrong:
1. Empty-squash success paths (mergeAttempt + attemptWithSideStrategy
return true when nothing was staged) recorded pre-merge HEAD as the
task's commitSha. That commit had nothing to do with this task —
misleading the dashboard, audit log, and recovery scans.
2. pushAfterMerge can trigger an internal pull --rebase that rewrites
HEAD; mergeDetails was captured before push, so the stored sha
referenced a now-orphaned commit.
Fix:
- Track an empty-merge flag on AiInvocationTracker, set at the three
squashIsEmpty/staged===0 sites. Metadata block omits commitSha when
the flag is set.
- After successful pushAfterMerge, recapture HEAD and update
mergeDetails.commitSha if it changed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The pre-merge rebase had the local-base rebase nested inside the
remote-rebase success path, so when no remote resolved (or worktreePath
was missing), the entire block exited without running local-base. That
left smart-prefer-main exposed: with no rebase, the -X ours fallback
would silently re-introduce code main had recently deleted, which is
exactly the case the strategy is meant to prevent.
Restructure so remote rebase (Stage 1) and local-base rebase (Stage 2)
run as independent gates. Local-base rebase still picks up sibling-task
merges that landed locally even when the remote stage was skipped or
disabled, so prefer-main always gets at least one defense.
Also relax the semantic-incompatibility guard: prefer-main now requires
EITHER stage to remain enabled (was: required worktreeRebaseBeforeMerge).
Extracted runLocalBaseRebase() helper to remove duplication between the
two entry points (after Stage 1 vs. standalone) and centralize the
ancestor-check + abort handling.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two recovery scans operated on in-review tasks without checking
!task.paused:
- recoverMergedReviewTasks would move a paused task whose merge was
already confirmed to done, against user intent.
- recoverMisclassifiedFailures would clear the error on a paused failed
task, defeating the user's intent to investigate manually.
Add the paused guard to both, matching the pattern used by all other
recovery scans. Completes the pause-vs-stuck audit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Attempt 2 of the merge cascade caught any git merge --squash failure into
mergeExitedWithConflicts=true. If the failure was non-conflict (pre-commit
hook rejection, IO error, locked repo) and produced no U files, the code
fell into the "all conflicts auto-resolved" branch with empty classified
arrays, ran deterministic verification on pre-merge HEAD, and returned
true — recording merge metadata for a merge that never happened.
Distinguish "exit code 1 with U files" (recoverable) from "any other
failure" (real). When a real failure surfaces with no conflicts, raise a
sentinel MergeNonConflictError that the outer mergeAttempt catch propagates
without retrying — retrying just re-runs the same broken command.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
recoverInterruptedMergingTasks was the one self-healing scan that didn't
guard !task.paused. A user who paused a task mid-merge (status=merging,
column=in-review) would still see the recovery scan finalize or unblock
the merge once the stuck timeout elapsed, violating their pause intent.
The other 12 self-healing recovery scans either explicitly skip paused
tasks or operate on terminal/metadata-only state where pause is moot.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The smart-prefer-main strategy depends on a successful pre-merge rebase
to honor main's deletions. Previously, three failure modes silently fell
through to the -X ours merge, which would re-introduce code main had
just removed (because branch additions vs main deletions don't textually
conflict and -X ours only resolves content conflicts, not modify/delete).
- Hard-fail when prefer-main is paired with worktreeRebaseBeforeMerge=false
(semantically incoherent combination)
- Hard-fail when the pre-merge rebase starts and aborts (any of the three
rebase paths: remote, nested local-base, or fallback local-only)
- Warn (not throw) on environmental silent skips — no remote resolvable
or no worktreePath — so the gap is observable in logs without breaking
common test/setup environments
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The single "smart" strategy is now two flavors with the new default flipped
to prefer-main. Both share a pre-cascade `git fetch origin <currentBranch>`
+ best-effort fast-forward so a freshly-pushed sibling commit doesn't get
clobbered when the fallback resolves a conflict against a stale base.
- "smart-prefer-main" (new default): -X ours fallback. Protects just-merged
sibling work from being regressed by a concurrent task branch.
- "smart-prefer-branch": -X theirs fallback. Equivalent to legacy "smart".
Legacy "smart" / "prefer-main" enum values are accepted and normalized via
`normalizeMergeConflictStrategy()` so existing settings.json files migrate
seamlessly. The fast-forward step gracefully degrades on fetch failure or
divergent local main (logs and continues).
Updates settings UI dropdown, test helpers, and adds 5 fetch+ff regression
tests + 7 normalize-helper tests. Lint cleanup of two empty catch blocks
in scripts/release.mjs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
On a fresh install useAuthOnboarding's effect ran at mount before the
setup wizard's 500ms auto-open timer fired. The one-shot ref locked,
and the resolved fetch could either stack model onboarding on top of
the wizard or never re-trigger after the wizard closed.
- Gate the trigger on projectId being set so the wizard owns the
bootstrap phase; the auth check only fires once a project exists.
- Re-check setupWizardOpen via a ref when the auth fetch resolves to
avoid stacking onboarding on top of a wizard opened mid-fetch.
- Release the one-shot in that suppressed branch so the effect retries
when the wizard closes.
Adds two regression tests: fresh-install handoff and mid-fetch wizard
suppression.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related executor fixes:
1. Spawned child agents previously bypassed the executor model lane hierarchy
and used settings.defaultProvider/defaultModelId directly, ignoring
project-level executionProvider/executionModelId from .fusion/config.json.
Resolve via resolveExecutorModelPair() so children honor the same
precedence as the parent executor.
2. Pre-merge workflow step AI calls now have a wall-clock timeout
(settings.workflowStepTimeoutMs, default 6 min) and fall back to the
configured validatorFallback / fallback model on timeout. The 20-min
stuck-detector kill loop was the only escape hatch when a provider's
streaming API hung mid-response, and the kill triggered a same-provider
retry — guaranteeing repeat hangs. The runner now races the prompt against
a timeout; on timeout it disposes the session, logs a clear entry, and
re-runs the step once with a distinct fallback provider/model. If neither
completes (or no fallback is configured), the step returns a normal
failure that flows into the existing handleWorkflowStepFailure retry path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The prior commit re-enqueued tasks after stale-merge recovery but didn't
account for the engine's in-memory `mergeActive` set, which still held the
wedged task. `internalEnqueueMerge` silently no-ops when the entry is
present, so the re-enqueue had no effect.
The recovery callback now also aborts the active merge's signal and
disposes its session if the wedged attempt was the currently-active one.
This is what unsticks tasks where an AI provider call is hung mid-await
and the surrounding `try/finally` never gets a chance to run.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Stale-merge recovery now calls back into ProjectEngine's auto-merge queue
directly instead of waiting on the 15s polling sweep — wired via a new
InProcessRuntime.setMergeEnqueuer hook so SelfHealingManager can re-enqueue
without leaking engine internals.
createWorktree mirrors the merge-time rebase: when worktreeRebaseBeforeMerge
is enabled, the new task branch is rebased onto <remote>/<defaultBranch>
right after creation, so executors start from origin's tip with local main
replayed on top. Best-effort — fetch/rebase failures abort cleanly and
leave the merge-time rebase as the backstop.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Reset merge metadata, verification counters, and workflow results when tasks move from in-review/done back to in-progress
- Reopen verification-related steps (or the last step fallback) so re-verification runs from a pending state
- Add execute-time guard to clear stale mergeDetails on in-progress tasks before continuing
- Prevent resumeOrphaned fast-path recovery when completed in-progress tasks still carry merge metadata
- Add targeted executor and TaskForm tests covering FN-2883 regression paths
- Add webhook settings fields and defaults for enablement, URL, format, and event filtering
- Implement WebhookNotificationProvider with payload formatting support for generic, Slack, and Discord endpoints
- Extend NotificationService to manage both ntfy and webhook providers with live settings sync
- Export webhook notification types/providers through engine notification entry points
- Add notification service module with provider abstractions and ntfy provider implementation
- Refactor NtfyNotifier into a compatibility wrapper that delegates task-event delivery to NotificationService
- Initialize and stop NotificationService from ProjectEngine while preserving gridlock notifications via NtfyNotifier
- Export notification APIs from engine index and add focused unit coverage for provider, service, and project-engine wiring
Replace lazy `await import("./pi.js")` and `require("./pi.js")` calls in
runtime-resolution, agent-session-helpers, agent-heartbeat, and
cron-runner with top-level static imports. These dynamic imports were
documented as plugin-decoupling, but pi.js is already eagerly loaded
through index.ts re-exports and static imports in executor/merger/
reviewer/triage/mission-execution-loop, so the deferral never paid off
in practice.
The deferral did, however, introduce a TOCTOU race: a tsc rebuild that
momentarily emptied dist/pi.js would let the engine load fine and only
fail minutes later when the first session was created (e.g. FN-2860
errored two minutes into execution while pi.js was being rewritten).
With static imports, a missing/half-built dist now fails immediately at
process startup with a clear stack — verified by `mv dist/pi.js
dist/pi.js.bak` reproducing ERR_MODULE_NOT_FOUND on the first import of
runtime-resolution.js.
Also drops the DefaultPiRuntime.describeModelFn cache, which only
existed to paper over the require-on-first-call latency.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When a dependency task merges and its branch is deleted, self-healing nulls
the dependent task's baseBranch. Both resolveDiffBase (dashboard) and
resolveTaskDiffBaseRef (merger) defaulted to "main" in that case, widening
the diff range to merge-base(HEAD, main) and surfacing unrelated history —
e.g. FN-2855 reported 108 changed files instead of 16. Skip the merge-base
step when baseBranch is unset and a baseCommitSha is recorded; fall back to
"main" only for legacy tasks lacking both hints.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Add an effective node resolver with task override, project default, and local fallback precedence.
- Wire scheduler dispatch to persist effectiveNodeId/effectiveNodeSource and log resolved node routing.
- Add coverage for effective node resolution and scheduler node routing integration behavior.
- Stabilize workspace test resolution by adding @fusion/core and @fusion/plugin-sdk aliases across Vitest configs.
- Add ProjectEngine memory dreams wiring tests for startup ordering, settings-change resync, and unrelated-setting no-op behavior
- Cover degraded-mode startup and settings-update failure paths to ensure sync errors are logged without stopping the engine
- Extend MemoryView Dream Now tests for success, failure toast handling, and disabled loading-state behavior
Replace process.env.HOME fallbacks with os.homedir() in dashboard usage
probes and the hermes plugin profile resolver so unset HOME no longer
yields literal "~" paths. Skip POSIX process-group semantics on Windows
in engine/merger and dashboard-tui's pgrep-based vitest killer. Add
shell: true to npx spawns in CLI skills/extension so .cmd shims resolve
on Windows, and route test:build-exe through cross-env.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Hermes / OpenClaw plugin index.ts now re-export `probeHermesBinary` /
`probeOpenClawBinary` and their status types so the dashboard's
`runtime-provider-probes.ts` façade can import them via the public
package entry instead of deep paths.
- Dashboard `package.json` adds `@fusion-plugin-examples/hermes-runtime`,
`…/openclaw-runtime`, `…/paperclip-runtime` as workspace deps so
pnpm symlinks them into `packages/dashboard/node_modules/`. Without
these, the new probe imports failed with "Cannot find module" during
`pnpm typecheck`.
This clears 6 of the 9 outstanding typecheck errors. The remaining 3 are
in the in-flight Hermes plugin rewrite (runtime-adapter still imports
from a deleted `./pi-module.js`; the new `index.ts` calls a factory
with the wrong arg type) and should be resolved by the same change set
that landed the rewrite.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reviewer subprocesses were spawned via fn_review_spec / fn_review_step
even with globalPause on, because reviewer.ts had no pause awareness.
Stuck detector also kept running, treating pause-disposed sessions as
inactivity and re-queuing tasks. Pause-transition listeners only called
session.dispose(), which doesn't always interrupt an in-flight LLM
stream — letting reviewer spawns leak through after pause flipped.
- reviewer.ts: re-read settings, return UNAVAILABLE without spawning
when globalPause/enginePaused is on.
- stuck-task-detector.ts: skip checkStuckTasks() while paused.
- triage.ts / executor.ts: call session.abort() before dispose() in the
pause-transition listener to interrupt in-flight work.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Replace Hermes pi module integration with pi-ai session streaming and updated runtime adapter contracts
- Remove legacy engine guard scaffolding and add hermes-stream-client coverage for streaming behavior
- Rewrite plugin and engine e2e tests to align with the new runtime flow and regenerate dist artifacts
- Update Hermes runtime README and package metadata to document pi-ai execution expectations
When the worktree-recycle pool reassigned a path to a new task, the old
task's diff endpoints kept reading the new task's branch state — surfacing
unrelated commits as the original task's "files changed" list.
- Clear task.worktree/branch in the merger after the worktree is released
to the pool or removed, so the path no longer points anywhere.
- Validate the worktree's current branch matches task.branch in the three
worktree-backed diff endpoints; on mismatch return empty rather than
diffing against a foreign branch.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Add end-to-end Hermes runtime test covering PluginStore registration through PluginLoader and PluginRunner resolution
- Verify createResolvedAgentSession uses the Hermes runtime and delegates createFnAgent, promptWithFallback, and describeModel calls
- Add regression test ensuring AgentRuntime-shaped Hermes adapters are reused without compatibility wrapping
- Cover fallback behavior to default pi runtime when Hermes plugin is not installed
- Add engine shell utility to resolve the correct shell per platform
- Update routine runner to execute commands through shared shell selection
- Update cron runner to use the same cross-platform shell behavior
- Apply shared shell handling in dashboard routes for command execution
- Add shell utility tests covering platform-specific selection behavior
- Capture prompt/completion/total token usage from step-scoped sessions in the step session executor
- Persist per-step token usage in executor run context so stats survive across task execution
- Record single-session token usage totals alongside run context stats logging for consistent aggregation
- Expand executor and step-session executor tests to validate token usage persistence and fixture behavior
Capture per-session token usage from pi-coding-agent's getSessionStats()
after each promptWithFallback in the executor and merger paths, so
task.tokenUsage populates live during runs and reflects final totals on
done tasks. Previously the executor never read session usage and only
the heartbeat path bumped agent token totals, leaving task.tokenUsage
undefined even after completion.
Stats panel and done-card timing also now reflect live state: the modal
overlays the SSE-updated task prop on top of the one-shot fullDetail
snapshot, in-progress workflow steps contribute live elapsed to the
Workflow runtime metric, and the done card uses Timed duration (matching
the stats tab) with workflow runtime as fallback. Time indicator labels
coarsened to <1m / Nm / Nh / Nd.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Improve automation startup diagnostics and route handling for manual execution steps
- Add support for full manual automation step execution in dashboard and engine flows
- Expand due-schedule coverage in automation store and dashboard route tests
- Add cron runner regression tests for edge cases and document the automation execution fix via changeset
- Fix triage planning model resolution to fall back through project/global planning settings and default overrides
- Fix reviewer model selection to honor validator-specific settings before default provider/model overrides
- Update merger model resolution to apply default override fallback and align shared task setting types/executor flow
- Add regression coverage for triage, reviewer, and merger fallback behavior and update settings hierarchy documentation
- Skip timer-triggered heartbeat ticks when the target agent is paused
- Add executeHeartbeat pause checks so paused agents do not start task work
- Expand agent-heartbeat tests to cover pause guards across scheduler and execution paths
- Document paused-agent heartbeat behavior in docs and add a patch changeset for @runfusion/fusion
- Add isGitRepository utility in worktree-pool using git rev-parse checks
- Fail fast in TaskExecutor with actionable non-git errors before worktree creation starts
- Classify not-a-git-repository worktree add failures as non-retryable in recovery flows
- Warn from in-process runtime startup when the working directory is not a Git repository
- Expand executor and worktree-pool tests to cover non-git, missing-dir, and conflict-classification paths
- Render a compact token usage indicator in TaskCard footer with accessible labeling and token-aware styling
- Track token usage fields in the TaskCard memo comparator and expose a comparator test helper for regression coverage
- Add TaskCard tests for token usage rendering behavior and comparator invalidation on token usage updates
- Configure runtime plugin Vitest setups with an @fusion/engine source alias for reliable workspace test resolution
- Keep restart integration child_process spawn mocking aligned with execSync-driven merge verification behavior
Three fixes for the worktree-overflow / stuck-task incident:
1. Cap deterministic-verification-failure bounces (fix#2)
Auto-merge previously bounced an in-review task back to in-progress
on every verification failure with no upper bound. A single flaky test
could keep a task ping-ponging in-review→in-progress forever, holding
its worktree and consuming agent slots. Adds verificationFailureCount
on Task (DB migration v48), increments on each bounce, and after 3
failures marks the task failed and creates a follow-up triage task
so a fresh agent can investigate the underlying flake instead of
re-running the same fix loop.
2. Reap unregistered orphan worktree dirs even when recycle is on (fix#3)
cleanupOrphans previously bailed out entirely when recycleWorktrees
was true, leaving stale dirs (clear-hawk-broken, *-bak, leftover
crash debris) on disk forever. New reapUnregisteredOrphans pass
removes only directories that aren't registered git worktrees, so
the recycle pool keeps its warm worktrees but the trash gets cleared.
3. Idempotence guard on activity-log listener wiring (fix#6)
setupActivityLogListeners() was registering handlers on every call.
When init() ran twice, every task:created / task:moved event wrote
N rows to activityLog, producing the duplicate entries visible in
the DB. Added activityListenersWired flag so repeated calls no-op.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
47514942 switched merger verification from exec to spawn-based
execWithProcessGroup, but restart.integration.test.ts only mocked
execSync/exec. spawn() returned undefined, so the merger crashed before
running the test command and any in-review merge test that hit the
verification path failed with VerificationError.
Adds a spawn mock that funnels through the existing execSync mock so a
single mockedExecSync.mockImplementation continues to control both git
calls and verification command outcomes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hitting Stop (globalPause) disposed the AI merge agent session but left
the spawned `pnpm test` / `pnpm build` child processes running until
they finished naturally. With recurring flaky-test loops at Step 5,
that meant Stop had no visible effect — new test runs kept piling up
across multiple worktrees.
Two gaps:
- project-engine.ts onGlobalPause never called mergeAbortController.abort(),
so subsequent verification commands (gated by the signal) weren't cancelled.
- merger.ts execWithProcessGroup only listened to its own internal
timeout — passing an AbortSignal had no effect on the in-flight
child process group.
Fix: abort the controller on global pause, and have execWithProcessGroup
SIGTERM/SIGKILL the detached process group when its signal aborts.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Manual version bump to 0.5.0 (changeset version produced 1.0.0 from a
single minor changeset against 0.4.1; that release was rolled back and
the 1.0.0 npm version deprecated).
Aggregates: status terminology refresh (planning/replan), Reviewer
rename, in-review pause behavior, dashboard-tui resize hardening,
dev-server experimental toggle fix, version reporting fix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>