feat(FN-1912): merge fusion/fn-1912

This commit is contained in:
gsxdsm
2026-04-16 07:53:21 -07:00
parent 19745989cf
commit 0d507091b2
4 changed files with 174 additions and 3 deletions

View File

@@ -48,6 +48,16 @@ These fields are managed by the engine and cannot be directly edited:
- `totalInputTokens` / `totalOutputTokens` — Token usage totals (managed by engine)
- `createdAt` / `updatedAt` / `lastHeartbeatAt` — Timestamps (managed by system)
- `lastError` — Last error message (managed by engine)
- `pauseReason` — Reason for paused state (managed by engine)
### Update-Only Fields
These fields can only be set during update (not on create):
- `pauseReason` — Why the agent is paused
- `lastError` — Last error message
- `totalInputTokens` — Accumulated input token count
- `totalOutputTokens` — Accumulated output token count
## Agents View (Dashboard)
@@ -82,6 +92,23 @@ Agents can be configured with:
- Custom instructions
- Heartbeat interval/timeout limits
- Max concurrent heartbeat runs
- Budget governance settings
- Model overrides for heartbeat sessions
### Runtime Configuration Fields
The `runtimeConfig` field on agents supports the following options:
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | `boolean` | `true` | Whether heartbeat triggers are enabled for this agent |
| `heartbeatIntervalMs` | `number` | — | How often the agent should wake up for heartbeat checks (ms) |
| `heartbeatTimeoutMs` | `number` | — | Time without heartbeat before agent is considered unresponsive (ms) |
| `maxConcurrentRuns` | `number` | `1` | Max concurrent heartbeat runs for this agent |
| `messageResponseMode` | `"immediate" \| "on-heartbeat"` | `"immediate"` | How the agent responds to messages |
| `modelProvider` | `string` | — | AI provider override for heartbeat session |
| `modelId` | `string` | — | AI model ID override for heartbeat session |
| `budgetConfig` | `AgentBudgetConfig` | — | Token budget governance settings |
Heartbeat values are validated and minimum-clamped.
@@ -271,11 +298,13 @@ Behavior:
## Heartbeat Monitoring and Trigger Scheduling
Fusion's `HeartbeatTriggerScheduler` supports three trigger types:
Fusion's `HeartbeatTriggerScheduler` supports five trigger types:
- `timer` — periodic wake based on heartbeat interval
- `assignment` — wake when task is assigned to agent
- `on_demand` — manual run trigger (`POST /api/agents/:id/runs`)
- `automation` — triggered by scheduled automation jobs
- `routine` — triggered by routine execution
All triggers respect per-agent `maxConcurrentRuns` and produce structured wake context metadata.
@@ -313,7 +342,7 @@ The dashboard displays agent health status in AgentsView, AgentListModal, and Ag
| **Terminated** | Agent state is "terminated" |
| **Error** | Agent state is "error" (uses lastError if available) |
| **Paused** | Agent state is "paused" (uses pauseReason if available) |
| **Running** | Agent state is "running" |
| **Running** | Agent state is "running" (task workers with `active` state also display "Running") |
| **Disabled** | `runtimeConfig.enabled === false` |
| **Starting...** | State is "active" with no lastHeartbeatAt |
| **Idle** | Non-active state with no lastHeartbeatAt |
@@ -386,6 +415,100 @@ POST /api/agents/:id/runs/stop → 200 { ok: true, runId: "run-xxx" }
If there's no active run, returns `{ ok: true, message: "No active run" }`.
## Budget Governance
Per-agent token budget tracking controls costs and prevents runaway AI spending. Budget configuration is stored in `runtimeConfig.budgetConfig`.
### Budget Configuration Fields
| Field | Type | Description |
|-------|------|-------------|
| `tokenBudget` | `number` | Maximum tokens allowed per budget period |
| `usageThreshold` | `number` (0-1) | Percentage threshold (0.8 = 80%) to trigger warning/warning state |
| `budgetPeriod` | `"daily" \| "weekly" \| "monthly" \| "total"` | Reset interval for budget tracking |
| `resetDay` | `number` (0-6) | Day of week for weekly reset (0=Sunday) |
### Budget Status Fields
| Field | Type | Description |
|-------|------|-------------|
| `isOverBudget` | `boolean` | Budget limit exceeded |
| `isOverThreshold` | `boolean` | Usage exceeded warning threshold |
| `periodStart` | `string` | ISO timestamp when current period started |
| `inputTokens` | `number` | Tokens used in current period |
| `outputTokens` | `number` | Tokens generated in current period |
| `totalTokens` | `number` | Combined input + output tokens |
### Enforcement Behavior
Budget enforcement happens at multiple points:
- `HeartbeatMonitor.executeHeartbeat()` checks budget before creating sessions; skips when `isOverBudget: true` or `isOverThreshold: true` (for timer triggers)
- `HeartbeatTriggerScheduler.onTimerTick()` skips timer ticks when budget is exceeded
Agents can be paused by budget exhaustion. Timer-triggered heartbeats skip when over threshold to avoid runaway costs, but assignment-triggered and on-demand runs may still execute for responsiveness.
### Budget API Endpoints
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/agents/:id/budget` | Get current budget status |
| `POST` | `/api/agents/:id/budget/reset` | Reset budget counters for current period |
## Agent Performance Ratings
Agent performance ratings allow users and agents to provide feedback that influences future behavior through system prompt injection.
### Rating API Endpoints
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/api/agents/:id/ratings` | List all ratings for an agent |
| `POST` | `/api/agents/:id/ratings` | Submit a new rating |
| `GET` | `/api/agents/:id/ratings/summary` | Get aggregated rating summary |
| `DELETE` | `/api/agents/:id/ratings/:ratingId` | Delete a specific rating |
### Rating Structure
Ratings use a 1-5 scale:
| Value | Meaning |
|-------|---------|
| 1 | Poor — consistently fails or produces low-quality output |
| 2 | Below average — often needs correction |
| 3 | Average — meets expectations with occasional issues |
| 4 | Good — reliable with minor improvements possible |
| 5 | Excellent — exceeds expectations consistently |
### Rating Summary
The summary endpoint returns aggregated statistics:
```json
{
"agentId": "AGENT-001",
"averageRating": 4.2,
"totalRatings": 15,
"ratingDistribution": { "1": 0, "2": 1, "3": 2, "4": 8, "5": 4 },
"trend": "improving"
}
```
The `trend` field indicates rating trajectory: `"improving"`, `"declining"`, or `"stable"`.
### Input Format
To submit a rating:
```
POST /api/agents/:id/ratings
{
"rating": 4,
"comment": "Agent completed the task efficiently with minimal corrections needed",
"taskId": "FN-123"
}
```
## Related Docs
- [Workflow Steps](./workflow-steps.md)

