Commit Graph

3071 Commits

Author SHA1 Message Date
Fusion
0bed997af8 feat: surface runtime-resolution fallback in dashboard, thread real FallbackReason
Fixes silent runtime fallback visibility (dashboard never read wasConfigured
or session:runtime-resolved) and threads the real FallbackReason
(not_found vs factory_error) through resolveRuntime()/logRuntimeFallback
instead of hardcoding "not_found" for every fallback.

- packages/engine/src/runtime-resolution.ts: resolvePluginRuntime() now
  returns a tagged miss result distinguishing not_found from factory_error;
  resolveRuntime() threads the real reason through and returns it as
  ResolvedRuntime.fallbackReason
- packages/engine/src/agent-session-helpers.ts: includes fallbackReason in
  the session:runtime-resolved audit event metadata
- packages/dashboard/src/routes/register-task-workflow-routes.ts: new
  GET /api/tasks/:id/runtime-fallback endpoint
- packages/dashboard/app/hooks/useRuntimeFallbackStatus.ts +
  packages/dashboard/app/components/RuntimeFallbackBadge.tsx: new polling
  hook + badge/toast component wired into TaskCard, ActiveAgentsPanel, and
  AgentsView

Ref: Fusion task FUX-022, investigations/FUX-017-hermes-runtime-fallback.md
recommendation #1
2026-07-08 03:09:29 -04:00
gsxdsm
9e5c025113 FN-7608: block executors on pending approvals instead of allowing workarounds
Executors could previously treat a pending approval as a normal turn end and go hunt for ungated workarounds instead of stopping. This change makes wait-for-approval a hard suspend point.

- wait-for-approval now suspends the in-flight executor session via awaitAbortInFlightTaskWork
- Dedupe identical pending approvals so repeated waits don't pile up
- Executor prompts now carve out awaiting-approval as a legitimate turn end (agent-prompts.ts)
- Extend provisioning-gate and agent-action-gate coverage for the new suspend/carveout behavior
- Add changeset (patch) documenting the fix for release notes
- Update docs/agents.md and docs/architecture.md to describe the new blocking behavior

Files changed:
 .changeset/fn-7608-awaiting-approval-blocking.md   |   7 ++
 docs/agents.md                                     |   1 +
 docs/architecture.md                               |   1 +
 packages/core/src/agent-prompts.ts                 |   5 +
 .../engine/src/__tests__/agent-action-gate.test.ts |  82 +++++++++++++
 .../executor-approval-gate-suspend.test.ts         | 128 +++++++++++++++++++++
 .../executor-approval-prompt-carveout.test.ts      |  61 ++++++++++
 packages/engine/src/agent-heartbeat.ts             |  13 +++
 packages/engine/src/executor.ts                    |  28 +++++
 packages/engine/src/pi.ts                          |  22 +++-
 .../sandbox/__tests__/provisioning-gate.test.ts    |  29 +++++
 packages/engine/src/sandbox/provisioning-gate.ts   |  11 ++
 12 files changed, 384 insertions(+), 4 deletions(-)

Fusion-Task-Id: FN-7608

Fusion-Task-Lineage: 9e42d8ee-bda7-4ef1-b159-46c2100bbc48

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-06 19:03:07 -07:00
gsxdsm
203f879c8f FN-7611: respect workflow intake column on task creation
Task creation surfaces stopped hardcoding column:"triage", so new tasks now land in the selected-or-default workflow's resolved intake column instead of always jumping to Planning/triage.

- Removed hardcoded column:"triage" override in engine's createTaskCreateTool (fn_task_create), letting TaskStore.createTask resolve the landing column from the workflow's intake-trait column.
- Removed the equivalent hardcoded override in the pi extension's fn_task_create, and updated its response text to echo the actual landing column instead of a fixed "Column: triage" string.
- Fixed signal-route, GitHub-import, and planning-subtask-route task creation to stop forcing column when no workflowId is given (or, for planning subtask routes, even when one is provided).
- Custom workflows with a non-triage intake column (e.g. Inbox) now correctly capture new cards inert until released, while the default builtin:coding workflow still resolves to "triage" byte-identically.
- Added regression coverage (agent-tools-intake-column.test.ts, extension-workflow-tools.test.ts) and a patch changeset documenting the fix.

Files changed:
 .changeset/fn-7611-intake-column.md                |   7 ++
 .../src/__tests__/extension-workflow-tools.test.ts |  70 +++++++++++
 packages/cli/src/extension.ts                      |  10 +-
 .../src/__tests__/register-signal-routes.test.ts   |   8 +-
 .../dashboard/src/__tests__/routes-github.test.ts  |   2 -
 .../dashboard/src/routes/register-git-github.ts    |  16 ++-
 .../src/routes/register-planning-subtask-routes.ts |  24 +++-
 .../dashboard/src/routes/register-signal-routes.ts |   8 +-
 .../__tests__/agent-tools-intake-column.test.ts    | 138 +++++++++++++++++++++
 packages/engine/src/__tests__/agent-tools.test.ts  |   1 -
 packages/engine/src/agent-tools.ts                 |  21 +++-
 11 files changed, 288 insertions(+), 17 deletions(-)

Fusion-Task-Id: FN-7611

Fusion-Task-Lineage: daf7f755-b1c7-4859-b74f-f15593d5e79e

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-06 19:03:07 -07:00
gsxdsm
44442622c5 FN-7609: show gated action payload details on approval requests
Approval cards previously showed only a generic gating message with no visibility into the underlying command/arguments being approved, and repeated pending requests for the same action could pile up as duplicates.

- Add GatedActionApprovalDetails component to render the gated command/arguments payload on agent-gating approval cards in MailboxView
- Persist approvalDedupeKey in targetAction.context and a payload-bearing summary via buildAgentGatedActionSummary in permanent-agent-gating
- Wire agent-heartbeat, executor, and pi to pass through the richer gated-action context/summary
- Add changeset (patch) documenting the fix
- Update docs/dashboard-guide.md
- Add/extend tests: GatedActionApprovalDetails, MailboxView, permanent-agent-gating, pi-create-fn-agent

Files changed:
 .changeset/FN-7609-gated-action-approval-payload.md            |  7 ++
 docs/dashboard-guide.md                                        |  1 +
 packages/core/src/types.ts                                     |  8 +++
 .../app/components/GatedActionApprovalDetails.css              | 50 ++++++++++++++
 .../app/components/GatedActionApprovalDetails.tsx              | 72 +++++++++++++++++++
 packages/dashboard/app/components/MailboxView.tsx               | 12 ++++
 .../__tests__/GatedActionApprovalDetails.test.tsx               | 66 ++++++++++++++++++
 .../app/components/__tests__/MailboxView.test.tsx                | 41 +++++++++++
 .../src/__tests__/permanent-agent-gating.test.ts                 | 31 +++++++++
 .../src/__tests__/pi-create-fn-agent.test.ts                     | 80 ++++++++++++++++++++++
 packages/engine/src/agent-heartbeat.ts                           | 19 ++++-
 packages/engine/src/executor.ts                                  | 19 ++++-
 packages/engine/src/permanent-agent-gating.ts                    | 53 ++++++++++++++
 packages/engine/src/pi.ts                                        |  6 ++
 14 files changed, 461 insertions(+), 4 deletions(-)

Fusion-Task-Id: FN-7609

Fusion-Task-Lineage: 80a6bb5b-79f7-4b78-9204-402c2dea6171

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-06 19:03:06 -07:00
gsxdsm
60081fb1f4 FN-7610: route workspace-mode tasks around PR-merge auto-merge strategy
Fixes workspace-mode (workspaceWorktrees) tasks failing auto-merge under mergeStrategy=pull-request, where processPullRequestMergeTask threw "could not determine repository" because the workspace root is a container of independent git sub-repos, not itself a git repo.

- Hoist an isWorkspaceTask check in ProjectEngine's merge dispatch (project-engine.ts) before the mergeStrategy branch, so workspace tasks always fall through to the existing direct/landWorkspaceTask path regardless of configured mergeStrategy.
- Add processPullRequestMergeTask and syncGroupPrCallback defense-in-depth guards (task-lifecycle.ts) that throw the new named WorkspaceTaskMergeError if a workspace task ever reaches the PR-merge path.
- Add engine tests covering multi-repo, single-repo, and zero-commit no-op workspace tasks under mergeStrategy=pull-request, plus a non-regression test for the legacy single-worktree PR path.
- Add CLI tests asserting the new guards throw WorkspaceTaskMergeError.
- Add a patch changeset describing the fix.

