Commit Graph

754 Commits

Author SHA1 Message Date
gsxdsm
9113f51f69 fix(core): recognize legacy kb-* backups and canonicalize .kb/backups settings
- BackupManager.listBackups now matches kb-* and kb-pre-restore-* filenames
  alongside the fusion-* pattern, parsing timestamps from either prefix.
- canonicalizeSettings rewrites autoBackupDir: ".kb/backups" to
  ".fusion/backups" so projects upgraded from the old brand keep working
  (custom .kb/* paths remain untouched).
- createBackupManager applies the same canonicalization to settings it
  receives, so the factory path also produces backups under .fusion/backups.
- Re-export getErrorMessage from core/src/types.ts so the dashboard's vite
  "@fusion/core" alias (which points at types.ts) resolves the symbol for
  client-side consumers — fixes the mobile build-output test.

Clears all 8 pre-existing kb → fn rename failures plus the 1 test that
regressed from the new getErrorMessage import surfacing the vite alias gap.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:37 -07:00
gsxdsm
4cabe7f613 refactor: eliminate ~400 no-explicit-any warnings across the workspace
Parallel subagent pass: four typescript-pro agents on non-overlapping scopes.

Patterns applied:
- catch (err: any) { ... err.message ... } → catch (err) { ... getErrorMessage(err) ... }
  using the new @fusion/core helper. Bare catch {} where the error was unused.
- SQLite row types: defined typed XxxRow interfaces per table and cast
  .all()/.get() results via `as unknown as XxxRow[]` (the double cast is
  required because better-sqlite3 returns Record<string, SQLOutputValue>).
- rowToX(row: any) converters: typed argument with the matching row interface.
- Dynamic settings key writes: (settings as Record<string, unknown>)[key].
- React event handlers and setState callbacks: inferred types or concrete
  React.{Mouse,Change,Form}Event<...> where needed.
- pi-claude-cli: local PiMessage / PiContext duck types to avoid re-typing
  pi-ai concrete shapes; typed Claude stream event message fields.

72 files changed, ~400 anys eliminated. Typecheck passes across the workspace.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:36 -07:00
gsxdsm
d1bd02b2c9 feat(core): add getErrorMessage helper for narrowing unknown errors
Designed to replace the \`catch (err: any) { ... err.message ... }\` pattern
across the repo. Keeps the catch binding typed as \`unknown\` (TS default)
while still producing a readable message.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:36 -07:00
gsxdsm
651c5678d2 refactor: fix and tighten mechanical lint rules
- no-useless-escape: drop needless backslashes in character classes and
  URL/path regexes (gh-cli, store, task, modelFilter, useFileMention,
  RoutineEditor, ScheduleForm).
- no-case-declarations: wrap case bodies in ProjectOverview and
  SettingsModal with block scopes.
- prefer-const: convert a never-reassigned slug binding in agent-import;
  annotate legitimate forward-declared let bindings in dashboard.ts that
  callbacks close over before assignment.
- no-fallthrough: add missing break after settings-subcommand error.
- no-empty-interface/no-empty-object-type: convert ProjectManifest from
  empty interface extension to a type alias.
- no-unused-expressions: replace `x && x.method()` short-circuits in
  TerminalModal with optional chaining.

Then ratchet these rules from warn → error so regressions are blocked.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:36 -07:00
gsxdsm
b818aa2196 refactor(core): remove unused imports, helpers, and dead migration constant
Drops orphaned imports and the never-referenced V4 migration SQL constant
(V4 was inlined into runMigrations). Also drops the unused TypedEventEmitter
helper type and unused destructured values from stores.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:35 -07:00
gsxdsm
f20d0b5a18 refactor: remove legacy kb compatibility
Drops the .kb/kb.db migration path, legacy backup filename handling, and
backward-compat test suites. Renames internal kbDir identifiers to
fusionDir and hasKbProject/isValidKbProject to their fusion equivalents.

- Remove needsCentralMigration, autoMigrateToCentral, and the
  "needs-migration" FirstRunState; checkAndMigrate and KB_SKIP_MIGRATION
  env var are gone
- Remove LEGACY_BACKUP_DIR and canonicalizeBackupDir; listBackups no
  longer matches kb-* filenames
- Delete backward-compat.test.ts and store-backward-compat.test.ts;
  update remaining tests to new 3-state first-run model

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:34 -07:00
Fusion
51870ed27b fix: prevent nested .fusion/.fusion dir from PluginStore path bug
PluginStore's constructor treats its rootDir arg as a project root and
internally appends `.fusion` before opening the SQLite DB. Several CLI
call sites were passing the already-resolved `.fusion` directory,
producing a doubled `.fusion/.fusion/fusion.db` that the dashboard
process kept recreating on every project load.

Pass the project root instead so the DB lands in the canonical
`.fusion/fusion.db` alongside the rest of the project's state.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:02:33 -07:00
Fusion
c6842c9bab fix(FN-2326): harden TaskStore observability logging paths
- Add a task-store logger and funnel activity listeners through a shared helper that logs source-event failures
- Replace silent catches with structured warn/error logs for workflow default resolution, title summarization, fs.watch, and polling paths
- Preserve best-effort behavior for activity recording and async summarization while attaching actionable error context
- Expand TaskStore tests to validate logging behavior for activity insert failures, listener rejections, workflow fallback, and watch/poll error handling
2026-04-23 12:36:52 -07:00
Fusion
445bdb2eea feat(FN-2328): add manager dropdown for agent reports-to setting
- Replace free-text Reports To input with a manager select populated from fetched agents
- Exclude the current agent from manager candidates and preserve unknown manager IDs as a fallback option
- Save selected manager IDs through updateAgent, including clearing reportsTo when No manager is selected
- Expand AgentDetailView settings tests for manager selection behavior and increase task document cascade test timeout stability
2026-04-23 12:23:56 -07:00
gsxdsm
bbdd11aab3 fix: guard SQLite FTS5 at runtime and fall back to LIKE search
On Node builds whose bundled node:sqlite was compiled without
SQLITE_ENABLE_FTS5 (older 22.x LTS), `fn dashboard` crashed on first
run with `Error: no such module: fts5` during schema migration 21.

Database and ArchiveDatabase now probe FTS5 at startup via a disposable
virtual table. When unavailable, migrations 21 and 35 skip the tasks_fts
DDL, ArchiveDatabase skips the archived_tasks_fts block, and
TaskStore.searchTasks / ArchiveDatabase.search fall back to LIKE scans
over id/title/description/comments with ESCAPE-aware patterns.

Set FUSION_DISABLE_FTS5=1 to force the fallback on runtimes where FTS5
is available but undesirable (e.g. reproducing fresh-install behavior
in tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:05:35 -07:00
Fusion
879f8a2e04 fix(FN-2313): make PR auth checks gh-first across settings UI
- Replace the server-computed settings flag with prAuthAvailable and document it in shared Settings types
- Compute PR auth availability from gh CLI auth first, with GITHUB_TOKEN as fallback in GET /api/settings
- Rename dashboard settings state/props/hooks from githubTokenConfigured to prAuthAvailable and strip server-owned auth fields on save
- Update PR section messaging to guide users to run 'gh auth login' and refresh related route/component tests
2026-04-23 10:58:36 -07:00
Fusion
86fd24e1d0 feat(FN-2311): default dashboard TUI to system section
- Reorder dashboard TUI sections so System is tab [1] and the initial active view
- Update header rendering across wide, medium, and narrow terminal layouts to reflect the new tab order
- Expand dashboard TUI tests to assert system-first labels and default active section behavior
- Document system-first startup behavior in CLI reference and add a patch changeset for @runfusion/fusion
2026-04-23 10:43:45 -07:00
gsxdsm
29056b412d fix(FN-2251): default durable agent heartbeats on 2026-04-23 09:42:54 -07:00
gsxdsm
70ad1836d0 fix(FN-2293): increase task_done retries and requeue immediately 2026-04-23 08:03:28 -07:00
gsxdsm
0538331c34 feat(FN-2279): merge fusion/fn-2279 2026-04-22 23:01:34 -07:00
gsxdsm
b72ff64a67 feat(merger): rebase task branch onto remote before merge
Adds a new worktree setting that fetches the configured remote and rebases
the task branch onto the latest default-branch tip before the merger attempts
to merge it back. Catches concurrent pushes from other collaborators or
fusion workers on other hosts before they surface as merge conflicts —
anything the rebase can't fast-forward flows into the existing smart/AI
resolve pipeline (attempts 1–3) rather than needing new handling.

- `settings.worktreeRebaseBeforeMerge` (bool, default true) — gates the step.
- `settings.worktreeRebaseRemote` (string, default "") — which remote to
  fetch; empty falls back to git's configured remote for the default branch,
  then to the sole remote if there's only one, then to "origin".
- Rebase runs inside the task's worktree; failure aborts and falls through
  to the merge cascade. Rebase errors are warn-logged but never throw.
- Dashboard SettingsModal Worktrees section now has a toggle for the setting
  plus a remote dropdown populated from `/api/git/remotes/detailed`. The
  dropdown defaults to "Use git default" so no explicit selection is needed
  on first configure.

Also aligns the Last/Next heartbeat spans on the agent list card — both now
share the `.agent-heartbeat-last, .agent-heartbeat-next, .agent-heartbeat-saving`
font-size rule with a consistent line-height and inline-flex alignment so
the labels don't drift vertically when they share a row.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 22:17:33 -07:00
gsxdsm
22d31c4cac fix: --no-auth override, workflow revision in-place fix, state-driven heartbeats
Three orthogonal fixes bundled together so they re-land as a unit after
earlier worktree-based reverts kept wiping them individually.

1. `--no-auth` flag now actually disables auth. Previously a stale
   FUSION_DAEMON_TOKEN in .env silently re-armed bearer-token auth despite
   the CLI flag. Added a `noAuth` option to ServerOptions; auth-middleware's
   isDaemonAuthActive/getDaemonToken short-circuit to false/undefined when
   set; CLI plumbs opts.noAuth through both createServer call sites.

2. Workflow review failures no longer reset every completed step. Previously
   a single CSS nit from a workflow reviewer could drag 5+ already-approved
   steps back through plan review, code review, and re-execution because
   determineRevisionResetStart fuzzy-matched feedback tokens against step
   names. handleWorkflowRevisionRequest, handleWorkflowStepFailure, and
   sendTaskBackForFix now call a new reopenLastStepForRevision helper that
   flips only the last non-pending step back to pending (with currentStep
   rewind via a newly-accepted updateTask field) — all earlier done steps
   stay done, and the agent applies the feedback as an in-place patch per
   the updated PROMPT.md instructions. determineRevisionResetStart stays
   exported as @deprecated so existing unit tests still link.

3. Heartbeat scheduling is now state-driven. Previously a non-ephemeral
   agent with a stale runtimeConfig.enabled=false on disk would never tick
   and the Pause/Resume button couldn't arm the timer without also flipping
   that hidden flag. HeartbeatTriggerScheduler's watchAgentLifecycle now
   registers on transitions into active/running and clears on transitions
   out; the tick and assignment-trigger guards key off state + ephemeral
   classification. InProcessRuntime's created/updated listeners and startup
   scan mirror the same semantics. runtimeConfig.enabled is only retained
   for ephemeral (task-worker) opt-out.

Tests updated: agent-heartbeat.test.ts — one test renamed from "skips
registration when enabled is false" (obsolete behavior) to
"registers regardless of the legacy enabled flag"; 4 assignment-watching
tests now pass a realistic `state: "active"` on mock agents. 207 heartbeat
tests + 330 executor tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 22:12:19 -07:00
gsxdsm
124a9daacc feat(FN-2274): add engine-level stale-task safeguards in heartbeat execution
- HeartbeatMonitor.executeHeartbeat() now checks if resolved task is done/archived
  and exits before session creation with reason 'task_closed'
- When stale task came from persisted agent.taskId, clears the linkage to prevent
  repeated stale activations
- HeartbeatTriggerScheduler.watchAssignments() now skips assignment callback dispatch
  when assigned task is done/archived (when taskStore is available)
- Added comprehensive tests for stale-task activation guard behavior
2026-04-22 21:14:44 -07:00
gsxdsm
9ca6b9174b fix(FN-000): backup routine uses npx runfusion.ai; alias exposes fn/fusion
Backup automation now emits `npx runfusion.ai backup --create` so scheduled
backups work for users on the zero-install path where `fn` is not on PATH.

`runfusion.ai` also exposes `fn` and `fusion` bins, so `npm i -g runfusion.ai`
puts them on PATH (npm does not link dep bins globally). Alias only defaults
to the dashboard when invoked as `runfusion.ai` / `runfusion`; `fn` / `fusion`
forward args verbatim so bare `fn` still prints help.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 19:19:07 -07:00
Fusion
e079704211 feat(FN-2269): migrate dashboard session selection to global settings
- Add global settings schema/types fields for persisted dashboard session state (selected project and node)
- Refactor NodeContext and current-project hooks to read/write project and node selection via global settings instead of project-local state
- Update App wiring to use the new selection flow across dashboard startup and switching behavior
- Add and expand dashboard tests for NodeContext, useCurrentProject, and view-state persistence behavior
2026-04-22 17:12:27 -07:00
Fusion
313a5e6385 test(dashboard): realign DevServer tests with session-based component
- DevServerView.preview.test.tsx: drop manual-preview-override assertion
  (the component hard-codes isManualPreviewOverride=false under the new
  session model, so the badge is always "Auto"), provide both legacy and
  current-API fields from createDevServerHookState, and mirror
  embedContext into blockReason in createPreviewEmbedState so the
  fallback panel picks up the reason text under the new destructure.
- runtime-adapter.test.ts: skip the createSession / promptWithFallback /
  describeModel blocks with a TODO — the adapter loads pi.js via
  CommonJS require() which vi.mock does not intercept, so the mocked
  module is never actually installed. Needs a dynamic import seam
  before these can run; tracking separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 16:31:30 -07:00
Fusion
841193d215 feat(FN-2255): add plugin runtime discovery contracts
- Extend core/plugin-sdk types with runtime manifest metadata, runtime factory, and runtime registration exports
- Add runtime validation in plugin manifest parsing, including runtimeId slug and semver checks
- Add PluginLoader.getPluginRuntimes() and PluginRunner runtime cache/invalidation plumbing across plugin lifecycle events
- Expand plugin loader/runner test coverage for runtime discovery and cache behavior, and document runtime registration in PLUGIN_AUTHORING.md
2026-04-22 13:01:25 -07:00
Fusion
086dbe80bd feat(FN-2246): add executionMode support to task APIs and storage
- Add ExecutionMode type contracts and executionMode field to core task interfaces
- Persist executionMode through SQLite schema mappings and TaskStore read/write paths
- Validate executionMode in dashboard route handlers and API request handling
- Expand core and dashboard test coverage for executionMode persistence and route behavior
2026-04-22 10:34:11 -07:00
Fusion
435fb60c98 feat(FN-2241): add review level selection in task creation and editing
- Extend core task types/store and dashboard API route handling to persist task reviewLevel
- Add review level controls to TaskForm, NewTaskModal, and TaskDetailModal flows
- Improve workflow step selector presentation in WorkflowResultsTab and styles for clearer review settings UX
- Document the new review level behavior and add route/form/modal tests to cover create and edit scenarios
2026-04-22 09:23:57 -07:00
gsxdsm
656f34c3dd fix(FN-LOCAL): remove done-file prompt and stale local artifacts 2026-04-22 00:22:49 -07:00
gsxdsm
7e3c68249e feat(dashboard): bearer-token auth with browser persistence + MIT license
Pre-release polish. Two related changes bundled because they both land the
project on public-release footing:

Dashboard auth
- fn dashboard now gates the HTTP API + terminal/badge WebSockets behind a
  bearer token by default. Token resolution order: --token flag,
  FUSION_DASHBOARD_TOKEN env, FUSION_DAEMON_TOKEN env (back-compat), or an
  auto-generated fn_<32 hex>. --no-auth disables. The startup banner prints
  a click-to-open URL with ?token=<token> embedded.
- Auth middleware now also accepts fn_token=<token> as a query-string
  fallback so EventSource and WebSocket clients (which can't set custom
  headers) still authenticate.
- setupTerminalWebSocket / setupBadgeWebSocket now refuse unauthenticated
  upgrades with a proper 401 + socket close.
- Frontend: new auth.ts module captures ?token= off the URL into
  localStorage (key fn.authToken), strips it from the visible URL via
  replaceState, and installs a window.fetch wrapper that injects
  Authorization: Bearer <token> on every same-origin /api/* request.
  EventSource/WebSocket URL builders (api.ts, sse-bus.ts, useTerminal,
  useBadgeWebSocket) route through appendTokenQuery().

MIT license
- LICENSE file at repo root.
- license: "MIT" on root package.json and every packages/*/package.json,
  plus description/bugs metadata on the CLI package.

Docs
- docs/cli-reference.md documents --token / --no-auth / FUSION_DASHBOARD_TOKEN
  and the click-to-open auth flow.
- docs/getting-started.md, docs/docker.md, README.md point at the new flow
  and the CLI reference section.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 20:12:00 -07:00
Fusion
c21e6fef15 perf(executor): recover approved steps on engine restart
When the engine restarts mid-step, an in-progress step may have already
passed plan + code review but not yet been flipped to done by the agent's
next task_update call. Previously, the next executor pass re-entered the
step and replayed both reviews — measured at 5-20 min of pure waste per
restart (observed in FN-2215 Step 1 and FN-2207 Step 6).

recoverApprovedStepsOnResume scans the task log for any in-progress step
whose most recent "code review Step N: APPROVE" entry is newer than its
most recent "Step N → pending" transition, and marks those steps done
before execute() runs. Safely skips steps that were reset after approval
(e.g. by a workflow revision) or only received REVISE verdicts.

Called from both the engine-restart path (resumeOrphaned) and the
unpause path, matching the two places the task log shows as vulnerable
to this race.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 20:12:00 -07:00
Fusion
fd83cc6fd5 fix(FN-2210): classify legacy verification agents as ephemeral
- Extend isEphemeralAgent to treat metadata.internal agents as internal system agents
- Add legacy fallback detection for executor agents named verification-agent with no reportsTo
- Update AgentsView list and org tree filtering to honor the Show system agents toggle
- Add regression coverage in core and dashboard tests for default filtering and includeEphemeral visibility
2026-04-21 02:40:50 -07:00
Fusion
42476ec3da feat(FN-2166): persist dev server script configuration across sessions
- Extend dev server store with config defaults, normalization, and JSON persistence alongside runtime state.
- Add GET/PUT /api/dev-server/config endpoints with strict request validation for nullable fields and preview URLs.
- Add dashboard API helpers plus a useDevServerConfig hook to load and update selected script, source, command, and preview override.
- Update DevServerView and styles to support saved script selection, change/clear actions, and synchronized command/preview inputs.
- Expand dev server store/routes/component tests and document the config endpoint in architecture docs.
2026-04-20 12:59:58 -07:00
gsxdsm
ed235c1edf fix(engine): recoverable worktree failures + prevent nested/gitlink worktrees
Fixes two classes of task failures found while investigating stuck in-review
tasks FN-2165 (worktree base ref missing) and FN-2152 (stray .tmp-fn-2152
gitlink accidentally committed via merger amend).

FN-2165 — stale baseBranch:
- resolveWorktreeStartPoint now returns null instead of throwing
  NonRetryableWorktreeError when the stored baseBranch is gone. Caller clears
  task.baseBranch and falls back to branching from the default base (HEAD) so
  the task self-heals instead of failing permanently.
- New TaskStore.clearStaleBaseBranchReferences() nulls baseBranch on any
  dependent task when its upstream branch is deleted. Wired into
  cleanupBranchForTask (archive/delete), merger branch cleanup, self-healing
  orphan-branch sweep, executor dep-abort and conflict-cleanup paths, and
  stale-branch recovery.

Nested worktrees:
- assertWorktreePathNotNested guard in tryCreateWorktree refuses to create a
  worktree inside another registered worktree (previously produced pathological
  paths like .worktrees/green-finch/.worktrees/amber-panda when rootDir pointed
  at a worktree instead of the main repo).

Context-overflow recovery (FN-2182 class):
- Reduced-prompt retry budget raised from 1 → 3 within the same session.
- Adds a fresh-session requeue path when same-session retries still overflow:
  task moves back to todo with worktree retained, bounded by
  computeRecoveryDecision / MAX_RECOVERY_RETRIES. Prevents late-step context
  exhaustion from becoming terminal.

Gitlink prevention (FN-2152 class):
- .gitignore now excludes .tmp-fn-* and .tmp-kb-* so stray worktrees at the
  repo root cannot be captured by git add -A.
- Merger amend flow now scans staged entries for 160000 gitlinks and unstages
  them with a loud warning; the project uses no submodules, so any such entry
  is a bug (this is how f8f90f26 landed in HEAD as .tmp-fn-2152).

Tests: new coverage for baseBranch fallback, nested-worktree guard, and
clearStaleBaseBranchReferences. Full engine + core + dashboard + cli suites
pass (15349 tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 08:30:24 -07:00
Fusion
e8b0ed5627 fix(triage): prevent orphaned deps when splitting tasks + detect worktree drift
Root cause: during a triage split the AI could set a child task's
`dependencies` to the parent id. The parent is hard-deleted after the split,
and the scheduler's dep check treats a missing id as unmet — permanently
blocking the dependent. This stranded FN-2164 behind the deleted FN-2163.

- core/store.deleteTask: refuse to delete when any live task still has the id
  in its `dependencies` array. Throws TaskHasDependentsError listing dependents
  so callers can rewrite or recover. Covers the triage-split path and any
  future caller.
- engine/triage task_create: validate each proposed dependency before creating
  a child — reject the parent id, reject unknown task ids, allow siblings
  created earlier in the same split or pre-existing tasks.
- engine/triage split cleanup: wrap the parent deleteTask in try/catch that
  keeps the parent alive (safer than stranding dependents) and logs the reason.
- engine/triage prompts: both the mandatory-split and proactive-split prompts
  now explicitly state that subtask deps must never reference the parent.
- dashboard/routes /subtasks/create-tasks: reject parent-id deps, drop unknown
  deps with an audit log entry, surface parentTaskCloseError + droppedDependencies
  in the response instead of silently swallowing them.
- engine/executor: on execute entry, detect the drift state (in-progress task
  with no worktree) and emit a loud log + task log entry; the existing
  fresh-worktree path then recovers. Prevents silent "operating without a
  worktree" behavior that we saw on FN-2152.

Tests:
  core:      2907/2907 pass (+5 new, incl. deleteTask guard regression)
  engine:    2554/2554 pass (+17 new, incl. task_create dep validation)
  dashboard: 9064/9064 pass (+2 new for /subtasks/create-tasks).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 08:30:24 -07:00
gsxdsm
f530a69955 fix(triage): prevent orphaned deps when splitting tasks + detect worktree drift
Root cause: during a triage split the AI could set a child task's
`dependencies` to the parent id. The parent is hard-deleted after the split,
and the scheduler's dep check treats a missing id as unmet — permanently
blocking the dependent. This stranded FN-2164 behind the deleted FN-2163.

- core/store.deleteTask: refuse to delete when any live task still has the id
  in its `dependencies` array. Throws TaskHasDependentsError listing dependents
  so callers can rewrite or recover. Covers the triage-split path and any
  future caller.
- engine/triage task_create: validate each proposed dependency before creating
  a child — reject the parent id, reject unknown task ids, allow siblings
  created earlier in the same split or pre-existing tasks.
- engine/triage split cleanup: wrap the parent deleteTask in try/catch that
  keeps the parent alive (safer than stranding dependents) and logs the reason.
- engine/triage prompts: both the mandatory-split and proactive-split prompts
  now explicitly state that subtask deps must never reference the parent.
- dashboard/routes /subtasks/create-tasks: reject parent-id deps, drop unknown
  deps with an audit log entry, surface parentTaskCloseError + droppedDependencies
  in the response instead of silently swallowing them.
- engine/executor: on execute entry, detect the drift state (in-progress task
  with no worktree) and emit a loud log + task log entry; the existing
  fresh-worktree path then recovers. Prevents silent "operating without a
  worktree" behavior that we saw on FN-2152.

Tests:
  core:      2907/2907 pass (+5 new, incl. deleteTask guard regression)
  engine:    2554/2554 pass (+17 new, incl. task_create dep validation)
  dashboard: 9064/9064 pass (+2 new for /subtasks/create-tasks).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 20:48:14 -07:00
Fusion
0b9bf62a2a refactor(FN-2162): rename kb-agent identifiers to fn-agent
- Rename core loader, dashboard server chat/planning routes, and frontend agent IDs/storage keys from kb-agent to fn-agent naming
- Update dashboard hooks and components (agent list, chat view, quick chat) to use the new fn agent key prefixes consistently
- Refresh engine, dashboard, core, and CLI tests/mocks to remove remaining kb-agent route and temp prefix references
- Update storage/gap-analysis docs to reflect fn agent key names and add a @gsxdsm/fusion patch changeset for the rename
2026-04-19 20:48:14 -07:00
Fusion
a929b729b9 refactor(FN-2161): standardize on createFnAgent naming
- Rename engine export and call sites to use createFnAgent consistently across runtime flows
- Update core lazy engine loader and dashboard agent-generation/planning/chat paths to reference createFnAgent
- Refresh affected unit and integration tests, including renaming pi-create-kb-agent.test.ts to pi-create-fn-agent.test.ts
- Update AGENTS.md documentation references to match the new createFnAgent name
2026-04-19 20:48:14 -07:00
Fusion
5b6392d849 feat(FN-2156): migrate agent log storage to SQLite
- Add an agentLogEntries table and schema migration updates for SQLite-backed agent log persistence
- Persist appended agent logs in SQLite and read task agent logs from the database instead of filesystem-only JSONL
- Import legacy agent log JSONL data into SQLite with type-safe handling for older log field shapes
- Preserve agent logs across task updates and archive flows, and update docs plus tests (including schema assertions) to cover the new behavior
- Add a changeset for @gsxdsm/fusion describing the agent log storage migration
2026-04-19 20:48:13 -07:00
gsxdsm
3f8161a90a refactor: low-regret cleanup across core, engine, dashboard
- core: extract ai-engine-loader.ts to share @fusion/engine dynamic-import
  boilerplate between ai-summarize and memory-compaction (incl. AgentMessage
  type); collapse getInbox/getOutbox, listInsights/countInsights,
  listRuns/countRuns, and three hasProjectDb* variants behind shared helpers.
- core: drop unused pluginLoaderLog export; tighten two `any` casts
  (db.walCheckpoint row, plugin-loader error.code).
- engine: extract resolveRoleFallback helper from buildSessionSkillContext/Sync;
  remove 22 stale `eslint-disable no-explicit-any` directives across
  project-engine, self-healing, triage, worktree-pool.
- dashboard: apply ESLint autofix (let→const, empty `interface extends`→type).

All three packages: typecheck clean, full test suites pass (14,414 tests),
builds clean. Net lint: -31 warnings. No public behavior changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 20:48:13 -07:00
Fusion
a93f0f2ef9 feat(FN-2160): add push-after-merge remote sync workflow
- Add project settings for pushAfterMerge and pushRemote with defaults and typed merge result fields for push status/errors
- Implement post-merge remote sync in the merger with pull --rebase, auto/AI conflict resolution, and one non-fast-forward retry before push
- Expose push-after-merge controls in Settings modal with conditional Push Remote input and coverage for desktop/mobile save flows
- Document the new settings in the settings reference and stabilize CLI cross-build help test timeout
2026-04-19 20:48:13 -07:00
Fusion
e106d87fcb fix(FN-2159): hide manual PR controls for auto-merge tasks
- Add an autoMerge prop to PrSection and show an auto-merge hint instead of manual PR actions
- Pass project autoMerge settings from TaskDetailModal into PrSection
- Preserve active automation messaging when PR creation is already in progress
- Expand PrSection tests to cover auto-merge enabled and disabled behavior
- Increase core RunMutationContext log entry bounds test timeout to reduce flakiness
2026-04-19 20:48:13 -07:00
Fusion
2b3f971fd5 feat(FN-2150): add agent memory file management
- Add core helpers to list, read, and write .fusion/agent-memory/{agentId} files with strict path validation and exports
- Add dashboard API routes and client methods for agent memory file listing and single-file read/write operations
- Expand AgentDetailView memory tab with file selection, editing, save states, and inline validation feedback
- Add route/backend coverage for agent memory file endpoints and include a @gsxdsm/fusion minor changeset
2026-04-19 20:48:13 -07:00
Fusion
302367e5c4 fix(FN-2155): require explicit store rootDir in tests
- Add constructor guards in AgentStore and ReflectionStore that throw when rootDir is omitted under Vitest
- Keep default .fusion root resolution for non-test execution paths
- Prevent accidental test writes to unintended filesystem locations by forcing explicit paths
2026-04-19 20:48:13 -07:00
Fusion
b1f6740b51 refactor(FN-2134): remove legacy memory path exports and bootstrap aliases
- Remove legacy memory path constants/helpers from core exports and backend contract surface
- Simplify memory bootstrap to initialize canonical layered memory files without seeding from .fusion/memory.md
- Update core memory tests to assert canonical .fusion/memory/MEMORY.md behavior and legacy-path rejection
- Refresh dashboard and docs naming/references to reflect canonical long-term memory path semantics
2026-04-19 10:13:34 -07:00
Fusion
f40f87fca4 fix(FN-2145): enforce absolute .fusion roots in core storage
- Default AgentStore rootDir to resolve(".fusion") so agent data paths are absolute by default
- Default ReflectionStore rootDir to resolve(".fusion") for consistent absolute root resolution
- Validate Database kbDir is absolute and throw a descriptive error when a relative path is provided
2026-04-19 10:13:34 -07:00
Fusion
5e31c409bd feat(FN-2133): standardize project memory path guidance to .fusion/memory/
- Update executor, reviewer, core prompt templates, and path-boundary messaging to reference the .fusion/memory/ directory instead of a single MEMORY.md file
- Broaden worktree boundary checks in pi path validation to allow .fusion/memory/ directory access from task worktrees
- Align memory backend metadata and dashboard backend labels to display file backend storage as .fusion/memory/
- Refresh core/engine tests to assert the new directory-based memory wording and boundary behavior
2026-04-19 10:13:34 -07:00
Fusion
7ed7cf3277 refactor(FN-2132): bootstrap canonical memory before existence checks
- Run memory-layer bootstrap before backend exists checks so legacy migrations seed canonical files during upgrades
- Preserve first-run MEMORY.md scaffold creation when long-term memory was created from the default migration scaffold
- Remove legacy direct file-exists fallback from backend ensure flow and rely on backend canonical paths
- Add tests for canonical read precedence in file/qmd backends and migration-preserving project-memory bootstrap
2026-04-19 10:13:34 -07:00
Fusion
a4ce10a1c5 feat(FN-2115): add heartbeat multiplier and agent interval controls
- Add heartbeatIntervalMultiplier to shared settings schema/types with settings parity coverage
- Apply heartbeat multiplier in engine scheduling logic while preserving explicit per-agent interval behavior
- Add Settings modal and Agents view controls for heartbeat multiplier and per-agent interval overrides, including new styling
- Expand dashboard and engine test coverage for multiplier/heartbeat controls and document the new setting
2026-04-19 10:13:34 -07:00
Fusion
a70ff39e31 fix(FN-2148): use hash cache-busting and fix store teardown
- Switch PluginLoader bypass-cache imports from a query string to a hash fragment for reload-safe module differentiation
- Update inline documentation to reflect hash-based cache busting semantics in Node ESM imports
- Close AgentStore in the affected agent-store test afterEach hook to ensure cleanup alongside TaskStore teardown
2026-04-19 10:13:34 -07:00
gsxdsm
f71c16cd54 feat(FN-2147): merge fusion/fn-2147 2026-04-19 10:13:34 -07:00
Fusion
c5918f386f fix(FN-2139): wire source export condition into CLI builds
- Add "source" export entries for @fusion/core, @fusion/dashboard, and @fusion/engine package exports
- Configure tsup/esbuild to include the "source" condition when resolving workspace dependencies
- Pass --conditions=source to bun compile so compiled CLI binaries resolve source-conditioned exports consistently
2026-04-19 10:13:34 -07:00
Fusion
a956ce5a4f refactor(FN-2126): align memory handling with canonical .fusion/memory paths
- Update memory docs and contracts to reference canonical .fusion/memory files while treating the legacy top-level memory file as compatibility-only
- Tighten memory backend path normalization messaging and map stale qmd legacy top-level memory results back to .fusion/memory/MEMORY.md
- Remove legacy memory read/write fallback branches from backend initialization paths and rely on ensureOpenClawMemoryFiles() migration behavior
- Preserve migration-seeded legacy content during ensureMemoryFile() bootstrap and add regression coverage for seeded long-term memory creation
2026-04-19 10:13:34 -07:00
gsxdsm
3472c122d4 feat(FN-2123): merge fusion/fn-2123 2026-04-19 10:13:34 -07:00