View File

@@ -357,6 +357,25 @@ Key server capabilities:
- `SubtaskBreakdownModal.tsx`
- Multi-task creation endpoints are wired under planning/subtask routes in `routes.ts`
### Health and monitoring endpoints
- **Health check**: `GET /api/health`
- Returns liveness status for load balancers and monitoring
- Response: `{ status: "ok", version: string, uptime: number }`
- No authentication required
### Run Audit API
The run-audit system records every mutation performed by the engine across three domains:
- **Database** — task:create, task:update, task:move, etc.
- **Git** — worktree:create, commit:create, merge:resolve, etc.
- **Filesystem** — file:write, prompt:write, attachment:create, etc.
Events are tied to specific run IDs for end-to-end traceability.
**Run audit endpoint:**
- `GET /api/agents/:id/runs/:runId/audit` — Returns audit trail for a specific agent run
- Query params: `?domain=database|git|filesystem` for filtering
- Requires agent ownership or admin access
---
## 7) CLI Package (`@gsxdsm/fusion`)

View File

@@ -57,7 +57,7 @@ fn dashboard --dev
Start Fusion as a headless node (API server + AI engine, no frontend UI).
```bash
fn serve [--port <port>] [--host <host>] [--paused]
fn serve [--port <port>] [--host <host>] [--paused] [--daemon]
fn serve --interactive
```
@@ -67,6 +67,26 @@ fn serve --interactive
| `--host` | Host to bind (default `0.0.0.0`, all interfaces). |
| `--paused` | Start with engine paused (automation disabled). |
| `--interactive` | Interactive port selection. |
| `--daemon` | Enable bearer token authentication for CLI client connections. |
---
## `fn daemon`
Start Fusion daemon (API server + AI engine, always requires bearer token authentication).
```bash
fn daemon [--port <port>] [--host <host>] [--token <token>] [--paused] [--token-only]
```
| Option | Description |
|---|---|
| `--port`, `-p` | Port for the daemon server (default: auto-assigned). |
| `--host` | Host to bind (default `0.0.0.0`, all interfaces). |
| `--token` | Set a specific daemon token. If not provided, a random token is generated and printed. |
| `--paused` | Start with engine paused (automation disabled). |
| `--token-only` | Only generate/show the token without starting the server. |
| `--interactive` | Interactive port selection. |
---