Files changed:
 .changeset/fn-7610-workspace-pr-merge-routing.md   |   7 ++
 .../src/commands/__tests__/task-lifecycle.test.ts  |  56 +++++++++
 packages/cli/src/commands/task-lifecycle.ts        |  33 ++++-
 .../engine/src/__tests__/project-engine.test.ts    | 140 +++++++++++++++++++++
 packages/engine/src/project-engine.ts              |  18 ++-
 5 files changed, 252 insertions(+), 2 deletions(-)

Fusion-Task-Id: FN-7610
Fusion-Task-Lineage: 31768b77-d9a9-4a79-a055-bbc6b228a1c4
Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-06 19:03:06 -07:00
gsxdsm
ed136b1e76 fix(engine): repair two stale test mocks broken by #1910 (#1919)
Two engine test files fail on current `main` (17c4007). Both are stale
**test-mock** breakages — no production code is touched.

### 1. `restart.integration.test.ts`
Its `vi.mock("../pi.js", …)` factory replaces the module wholesale but
omits `ModelFallbackExhaustedError`. `triage.ts` guards its catch block
with `err instanceof ModelFallbackExhaustedError` (imported from
`pi.js`), so evaluating that guard throws *"No
ModelFallbackExhaustedError export is defined on the mock"*.

Fix: export a plain `Error`-subclass stub from the factory. No restart
test enters the fallback-exhausted branch, so `instanceof` simply
returns `false` — a faithful stub.

### 2. `reliability-interactions/mission-validation-trigger-gap.test.ts`
Two recovery-path `missionStore` mocks omit `getMission`. #1910's
mission-active gate now walks `getSlice → getMilestone → getMission`
inside `resolveFeatureMission`. The resulting throw is swallowed by
`processTaskOutcome`'s `catch`, aborting recovery before it can ensure
assertions / start the validator run — surfacing as
`ensureFeatureAssertionLinked` asserted called-once but seen 0 times.

Fix: add `getMission` returning an active mission to both mocks.

### Verification
```
npx vitest run src/__tests__/reliability-interactions/mission-validation-trigger-gap.test.ts src/__tests__/restart.integration.test.ts
Test Files  2 passed (2)
Tests  54 passed (54)
```

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Tests**
* Improved coverage for mission recovery and restart flows, making
validation scenarios more reliable.
* Fixed test mocks so recovery and triage paths can run without
unexpected errors during assertions.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-06 13:11:45 -07:00
gsxdsm
cc98852027 fix(engine): defer validator fail when the judged workspace predates the merged code (#1929)
## Problem

The mission validator runs its read-only judge session with `cwd:
this.rootDir` — the engine's **main working copy**. When a task's merge
landed on the remote (or in another worktree) and `rootDir` was never
fetched/reset to that commit, the judge reads **pre-merge files** and
returns a spurious `fail`.

#1917's premerge column guard does not catch this case: by the time
validation runs the task column is already `done`, so execution falls
through to `handleValidationFail` and mints a **bogus Fix Feature** for
code that is actually correct and merged.

## Fix

A symmetric second guard in the `fail` branch, placed **after** the
#1917 premerge column check:

- `isValidationWorkspaceStale(feature)` resolves the task's integration
SHA and runs `git merge-base --is-ancestor <sha> HEAD` in `rootDir`.
- **Only affirmative staleness evidence defers.** `--is-ancestor` exit
`1` (the SHA is *not* an ancestor of HEAD → the workspace predates the
merge) → defer the fail to **inconclusive**, so a later validation
judges the merged code.
- Every other outcome trusts the fail: exit `0` (ancestor → workspace is
fresh), no integration SHA available, or a bad/unknown object (exit
`128`).

Fail-open doctrine, matching #1917: a guard may only ever **defer** a
fail, never **suppress** one on missing or unreadable data.

## Tests

Four real-git cases in `mission-execution-loop.test.ts` (skipped when
`git` is unavailable):

1. Judged checkout predates the merged commit → fail deferred to
inconclusive, no Fix Feature minted, emits `validation:inconclusive`.
2. Merged commit is an ancestor of HEAD (fresh workspace) → normal fail
path, Fix Feature minted, emits `validation:failed`.
3. Task carries no integration SHA → fail open (normal fail).
4. Integration SHA is an unknown object (exit 128) → fail open (normal
fail).

Verified with stash-red/restore-green discipline: with the production
guard stashed, case (1) goes red while the three fail-open guardrails
stay green — proving case (1) exercises the fix. Full file: 62 passed.
`tsc --noEmit`: clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Validation failures are now deferred when the workspace appears to be
out of date with merged changes, reducing incorrect failure reports.
* Tasks with linked work continue to use the usual failure path when the
current workspace is up to date.
* Staleness checks now avoid masking real validation failures when no
merge reference is available or when the reference can’t be verified.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-06 13:11:21 -07:00
fusion-merge-train
58683f9610 fix(engine): defer validator fail when the judged workspace predates the merged code
The mission validator runs its read-only judge session with cwd:
this.rootDir — the engine's main working copy. When a task's merge landed
on the remote or in another worktree and rootDir was never fetched/reset to
it, the judge reads PRE-merge files and returns a spurious `fail`. #1917's
premerge column guard doesn't catch this: the task column is already `done`,
so it falls through to handleValidationFail and mints a bogus Fix Feature.

Add a symmetric second guard in the fail branch, after the premerge column
check: isValidationWorkspaceStale resolves the task's integration SHA and
runs `git merge-base --is-ancestor <sha> HEAD` in rootDir. Only affirmative
staleness evidence (exit 1 = NOT an ancestor) defers the fail to
inconclusive; exit 0 (ancestor/fresh), a missing SHA, or a bad object
(exit 128) all trust the fail. Fail-open: a guard may DEFER a fail, never
SUPPRESS one on missing or unreadable data.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 08:23:07 +02:00
Phil Larson
3d60f67fab fix(missions): address generated fix review blockers 2026-07-05 22:14:22 -07:00
Phil Larson
3744fbcc2f fix(missions): supersede stale generated fix features 2026-07-05 21:50:28 -07:00
gsxdsm
6c9989c847 fix(engine): short-circuit zero-commits-ahead branch before AI-merge clean-room churn (#1920)
## Problem

When a coding agent produces **zero commits** relative to base, the
AI-merge path wedges the card terminally:

1. `runAiMerge` → `landOneRepo` builds a clean-room worktree and runs a
dependency install.
2. On a non-workspace land the dep-install step throws hard (`if
(!ctx.nonFatalDependencySync) throw depsErr;`).
3. The throw is transient-classified and retried up to
`MAX_AUTO_MERGE_TRANSIENT_RETRIES` → `Auto-merge transient retries
exhausted (3/3)`.
4. The card is parked `failed` (→ archived), even though the correct
outcome for an empty branch is a no-op finalize.

The truly-empty branch *would* reach `outcome: "empty"` anyway via
`mergeAndReview` producing no `squashSha` — but only **after** the
throw-prone churn that fails first.

The canonical `aiMergeTask`/`classifyOwnedLandedEvidence` path already
has an early empty-own-diff fast-path; the `runAiMerge` → `landOneRepo`
path did not.

## Fix

Short-circuit inside `landOneRepo`, right after the `tipSha` computation
and **before** the clean-room build, when the branch is a confident zero
commits ahead of the integration tip:

```ts
const aheadRaw = await git(["rev-list", "--count", `${integrationBranch}..${branch}`], repoRootDir).catch(() => "");
if (Number.parseInt(aheadRaw.trim(), 10) === 0) {
  await audit.git({ type: "merge:ai-empty", target: integrationBranch, metadata: { taskId, tipSha } });
  return { outcome: "empty", tipSha, integrationBranch };
}
```

- Returns the **identical** `{ outcome: "empty", tipSha,
integrationBranch }` shape and the same `merge:ai-empty` audit event the
downstream already handles, so `runAiMerge`'s empty-outcome handling
(block-to-todo / no-op finalize) is unchanged.
- **Only** short-circuits on a confident `0`: a git failure yields `""`
→ `parseInt` → `NaN` (≠ 0) and falls through to the normal path — no
behavior change on error.
- Placed in `landOneRepo` (not `runAiMerge`) because it is shared by
both the single-repo and workspace per-repo callers.

## Test

New test in `merger-ai.test.ts` asserts the merge agent is **never
invoked** for a 0-ahead branch, the result is a no-op, `main` is
unmoved, and the card moves to `done` with `preserveProgress`. Without
the fix the branch reaches the clean room and `mergeAndReview` invokes
the merge agent, so the assertion fails — it genuinely guards the
short-circuit.

Full engine merge-suite regression run is green (merger-ai,
workspace-merger and lease variants, cleanup, dependency-sync,
group-merge, classify-owned-landed-evidence).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved merge handling for branches with no new commits ahead of the
target branch.
* Empty or already-synced branches now finish as a no-op instead of
triggering merge work.
* Tasks in this scenario still move to done, while the main branch
remains unchanged.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-05 21:37:26 -07:00
gsxdsm
9b7921b7d8 fix(engine): defer validator fail to inconclusive while the linked task is unmerged (#1917)
## Problem

`MissionExecutionLoop.runFeatureValidation` treats a validator "fail"
verdict as authoritative regardless of whether the linked task's code
has actually landed. When validation fires while the task is still
mid-pipeline — an in-review PR, an external merge train, a deferred base
sync — the validator judges a checkout that predates the merge,
concludes the feature "is not present", and `handleValidationFail` mints
a Fix feature for work that is already done.

We hit this in production (2026-07-05): a recovery-path validation ran
against four features whose implementing tasks were in-review in an
external merge pipeline. All four "failed" → four duplicate Fix tasks
were created one minute after the real work merged. Worse, the Fix
tasks' planned file scopes included hot shared files, so their
file-scope leases serialized the entire board until they were manually
archived.

## Fix

Before dispatching a `fail` verdict, resolve the linked task's column.
If it affirmatively shows the task has **not** completed (any column
other than `done`/`archived`), route the outcome to
`handleValidationInconclusive` (R21 — completes the run as `blocked`,
logs `verification_inconclusive`, notifies autopilot, **spawns no Fix
feature**) with a "code not merged yet — validation deferred" reason. A
later validation (post-merge recovery pass) judges the real merged code.

**Fails open by design** — the guard may only ever *defer* a fail, never
suppress one on missing data. Missing `taskId`, missing task, unreadable
store, or unknown column all fall through to the normal
`handleValidationFail` path:

```ts
private async getPremergeTaskColumn(taskId: string | undefined): Promise<string | null> {
  if (!taskId) return null;
  const linkedTask = await this.taskStore.getTask(taskId).catch(() => null);
  const column = linkedTask?.column;
  if (!column || column === "done" || column === "archived") return null;
  return column;
}
```

The vanilla flow is unaffected: the scheduler triggers validation on
`toColumn === "done"`, so by the time a normally-triggered validation
runs the task is already `done` and the guard is a no-op. Only
recovery-path / re-validation runs that race an unmerged task are
deferred.

## Tests

Three new tests in `mission-execution-loop.test.ts` (`premerge guard`
describe):

1. fail verdict + linked task `in-review` → routes to inconclusive: no
Fix feature, run completed as `blocked`, `validation:inconclusive`
emitted (not `validation:failed`), `verification_inconclusive` mission
event logged
2. fail verdict + linked task `done` → normal fail path: Fix feature
created, `validation:failed` emitted
3. fail verdict + `taskStore.getTask` rejects → fails open to the normal
fail path

`npx vitest run src/__tests__/mission-execution-loop.test.ts`: 58/58
green. `npx tsc --noEmit`: clean. Full engine suite: the 46 failures
across 24 files present on my branch fail **identically on clean
`17c4007`** (verified by re-running the same files on a detached
checkout of upstream main) — all pre-existing/environment-dependent,
none related to this change.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Validation failures now account for whether the linked task is
actually merged. If the task is still in progress, the result is marked
as inconclusive instead of creating a fix flow.
* Added clearer handling when task details can’t be read, so normal
failure behavior still applies.
* Improved validation status reporting and event logging for merged vs.
unmerged task states.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-05 21:37:04 -07:00
gsxdsm
51f354dec1 Merge branch 'main' into fix/stale-test-mocks 2026-07-05 21:36:07 -07:00
gsxdsm
f7d1346724 Merge branch 'main' into fix/validator-premerge-guard 2026-07-05 21:04:34 -07:00
gsxdsm
1ee2e3a27c Merge branch 'main' into fix/transient-auth-retry 2026-07-05 21:02:11 -07:00
gsxdsm
9bbb16c4a1 Merge branch 'main' into fix/empty-branch-merge-wedge 2026-07-05 21:01:51 -07:00
gsxdsm
78d570747f fix(engine): self-heal failed in-review cards whose PR merged on the remote (#1922)
## Problem

A transient error at merge time can flag an in-review card `failed` even
when its PR actually squash-merged on the remote (human merge,
merge-train, etc.). `recoverAlreadyMergedReviewTasks` runs the
already-merged **evidence detector** only against the **local** base
ref. If this process never fetched the merge, the owned commit is absent
locally → the detector returns `null` → `landed` is null → the card
never finalizes and **holds its file-scope lease forever**, wedging
every other task that touches the same files.

## Fix — fetch-then-prove

When a `failed` in-review candidate has a recorded PR
(`getPrimaryPrInfo`) and the local base yields no owned commit:

1. best-effort `git fetch origin <base>` (new `refreshRemoteBaseRef`
helper), then
2. re-run the **same** evidence detector against `origin/<base>`.

The detector's owned-commit proof and every foreign-ownership guard
inside it remain the **sole** finalize gate, so this only un-wedges a
genuinely-merged task — it never phantom-finalizes on unproven state.

**Safety:**
- Gated on a recorded PR — no PR ⇒ nothing could have merged remotely ⇒
no fetch.
- Fail-closed — a fetch error (offline / auth / no remote) is swallowed;
if `origin/<base>` can't be resolved the card is left untouched.
- No new dependency, no github client seam — direct git only.

## Tests

Two real-git tests in `self-healing-already-merged.real-git.test.ts`,
both verified to **fail without the prod change**:

- **fetch-then-prove positive:** a PR squash-merges on a bare remote
while the local base stays stale → recovery fetches, proves the owned
SHA against `origin/main`, and finalizes the card to `done`
(`mergeConfirmed: true`, worktree removed).
- **phantom-finalize guard:** remote base advances with a commit owned
by a *different* task → the fetch still runs, but the detector proves
nothing → the card is left `failed`/`in-review`, never healed.

Full self-heal suite: 594 passed. Engine typecheck clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved recovery for review tasks that appear already merged when the
local base branch is stale.
* The app now refreshes the remote base branch before re-checking merge
status, helping finalize tasks correctly and clean up completed
worktrees.
* Added coverage for cases where the remote base has moved forward with
either the merged commit or unrelated changes.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-05 20:59:01 -07:00
gsxdsm
ba9c9b5ca7 Merge branch 'main' into fix/self-heal-merged-pr-stale-base 2026-07-05 20:47:22 -07:00
gsxdsm
80a05e41fe Merge branch 'main' into fix/hermes-runtime-chat-state 2026-07-05 20:45:47 -07:00
gsxdsm
eb86555797 chore(release): v0.56.1
Version bump via changesets.
2026-07-05 19:57:09 -07:00
gsxdsm
ed823c794c fix: preserve Claude OAuth scopes on token refresh so inference keeps working
The Anthropic OAuth refresh request sent `scope: user:profile`, which under
RFC 6749 §6 re-issues the access token with exactly that scope — stripping
`user:inference` and 403-ing every model call while the account still read
as "logged in via OAuth". Stop sending `scope` on refresh (Anthropic then
preserves the originally-granted scopes, matching pi-ai), and widen
ANTHROPIC_DEFAULT_SCOPES to mirror pi-ai's full granted Claude Code scope
set so any fallback describes a usable token.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 18:47:40 -07:00
Phil Larson
8d6c92ac2e fix: preserve Hermes runtime chat session state 2026-07-05 17:50:13 -07:00
gsxdsm
2025f9d56d chore(release): v0.56.0
Version bump via changesets.
2026-07-05 17:13:36 -07:00
gsxdsm
09a1c9d843 FN-7596: regression-test the Coding (Ideas) manual-intake lifecycle end-to-end
Adds cross-layer regression coverage for the manual-intake parking lifecycle (create -> parked -> operator Start promotion -> poll-time todo-discovery), and clarifies the workflow-steps doc to describe the tested lifecycle.

- packages/core: covers store create -> moveTask promotion out of the parked intake column
- packages/engine: covers triage poll ordering/discovery of the still-unplanned bootstrap-stub card
- packages/dashboard: covers TaskCard's Start affordance for parked cards
- docs: documents the full regression-tested lifecycle for manual-intake column parking (FN-7596)

Files changed:
 docs/workflow-steps.md                             |   2 +-
 .../__tests__/store-create-intake-column.test.ts   |  26 ++++
 .../app/components/__tests__/TaskCard.test.tsx     | 153 +++++++++++++++++++++
 packages/engine/src/__tests__/triage.test.ts       | 119 +++++++++++++++-
 4 files changed, 298 insertions(+), 2 deletions(-)

Fusion-Task-Id: FN-7596

Fusion-Task-Lineage: 267c3d9a-6181-4ca5-b871-7009c0204372

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 16:33:21 -07:00
gsxdsm
f30d55fae7 FN-7593: move Before/After Transformation section to top of task definitions
Reorders task-definition prompt templates so the Before -> After Transformation section appears before other sections, making the expected change visible first.

- Move the Before -> After Transformation section ahead of other sections in agent-prompts.ts task-definition templates
- Update docs/task-management.md to reflect the new section order
- Add/extend tests in agent-prompts.test.ts and triage.test.ts covering the new ordering
- Add changeset fn-7593-before-after-top.md documenting the change

Files changed:
 .changeset/fn-7593-before-after-top.md            |  7 +++++++
 docs/task-management.md                           |  2 +-
 packages/core/src/__tests__/agent-prompts.test.ts | 20 ++++++++++++++++++++
 packages/core/src/agent-prompts.ts                | 20 +++++++++++++-------
 packages/engine/src/__tests__/triage.test.ts      | 17 +++++++++++++++++
 5 files changed, 58 insertions(+), 8 deletions(-)

Fusion-Task-Id: FN-7593

Fusion-Task-Lineage: d0d5eb4d-2fe0-456c-b061-5c078b78911b

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 13:44:50 -07:00
fusion-merge-train
15c2c831a8 fix(engine): self-heal failed in-review cards whose PR merged on the remote
A transient error at merge time can flag an in-review card `failed` even
when its PR actually squash-merged on the remote. `recoverAlreadyMergedReviewTasks`
only ran the already-merged evidence detector against the LOCAL base ref, so
when this process never fetched the merge, the owned commit was absent locally,
the detector returned null, and the card held its file-scope lease forever.

Fetch-then-prove: when a failed candidate has a recorded PR and the local base
yields no owned commit, best-effort `git fetch origin <base>` and re-run the
SAME evidence detector against `origin/<base>`. The owned-commit proof and every
foreign-ownership guard inside the detector remain the sole finalize gate, so
this only un-wedges a genuinely-merged task — it never phantom-finalizes on
unproven state. Gated on a recorded PR (no PR ⇒ nothing merged remotely ⇒ no
fetch); fail-closed on fetch error.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 20:41:20 +02:00
gsxdsm
72b77bf621 fix(FN-7561): stop Plan Review replan loop and fix "can't find the plan" reviews
The Plan Review pre-merge gate could loop a task through triage↔plan-review
indefinitely (FN-7525 ran 13+ replans overnight with no operator visibility),
and its reviewer frequently produced "no PROMPT.md found / data lives in a DB"
non-verdicts that fed the loop.

Root cause of the non-verdicts: the reviewer runs readonly with cwd set to the
task worktree, but the spec lives at project-root .fusion/tasks/<id>/PROMPT.md —
outside the worktree — so telling it to "Read PROMPT.md" had it search the wrong
tree and give up. Four fixes:

1. Inject the PROMPT.md content (via readTaskArtifact, store-backed) directly
   into the Plan Review reviewer prompt so the verdict never depends on the
   agent locating the file.
2. Self-retry a malformed reviewer response once on the primary model when no
   fallback model is configured, so a single fumbled response gets a second
   chance instead of feeding the replan loop.
3. A malformed (advisory_failure, no parsed verdict) plan-review result can
   never trigger a triage replan — it is an infra failure, not a plan defect.
4. Cap the unbounded plan-review replan default at 15 attempts; past the cap it
   emits a loud halting log entry and leaves the task for a human instead of
   looping forever. Explicit numeric operator budgets are unchanged.

Tests: cap halts at 15 / still replans at 14 / malformed never replans. Existing
Plan Review replan and malformed-verdict-gate tests still pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 11:31:49 -07:00
gsxdsm
42bbe58c03 FN-7579: add ask-user and exit-gate workflow nodes
Add workflow nodes for mid-flow user reach-out and early exit from a workflow run.

- Add `ask-user` IR node kind that reuses the await-input park/resume mechanism and surfaces the question in the task chat for brainstorming/clarification.
- Add `exit-gate` IR node kind that terminates the workflow early, with an optional condition.
- Wire both node kinds through the engine executor and workflow-node-handlers, including a new exit-gate-runner.
- Update the WorkflowNodeEditor palette, node summaries, and node help text for the two new node types.
- Extend workflow-flow-mapping to support the new node kinds.
- Keep `prompt`+`awaitInput` as a back-compat alias.
- Add core/engine/dashboard tests covering the new node kinds.
- Document the new nodes in docs/workflow-steps.md.
- Add changeset for the new minor feature.

Files changed:
 .changeset/fn-7579-ask-user-exit-gate-nodes.md     |   7 +
 docs/workflow-steps.md                             |  28 ++++
 packages/core/src/__tests__/workflow-ir.test.ts    | 120 ++++++++++++++
 packages/core/src/workflow-ir-types.ts             |  12 +-
 packages/core/src/workflow-ir.ts                   |  47 ++++++
 .../app/components/WorkflowNodeEditor.tsx          | 181 ++++++++++++++++++++-
 .../app/components/__tests__/node-summary.test.ts  |  43 +++++
 .../__tests__/workflow-flow-mapping.test.ts        |  49 ++++++
 .../app/components/nodes/WorkflowNodeTypes.tsx     |  14 +-
 .../dashboard/app/components/nodes/node-help.ts    |  24 +++
 .../dashboard/app/components/nodes/node-summary.ts |  28 ++++
 .../app/components/workflow-flow-mapping.ts        |   4 +
 .../workflow-graph-executor-handlers.test.ts       | 115 +++++++++++++
 .../src/__tests__/workflow-node-handlers.test.ts   |  66 ++++++++
 packages/engine/src/executor.ts                    |  23 ++-
 packages/engine/src/workflow-node-handlers.ts      |  18 +-
 .../src/workflow-node-runners/exit-gate-runner.ts  |  81 +++++++++
 17 files changed, 849 insertions(+), 11 deletions(-)

Fusion-Task-Id: FN-7579
Fusion-Task-Lineage: 9a89ff49-200d-4a6c-b97c-15d219349ee5
Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:48 -07:00
gsxdsm
74358494a7 FN-7577: extend PR-based revert to workspace tasks under autoMerge:false
Extends FN-7554's single-repo PR revert path to workspace (multi-repo) tasks: when autoMerge is disabled, the revert route now opens one dedicated fusion/revert-<id> PR per sub-repo instead of refusing workspace tasks outright.

- Add prepareWorkspaceRevertPrBranches (packages/engine/src/task-revert.ts): classifies every sub-repo first and only prepares a per-sub-repo fusion/revert-<id> branch when all sub-repos are clean/already-reverted (all-or-nothing at branch-prep phase); never force-writes any sub-repo integration branch.
- Export the new helper from packages/engine/src/index.ts.
- Extend POST /api/tasks/:id/revert (register-task-workflow-routes.ts) to resolve owner/repo and check the GitHub rate limiter for every sub-repo before pushing/creating any PR, opening one PR per sub-repo and returning an additive { mode: "pr", clean: true, workspace: { repos: [...] } } result; degrades the whole task to needsHuman if GitHub is unconfigured or any sub-repo is rate-limited, rather than opening a partial subset of PRs.
- Leave existing { mode: "git" | "ai" | "pr" } shapes, the autoMerge:true workspace path, and FN-7554's single-repo PR path unchanged.
- Add engine real-git coverage (task-revert-workspace-pr.real-git.test.ts) and extend dashboard route tests (task-revert-route.test.ts) for the new workspace PR path.
- Add changeset (.changeset/fn-7577-workspace-pr-revert.md, minor) and update docs/task-management.md.

Files changed:
 .changeset/fn-7577-workspace-pr-revert.md          |   7 +
 docs/task-management.md                            |   3 +-
 .../src/__tests__/task-revert-route.test.ts        | 313 ++++++++++++++++-
 .../src/routes/register-task-workflow-routes.ts    | 181 +++++++++-
 .../task-revert-workspace-pr.real-git.test.ts      | 371 +++++++++++++++++++++
 packages/engine/src/index.ts                       |   4 +
 packages/engine/src/task-revert.ts                 | 295 ++++++++++++++++
 7 files changed, 1166 insertions(+), 8 deletions(-)

Fusion-Task-Id: FN-7577

Fusion-Task-Lineage: bedbfab7-5804-485f-9b40-64531edfc64a

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:48 -07:00
gsxdsm
b173f76adb fix(FN-7577): stop planner overseer from "recovering" healthy in-progress tasks
decidePlannerRecovery fell through to inject_guidance for any non-failed
executor/workflow-gate signal, including the healthy `progressing` signal.
Under autonomous oversight this dispatched steering into the live agent of
every healthy task — flipping the card badge to "recovering", burning a
bounded-attempt slot, and consuming AI usage for no reason.

- Only problem signals (`stuck`/`blocked`, plus the existing `failed` path)
  now trigger autonomous steering; healthy (`progressing`/`complete`) and
  human-wait (`awaiting-human`) signals return `none`.
- PlannerRecoveryController.tick clears stale attempt/last-action records for
  a (taskId, stage) once its signal is healthy, so a recovered task drops
  from "recovering" back to "watching" and a later problem gets a fresh budget.
- PlannerOverseerMonitor dedupes the activity-feed heartbeat: an unchanged
  (stage, signal, reason) observation logs once per change, not every tick.

Invariant tests added across all signals for both fall-through stages.

Fusion-Task-Id: FN-7577

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 11:31:48 -07:00
gsxdsm
94e9d15e38 FN-7556: auto-select review-heavy workflow for AI-undo tasks
AI-undo tasks now default to a configurable, stricter review workflow instead of always inheriting the project default.

- Add project setting `aiUndoTaskWorkflowId` (default `builtin:review-heavy`) to ProjectSettings type and DEFAULT_PROJECT_SETTINGS
- `POST /api/tasks/:id/revert` resolves and validates the configured workflow id (via `isBuiltinWorkflowId`/`getWorkflowDefinition`), falling back to inherit-with-warning on a blank/unknown value
- `createAiUndoTask` engine helper gains an optional `workflowId` param, forwarded verbatim to `createTask` only when non-blank, staying pure (no settings/store access itself)
- Add regression tests for the route resolution logic and the engine helper's workflow forwarding
- Update docs (`settings-reference.md`, `task-management.md`) and add changeset

Files changed:
 .changeset/fn-7556-ai-undo-workflow.md             |  7 +++
 docs/settings-reference.md                         |  1 +
 docs/task-management.md                            |  1 +
 packages/core/src/settings-schema.ts               |  4 ++
 packages/core/src/types.ts                         | 14 +++++
 .../settings-default-descriptions.test.tsx         |  2 +
 .../src/__tests__/task-revert-route.test.ts        | 52 ++++++++++++++++-
 .../src/routes/register-task-workflow-routes.ts    | 31 +++++++++-
 .../src/__tests__/task-revert-ai-undo.test.ts      | 67 ++++++++++++++++++++++
 packages/engine/src/task-revert.ts                 | 16 ++++++
 10 files changed, 192 insertions(+), 3 deletions(-)

Fusion-Task-Id: FN-7556
Fusion-Task-Lineage: dec5603c-10a8-4780-a1b8-8a836a0de4c1
Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:47 -07:00
gsxdsm
2df6c356fc FN-7554: add PR-based revert path for autoMerge:false projects
Adds a PR-based revert path for done/archived tasks in autoMerge:false projects instead of refusing outright.

- New engine export `prepareRevertPrBranch` (packages/engine/src/task-revert.ts) prepares a dedicated `fusion/revert-<id>` branch off the base branch's HEAD and applies the revert commit(s) there, never mutating the base branch itself.
- `POST /api/tasks/:id/revert` route gains an additive `{ mode: "pr", clean: true, prUrl, prNumber, revertBranch, existingPr? }` result for clean single-repo reverts under autoMerge:false, reusing GitHubClient.createPr, findPrForBranch idempotency, and the manual:true PR handoff.
- Existing `{ mode: "git" | "ai", ... }` result shapes and the autoMerge:true path are unchanged.
- Workspace (multi-repo) tasks are explicitly refused for PR-based revert (out of scope; single PR cannot represent a multi-repo revert).
- Adds real-git integration tests for the new branch-prep/apply/commit flow and expands the dashboard route test coverage.
- Adds a changeset for @runfusion/fusion (minor) and a small task-management doc update.

Files changed:
 .changeset/fn-7554-pr-based-revert.md              |   7 +
 docs/task-management.md                            |   2 +-
 .../src/__tests__/task-revert-route.test.ts        | 196 +++++++++++++++++++-
 .../src/routes/register-task-workflow-routes.ts    | 182 ++++++++++++++++++
 .../src/__tests__/task-revert-pr.real-git.test.ts  | 206 +++++++++++++++++++++
 packages/engine/src/index.ts                       |   3 +
 packages/engine/src/task-revert.ts                 | 154 +++++++++++++++
 7 files changed, 747 insertions(+), 3 deletions(-)

Fusion-Task-Id: FN-7554

Fusion-Task-Lineage: 9b1bfd82-2428-4cf7-9b36-77afe3517a14

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:47 -07:00
gsxdsm
a5ac3c3314 fix(FN-7566): stop phantom-binding reclaim from killing live ephemeral executor tasks
isPhantomExecutorBinding's liveness gate (heartbeat/checkout/runAudit) is
structurally blind to ephemeral executor agents, leaving only the
age>graceMs*3 (~30 min) threshold, so any ephemeral-executor task running
longer than ~30 min was reclaimed to `todo` mid-flight and its worktree
destroyed. Add the in-process live-session veto (activeSessionRegistry path /
executingTaskLock / isTaskActive), mirroring the isWorkspaceTaskLive/sessionDead
predicate, and honor clearPhantomExecutorBinding's live-session refusal in
reclaimSelfOwnedBranchConflicts. Legitimate FN-6736 leaked-binding recovery is
preserved (empty registry / no lock / inactive task still reads as phantom).

Fusion-Task-Id: FN-7566

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 11:31:47 -07:00
gsxdsm
4b530a65de fix: restore Anthropic subscription card after in-session logout + re-login
Subscription OAuth is aliased across the legacy `anthropic` id (where login
persists the credential) and `anthropic-subscription` (where the settings card
and status read are keyed). After an in-session logout, re-login wrote only
`anthropic` and never cleared the in-memory `anthropic-subscription` logged-out
flag, so the card reported "Login did not complete" despite a valid stored
credential until the process restarted.

auth-storage's proxy now clears the logged-out suppression on both aliases when
either is re-authenticated (new `login` trap + hardened `set` trap via
clearReauthenticatedLogoutState); raw api_key writes stay scoped to their own
card. Also surface previously-swallowed background OAuth login failures on
GET /auth/status (`loginError`) plus server logs and a settings toast, so real
paste-callback failures are diagnosable instead of a generic error.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 11:31:47 -07:00
gsxdsm
b471aece6a fix(FN-7560): stop release-auth gate flagging tasks that disclaim releasing
The release-authorization classifier substring-matched release signals
(notably `scripts/release.mjs`) even inside disclaimer clauses that
explicitly say the task performs NO release/publish. AI-authored specs
routinely append such disclaimers, so revert/undo/UI tasks (FN-7525,
FN-7554, FN-7556) were parked in awaiting-release-authorization with no
in-band exit — their non-user sources (agent_heartbeat/api) make the
authorization marker inert.

classifyReleaseTask now strips negated release-disclaimer clauses before
signal matching. Genuine "run pnpm release"/"publish @runfusion/fusion"
intent lives in a non-negated clause and still trips the gate. Tests
cover all three real repro shapes plus every documented signal in both
its negated (not release-class) and actionable (still release-class) form.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 11:31:47 -07:00
gsxdsm
ce9df297eb FN-7574: fix OAuth token expiry detection and add proactive auto-refresh
Unifies OAuth expiry detection so expired Claude subscription logins correctly show as disconnected with a re-login prompt, and adds a proactive engine-side scheduler that refreshes tokens before they expire.

- Share expiry-detection logic between OAuthExpiryMonitor and the /api/auth/status route so both agree on when a token is expired.
- Add engine-side oauth-refresh-scheduler that proactively refreshes OAuth tokens ahead of expiry, wired into project-engine (guarded by skipNotifier).
- Extend auth-storage with the helpers needed for expiry checks/refresh.
- Add tests covering routes-auth status detection, auth-storage expiry helpers, and the new refresh scheduler.
- Document the new behavior in dashboard-guide.md and settings-reference.md.
- Add changeset for the user-facing fix.

Files changed:
 .../fn-7574-oauth-expiry-detection-refresh.md      |   7 +
 docs/dashboard-guide.md                            |   4 +
 docs/settings-reference.md                         |   4 +
 .../dashboard/src/__tests__/routes-auth.test.ts    |  76 +++++++++++
 .../dashboard/src/routes/register-auth-routes.ts   |  25 +++-
 packages/engine/src/__tests__/auth-storage.test.ts |  60 +++++++++
 packages/engine/src/auth-storage.ts                |  14 +-
 .../__tests__/oauth-refresh-scheduler.test.ts      | 141 ++++++++++++++++++++
 packages/engine/src/notification/index.ts          |   3 +
 .../src/notification/oauth-refresh-scheduler.ts    | 143 +++++++++++++++++++++
 packages/engine/src/project-engine.ts              |  14 +-
 11 files changed, 488 insertions(+), 3 deletions(-)

Fusion-Task-Id: FN-7574

Fusion-Task-Lineage: 59996eac-c070-4992-9727-d066c6934b69

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:46 -07:00
gsxdsm
9592e3ac5c FN-7569: skip re-asking manual plan approval for unchanged re-specified plans
Manual plan approval now skips re-asking for approval when a re-specification produces an identical plan to one already approved.

- Add nullable Task.approvedPlanFingerprint field with DB migration 139 to track the approved PROMPT.md fingerprint
- Skip re-parking at awaiting-approval when replan/plan-review-retry/self-healing rebound yields the same plan fingerprint as before
- Require fresh approval when the plan content changes or when a plan is rejected
- Leave Release Authorization, Workflow Plan Review, and auto-approve-all behavior unchanged
- Add/extend tests across core (db, plan-approval, store-persistence), engine (triage), and dashboard (routes-github) to cover fingerprint comparison and idempotent re-approval
- Update docs (settings-reference.md, workflow-steps.md) to describe the idempotent approval behavior
- Add changeset for @runfusion/fusion (patch)

Files changed:
 .changeset/fn-7569-plan-approval-idempotent.md     |   7 +
 docs/settings-reference.md                         |   2 +-
 docs/workflow-steps.md                             |   2 +
 packages/core/src/__tests__/db.test.ts             |  54 +++++++
 packages/core/src/__tests__/plan-approval.test.ts  |  31 +++-
 .../core/src/__tests__/store-persistence.test.ts   |  39 +++++
 packages/core/src/db.ts                            |  22 ++-
 packages/core/src/index.ts                         |   2 +-
 packages/core/src/plan-approval.ts                 |  23 +++
 packages/core/src/store.ts                         |  20 ++-
 packages/core/src/types.ts                         |  13 ++
 .../dashboard/src/__tests__/routes-github.test.ts  |  69 +++++++-
 .../src/routes/register-task-workflow-routes.ts    |  37 ++++-
 packages/engine/src/__tests__/triage.test.ts       | 178 ++++++++++++++++++++-
 packages/engine/src/triage.ts                      |  58 +++++--
 15 files changed, 527 insertions(+), 30 deletions(-)

Fusion-Task-Id: FN-7569

Fusion-Task-Lineage: 7d3855ae-6f45-4571-90db-cf1ae3b541dd

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:46 -07:00
gsxdsm
2ed06f9f14 FN-7547: support reverting multi-repo workspace tasks via git
Adds all-or-nothing git-revert support for multi-repo workspace tasks and wires it into the existing revert route/AI-undo/per-sha machinery.

- Add `resolveWorkspaceTaskRevertCommits` and `revertWorkspaceTask` to `packages/engine/src/task-revert.ts`, dry-run classifying every sub-repo first and only committing per-repo revert commits when every sub-repo is clean/already-reverted; any conflicting sub-repo rolls back every already-committed sub-repo.
- Extract shared `applyAndCommitRevert" apply/commit machinery (built on the existing `applyRevertNoCommit` primitive) so the workspace path reuses the same commit-message/trailer contract as the single-repo path.
- Add a defensive `isWorkspaceTask` guard to `performTaskRevert` so workspace tasks can never be silently reverted through the single-repo path.
- Wire `POST /api/tasks/:id/revert` (register-task-workflow-routes.ts) to dispatch workspace tasks to `revertWorkspaceTask`, preserving the existing `mode` (git/ai/auto) and AI-undo-fallback contract for workspace conflicts.
- Export the new workspace revert types/functions from `packages/engine/src/index.ts`.
- Add route-dispatch and real-git workspace revert test coverage; update docs and add a changeset.

Files changed:
 .changeset/fn-7547-workspace-task-revert.md        |   7 +
 docs/task-management.md                            |   8 +-
 packages/dashboard/src/__tests__/task-revert-route.test.ts        | 102 +++++
 packages/dashboard/src/routes/register-task-workflow-routes.ts    |  76 +++-
 packages/engine/src/__tests__/task-revert.workspace.real-git.test.ts | 272 +++++++++++++
 packages/engine/src/index.ts                       |   6 +
 packages/engine/src/task-revert.ts                 | 448 ++++++++++++++++++++-
 7 files changed, 897 insertions(+), 22 deletions(-)

Fusion-Task-Id: FN-7547

Fusion-Task-Lineage: b1b5eeda-06fd-43c1-8163-74b62c77b000

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:44 -07:00
gsxdsm
6e4c207a7f FN-7559: disambiguate release-authorization holds from manual plan-approval holds
Disambiguate release-authorization approval holds from manual plan-approval holds so auto-approve no longer appears broken.

- Add `Task.awaitingApprovalReason` (`"release-authorization" | null`) to distinguish the release-authorization gate from the independent manual plan-approval gate, both of which set `status: "awaiting-approval"`.
- Stamp `awaitingApprovalReason: "release-authorization"` when the release gate blocks a task, and explicitly clear it (`null`) when the manual plan-approval gate parks the task, so a stale reason never survives a replan.
- Add DB migration/persistence support for the new column in `db.ts`/`store.ts`/`types.ts`.
- TaskCard/TaskDetailModal now render a distinct status for release-authorization holds and suppress the generic manual Approve/Reject affordance for them.
- Add i18n string and docs updates (`settings-reference.md`, `workflow-steps.md`) plus a changeset.
- Extend regression tests in db, triage, TaskCard, and TaskDetailModal to cover the new reason field and disambiguated UI.

Files changed:
$(git diff --cached --stat)

Fusion-Task-Id: FN-7559
Fusion-Task-Lineage: 0b37cbf0-40a4-4165-8088-482ed365ba19
Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:44 -07:00
gsxdsm
8c6f76c37e FN-7548: add per-sha revert commit granularity to the git-revert service/route
Adds an opt-in per-sha commit granularity mode to the task-revert git path, alongside its default squash behavior, and merges it cleanly with the existing FN-7524 AI-undo mode support.

- Add `TaskRevertGranularity` ("squash" | "per-sha") and thread an optional `granularity` option through `performTaskRevert`/`PerformTaskRevertOptions`.
- Factor a shared `applyRevertNoCommit` primitive (stage + no-op/conflict detection) used by both the squash and new per-sha apply paths.
- `"per-sha"` creates one attributed `revert(FN-xxxx): ...` commit per original sha (each with its own `Fusion-Task-Id` trailer and audit line), skipping no-op shas without empty commits; a mid-batch conflict rolls the whole batch back to the pre-call HEAD.
- Extend `TaskRevertResult`'s clean shape with `revertCommitShas: string[]` (all created commits) alongside the existing `revertCommitSha`.
- `POST /api/tasks/:id/revert` accepts an optional `granularity` request-body field (default `"squash"`, validated, 400 on unknown values) and forwards it to the engine service; documented alongside the existing `mode` (git/ai/auto) contract.
- Add real-git and route-level test coverage for per-sha creation, no-op skipping, default-squash behavior, and mid-batch conflict rollback.
- Update docs/task-management.md's revert section and add a changeset.

Files changed:
 .changeset/fn-7548-per-sha-revert-granularity.md   |   7 +
 docs/task-management.md                            |   3 +-
 packages/dashboard/src/__tests__/task-revert-route.test.ts        |  46 +++++-
 packages/dashboard/src/routes/register-task-workflow-routes.ts    |  51 ++++--
 packages/engine/src/__tests__/task-revert.real-git.test.ts     | 124 +++++++++++++++
 packages/engine/src/index.ts                       |   2 +
 packages/engine/src/task-revert.ts                 | 176 +++++++++++++++++----
 7 files changed, 359 insertions(+), 50 deletions(-)

Fusion-Task-Id: FN-7548

Fusion-Task-Lineage: b9548f5e-fcc2-45d4-98e0-dd7340928208

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:44 -07:00
gsxdsm
c4d81fe5cc FN-7524: add AI-undo fallback task for reverting done/archived tasks
Adds an AI-undo fallback to the revert route: when a git-based revert conflicts or is unsupported, an ordinary board task is created to perform the undo via AI instead of a forced/failed git write.

- POST /tasks/:id/revert now accepts an optional `{ mode?: "git" | "ai" | "auto" }` body (default "auto"); unknown values reject with 400.
- "git" preserves the FN-7523 git-only contract unchanged; "ai" always creates the AI-undo task; "auto" tries git first and falls back to AI only on a conflicting or unsupported (e.g. workspace) result — needsHuman (autoMerge:false) never triggers the fallback.
- New engine helpers in task-revert.ts: `createAiUndoTask`, `buildAiUndoTaskDescription`, `REVERT_OF_METADATA_KEY`, plus `AiUndoTaskResult`/`CreateAiUndoTaskDeps` types, exported from packages/engine/src/index.ts.
- The AI-undo task is created via the normal triage-column `store.createTask` path with no dependency on the source task, referencing the source task's mission, id, and landed files, and instructing an undo commit using the `revert(FN-xxxx): ...` convention.
- New core `TaskStore.findOpenRevertTaskForSource` backs an idempotency guard: a repeated call while an AI-undo task is still open returns the same `createdTaskId` with `alreadyOpen: true` instead of creating a duplicate.
- Updated docs/task-management.md's revert section to document the git path + AI-undo fallback contract.
- Added a minor changeset for the @runfusion/fusion release notes.
- Added/extended tests: packages/engine/src/__tests__/task-revert-ai-undo.test.ts (new) and packages/dashboard/src/__tests__/task-revert-route.test.ts (extended) covering mode validation, auto-fallback-on-conflict, forced "ai" mode, and the duplicate-open-task guard.

Files changed:
 .changeset/fn-7524-ai-undo-revert.md               |   7 +
 docs/task-management.md                            |  13 +-
 packages/core/src/store.ts                         |  31 +++++
 packages/dashboard/src/__tests__/task-revert-route.test.ts | 143 ++++++++++++++++++++-
 packages/dashboard/src/routes/register-task-workflow-routes.ts |  75 +++++++++--
 packages/engine/src/__tests__/task-revert-ai-undo.test.ts |  114 ++++++++++++++++
 packages/engine/src/index.ts                       |   5 +
 packages/engine/src/task-revert.ts                 | 117 ++++++++++++++++-
 8 files changed, 487 insertions(+), 18 deletions(-)

Fusion-Task-Id: FN-7524

Fusion-Task-Lineage: 64dfedcf-c286-4c46-8cf8-51ec5e668bf7

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-05 11:31:43 -07:00
fusion-merge-train
ca2fbbd8f8 fix(engine): short-circuit zero-commits-ahead branch before AI-merge clean-room churn
An AI-merge land of a branch with zero commits ahead of the integration
tip (the shape a coding agent that produced no commits leaves behind)
builds a clean-room worktree and runs a dependency install before
reaching the empty outcome via mergeAndReview. On a non-workspace land
the dep install throws hard, so the merge is transient-retried to
exhaustion (3/3) and the card is terminally parked failed.

Short-circuit on a CONFIDENT zero-ahead count (a git failure yields NaN
and falls through) and return the identical outcome:"empty" shape
before the throw-prone churn.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 20:09:25 +02:00
fusion-merge-train
e5cae03f9a fix(engine): repair two stale test mocks broken by #1910
restart.integration.test.ts's `../pi.js` factory replaces the module
wholesale but omits ModelFallbackExhaustedError, which triage.ts references
via `err instanceof ModelFallbackExhaustedError` — evaluating the guard threw
"No ModelFallbackExhaustedError export is defined on the mock". Added a plain
Error-subclass stub (no restart test enters the fallback-exhausted branch).

mission-validation-trigger-gap.test.ts's two recovery-path missionStore mocks
omit getMission, which #1910's mission-active gate now walks
(getSlice → getMilestone → getMission) inside resolveFeatureMission. The throw
was swallowed by processTaskOutcome's catch, aborting recovery before it
ensured assertions / started the validator run — surfacing as
ensureFeatureAssertionLinked called 0 times. Added getMission returning an
active mission.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 19:56:06 +02:00
fusion-merge-train
c73c700e24 fix(engine): defer validator fail to inconclusive while the linked task is unmerged
A "fail" verdict from runFeatureValidation is only trustworthy once the
linked task's code has actually landed (column done/archived). When the
task is still mid-pipeline — an in-review PR, an external merge train, a
deferred base sync — the validator judged a checkout that predates the
merge and reports the work as missing, minting a duplicate Fix feature
(and board task) for code that is about to land.

Route that case to handleValidationInconclusive (R21: no Fix feature,
run completed as blocked, distinguishable verification_inconclusive
event) so a later validation judges the merged code instead.

The guard fails open: a missing/unlinked task, an unreadable task store,
or an unknown column all keep the existing handleValidationFail path —
it can only ever defer a fail on affirmative evidence of an unmerged
column, never suppress one on missing data. The vanilla done-triggered
flow (scheduler fires processTaskOutcome on toColumn === "done") is
unaffected; the guard matters for recovery-path validations and for
deployments whose tasks merge through external pipelines.

Incident context: a mission validator racing an external merge train
failed four features while their tasks were in-review, and the four
generated Fix tasks' file-scope leases on hot shared files serialized
the entire board.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-05 18:38:29 +02:00
gsxdsm
a486e0b75d fix(engine): exclude OAuth scope errors from transient-auth retry
Address review feedback on #1911:

- Greptile P1 (blocking): OAuth scope/permission failures are permanent
  (operator must re-authorize), so they are removed from the transient-auth
  classifier. A new SCOPE_ERROR_RE exclusion runs BEFORE the transient match,
  so scope errors wrapped in a generic {"type":"authentication_error"}
  envelope are also excluded instead of being retried for ~10 s.

- CodeRabbit: add a test for abort during the auth-retry sleep, covering the
  auth-specific short-circuit (the existing abort test only exercised the
  rate-limit backoff path).

- Add a regression test asserting scope errors (plain text, JSON-wrapped, and
  OAuth error codes insufficient_scope/invalid_scope) are not retried.

- Add a changeset (@runfusion/fusion: patch) — engine retry behavior ships in
  the published CLI bundle.

- Add FNXC requirement comments encoding the retry-budget invariants
  (separate auth budget, flat ~5 s delay, no rate-limit-attempt consumption,
  abort short-circuit, scope exclusion ordering).

Tests: 17/17 (rate-limit-retry). tsc --noEmit clean. eslint --fix clean.
2026-07-04 23:13:19 -07:00
gsxdsm
17c40070db fix: honor mission branchStrategy in triage; skip validation for inactive missions (#1910)
## Summary

Two related mission-loop fixes, both observed wedging a live autonomous
board.

### 1. Triage ignores `mission.branchStrategy` when `branchAssignment`
is omitted (dashboard)

`resolveBranchAssignmentContext` fabricated `{ mode: "shared" }` for
absent input, so the mission triage routes (`triage`, `triage-all`)
always passed an explicit `assignmentMode` into
`missionStore.triageFeature`/`triageSlice`. That defeats the store's
fallback — `branchOptions?.assignmentMode ??
strategyDefaults.assignmentMode` — so a mission configured with
`branchStrategy: auto-per-task` still produced a **shared** branch
group, named after the base branch.

docs/missions.md documents the intended behavior: missions "can also
persist a `branchStrategy` used whenever triage is triggered without
explicit branch options."

**Fix:** absent input resolves to `{ mode: undefined }`; callers pick
their own default. The mission routes need no change (undefined now
flows through to the strategy fallback). The two planning-subtask call
sites keep their historical `shared` default via a destructure default,
since they have no strategy to fall back to. Explicit
`branchAssignment.mode` is unchanged and still overrides the strategy.

**Observed impact:** with `baseBranch: main`, every triaged task joined
a shared group literally named `main` — tasks tried to push to `main` /
open PRs with head=main base=main, and the whole group wedged in
`merge-retries-exhausted`. The only workaround was remembering to send
`{"branchAssignment": {"mode": "per-task-derived"}}` on every triage
call, which silently ignores the mission's configured strategy the rest
of the time.

### 2. Task-completion validation runs for parked missions (engine)

`MissionExecutionLoop.processTaskOutcome` validated every completed
feature-linked task with no mission-status check — unlike
`recoverActiveMissions`, which already skips missions with `status !==
"active"`. A parked mission (`status: planning`) kept minting validator
runs, and on validator failure, new "Fix:" features — for tasks that
completed after parking. On our board a stale validator workspace
produced a `Fix: → Fix: Fix: → Fix: Fix: Fix:` spiral of bogus features
for already-merged work; the only mitigation was re-parking the mission
after every release and manually archiving the minted features.

**Fix:** gate `processTaskOutcome` on the resolved mission being active,
mirroring the `recoverActiveMissions` guard. The gate sits before the
`needs_fix → implementing` transition so an inactive mission's features
get zero state mutation; the skip logs a `warning` mission event
(`validation_skipped_mission_inactive`) so it's visible in the mission
log. Features that don't resolve to a mission keep the current behavior.

(Out of scope but worth noting: the validator that triggered the spiral
was judging merged work against a stale workspace checkout — that
freshness issue is a separate problem this PR doesn't attempt.)

## Tests

- `branch-selection.test.ts` — updated: absent/`{}` input resolves
`mode: undefined`; explicit modes and the bad-mode error unchanged.
- `mission-execution-loop.test.ts` — two new tests: parked mission skips
validation and logs the warning event; active mission still validates.
- Existing `mission-store.test.ts` coverage ("uses mission
branchStrategy … when branch options are omitted", explicit `shared`
override still creates a group) pins the store side end-to-end — those
pass unchanged, as do the planning/branch-group route suites (182 tests)
and full workspace `pnpm typecheck`.

Changeset included (`patch`, category `fix`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Branch selection now keeps an unspecified mode unset and falls back to
the mission’s configured branch strategy where appropriate.
* Task outcome processing now skips validation for missions that are not
active, preventing unnecessary follow-up actions.
* Added coverage for branch selection and mission execution behavior to
verify the updated handling.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-04 23:00:51 -07:00
fusion-merge-train
df88cb7289 fix(engine): retry transient auth errors in withRateLimitRetry
A long-running agent session holds its OAuth access token in memory. When
the token rotates mid-run (Claude Max tokens have an ~8h lifetime), the next
API call fails with 401 authentication_error and withRateLimitRetry re-throws
it immediately — the task is marked failed and the operator is paged, even
though the refreshed credentials make the very next call succeed. Observed
recurring at every ~8h token boundary, hitting whatever task or heartbeat is
in flight.

Add isTransientAuthError (authentication_error / invalid authentication
credentials / token_expired / oauth scope) with its own small retry budget:
2 retries at a flat ~5s delay (credential refresh completes within seconds,
so the 30s -> 2min rate-limit backoff curve would just prolong the outage).
Auth retries decrement the loop counter so they never consume rate-limit
attempts, and the existing rate-limit path is byte-for-byte unchanged.
Genuinely bad credentials still propagate after ~10s.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-05 05:30:12 +00:00
gsxdsm
3d58260e1a FN-7551: wire overseer decision points to engine emitOverseer* façade
Wires PlannerOverseerMonitor/PlannerRecoveryController decision points (human-control withholds, confirmation requests/resolutions, and related overseer stages) to the FN-7520 emitOverseer* façade using the real TaskStore, so the planner-oversight intervention timeline now populates from real engine activity instead of staying empty.

- Add onConfirmationResolved handler to PlannerRecoveryController, invoked (best-effort, audit-only) from resolveConfirmation for both approved and denied outcomes.
- Wire project-engine.ts to call emitOverseerObservation/emitOverseerEscalation/emitOverseerConfirmation at the real engine decision points, deduped per (task, stage[, signal]).
- Add planner-overseer-intervention-wiring.test.ts covering the new wiring end-to-end.
- Update docs/architecture.md to reflect the wiring.
- Add changeset fn-7551-overseer-timeline-wiring.md (patch).

Files changed:
 .changeset/fn-7551-overseer-timeline-wiring.md     |   7 +
 docs/architecture.md                               |   2 +-
 .../planner-overseer-intervention-wiring.test.ts   | 319 +++++++++++++++++++++
 packages/engine/src/planner-recovery-controller.ts |  36 +++
 packages/engine/src/project-engine.ts              | 248 +++++++++++++++-
 5 files changed, 607 insertions(+), 5 deletions(-)

Fusion-Task-Id: FN-7551

Fusion-Task-Lineage: 8bcd103e-8797-4ef5-9b68-bd2daec8d26b

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-04 21:28:18 -07:00
gsxdsm
654375723f FN-7521: add test coverage for planner oversight levels, overrides, and UI controls
Adds targeted regression tests covering plannerOversightLevel resolution/precedence, per-task overrides, TaskCard/TaskDetailModal oversight UI (including desktop+mobile breakpoints), lifecycle-stage monitoring, bounded recovery, confirmation gates, and human-control safeguards in the planner overseer.

- store-update.test.ts: covers remaining plannerOversightLevel enum values and per-task override precedence
- workflow-settings-resolver.test.ts: covers additional plannerOversightLevel resolution cases
- TaskCard.oversight.test.tsx: adds desktop+mobile (@media max-width: 768px) breakpoint coverage for the oversight badge, and reconciles a new mobile-breakpoint case with the FN-7542 active-overseer-state indicator removal already on main
- TaskDetailModal.oversight-controls.test.tsx: adds desktop+mobile breakpoint coverage for oversight UI controls
- planner-recovery-controller-human-control.test.ts: adds hard-cancel inertness test and verifies existing engine coverage for confirmation gates and human-control safeguards

Files changed:
 packages/core/src/__tests__/store-update.test.ts   | 25 ++++++
 .../__tests__/workflow-settings-resolver.test.ts   | 14 ++++
 .../__tests__/TaskCard.oversight.test.tsx          | 67 +++++++++++++++
 .../TaskDetailModal.oversight-controls.test.tsx    | 96 ++++++++++++++++++++++
 ...anner-recovery-controller-human-control.test.ts | 27 ++++++
 5 files changed, 229 insertions(+)

Fusion-Task-Id: FN-7521

Fusion-Task-Lineage: 87d7755b-e242-4f68-8783-835531c8d105

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-04 21:28:18 -07:00
gsxdsm
53d7b7edcd FN-7523: add git-revert engine service and task revert API route
Adds an intelligent git-revert service for done/archived tasks plus a single POST /api/tasks/:id/revert route, with tests and a changeset.

- Add packages/engine/src/task-revert.ts exporting resolveTaskRevertCommits, classifyTaskRevert, and performTaskRevert (squash/rebase/lineage attribution precedence, dry-run classification, guaranteed-clean rollback)
- Wire new revert exports into packages/engine/src/index.ts
- Add POST /api/tasks/:id/revert route in register-task-workflow-routes.ts, enforcing done/archived-only and autoMerge-off guard rails; unresolved conflicting results are left for sibling FN-7524 (AI-undo) to act on; workspace tasks return unsupported
- Add engine real-git revert tests (task-revert.real-git.test.ts) and dashboard route tests (task-revert-route.test.ts)
- Document the revert capability in docs/task-management.md
- Add .changeset/fn-7523-task-revert.md (@runfusion/fusion: patch)

Files changed:
 .changeset/fn-7523-task-revert.md                  |   7 +
 docs/task-management.md                            |   8 +
 .../src/__tests__/task-revert-route.test.ts        | 180 +++++++
 .../src/routes/register-task-workflow-routes.ts    |  75 ++-
 .../src/__tests__/task-revert.real-git.test.ts     | 248 ++++++++++
 packages/engine/src/index.ts                       |  14 +
 packages/engine/src/task-revert.ts                 | 524 +++++++++++++++++++++
 7 files changed, 1055 insertions(+), 1 deletion(-)

Fusion-Task-Id: FN-7523

Fusion-Task-Lineage: ec349d4f-cc05-48d1-9e82-8c14d1470881

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-04 21:28:18 -07:00