View File

@@ -53,6 +53,9 @@ Defaults from `DEFAULT_GLOBAL_SETTINGS`; key scope from `GLOBAL_SETTINGS_KEYS`.
| `validatorGlobalModelId` | `string` | `undefined` | Global baseline AI model ID for validator/reviewer. |
| `titleSummarizerGlobalProvider` | `string` | `undefined` | Global baseline AI provider for title summarization. Project `titleSummarizerProvider` overrides this. |
| `titleSummarizerGlobalModelId` | `string` | `undefined` | Global baseline AI model ID for title summarization. |
| `daemonToken` | `string` | `undefined` | The daemon authentication token (format: `fn_<32 hex chars>`). Used for authenticating CLI clients to the daemon server. |
| `daemonPort` | `number` | `4040` | Port for daemon mode server binding. |
| `daemonHost` | `string` | `"0.0.0.0"` | Host for daemon mode server binding (all interfaces by default). |
### Additional GlobalSettings fields
@@ -75,6 +78,8 @@ Defaults from `DEFAULT_PROJECT_SETTINGS`; key scope from `PROJECT_SETTINGS_KEYS`
| `globalPause` | `boolean` | `false` | Hard stop: terminate active engine sessions and pause scheduling. |
| `enginePaused` | `boolean` | `false` | Soft pause: stop dispatching new work but allow active sessions to finish. |
| `maxConcurrent` | `number` | `2` | Max concurrent task-lane AI agents (triage, executor, merge). Utility AI workflows run on a separate control-plane lane and are not gated by this limit. |
| `maxTriageConcurrent` | `number` | `2` | Max concurrent triage/specification agents. When undefined, falls back to `maxConcurrent`. |
| `globalMaxConcurrent` | `number` | `4` | System-wide maximum concurrent agents across ALL projects. When multiple projects are active, the sum of their in-flight agents will not exceed this limit. |
| `maxWorktrees` | `number` | `4` | Max git worktrees. |
| `pollIntervalMs` | `number` | `15000` | Scheduler poll interval (ms). |
| `groupOverlappingFiles` | `boolean` | `true` | Serialize execution when file scopes overlap. |
@@ -87,6 +92,9 @@ Defaults from `DEFAULT_PROJECT_SETTINGS`; key scope from `PROJECT_SETTINGS_KEYS`
| `worktreeNaming` | `"random" \| "task-id" \| "task-title"` | `"random"` | Naming mode for fresh worktree directories. |
| `taskPrefix` | `string` | `"FN"` | Prefix for generated task IDs. |
| `includeTaskIdInCommit` | `boolean` | `true` | Include task ID in commit message scope. |
| `commitAuthorEnabled` | `boolean` | `true` | When true, Fusion adds `--author` attribution to all commits it creates. |
| `commitAuthorName` | `string` | `"Fusion"` | Name used in the git `--author` flag for Fusion commits. Only used when `commitAuthorEnabled` is true. |
| `commitAuthorEmail` | `string` | `"noreply@runfusion.ai"` | Email used in the git `--author` flag for Fusion commits. Only used when `commitAuthorEnabled` is true. |
| `defaultProviderOverride` | `string` | `undefined` | Project-level override for base default provider. Overrides global `defaultProvider`. |
| `defaultModelIdOverride` | `string` | `undefined` | Project-level override for base default model ID. |
| `executionProvider` | `string` | `undefined` | AI provider for task execution. Overrides `executionGlobalProvider`. |
@@ -106,6 +114,7 @@ Defaults from `DEFAULT_PROJECT_SETTINGS`; key scope from `PROJECT_SETTINGS_KEYS`
| `smartConflictResolution` | `boolean` | `true` | Alias/preferred flag for smart merge conflict handling. |
| `strictScopeEnforcement` | `boolean` | `false` | Block merges on out-of-scope file changes. |
| `buildRetryCount` | `number` | `0` | Build retry attempts during merge. |
| `verificationFixRetries` | `number` | `1` | Number of automatic retry attempts when deterministic verification fails during merge. |
| `buildTimeoutMs` | `number` | `300000` | Build timeout in ms (5 minutes). |
| `requirePlanApproval` | `boolean` | `false` | Require manual approval before triage → todo. |
| `reviewHandoffPolicy` | `"disabled" \| "comment-triggered" \| "always"` | `"disabled"` | Policy for agent-to-user review handoff. |