Skip to content
Back to search

Builderforce.ai

Agentic AI Coding Platform that enables everyone to train, design and embed custom LLMs into a custom agent. Deploy your agent into the builderforce (a workforce and hiring platform). Explore skills, personnas, content, governance and workforce agents in the marketplace.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/seanhogg--builderforce-ai/badge.svg)](/listings/seanhogg--builderforce-ai)

HTML

<a href="/listings/seanhogg--builderforce-ai"><img src="/api/listings/seanhogg--builderforce-ai/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

| Provider | Setup time | Manual review? | Key gotcha | |---|---|---|---| | Google | ~10 min | No for sign-in; **yes** for Gmail/Calendar/Drive/YouTube scopes | One OAuth client serves every Google flow — register a redirect URI **per flow**, or the connector 400s with `redirect_uri_mismatch` even though sign-in works | | LinkedIn | ~10 min | No (auto-approved) | Must add the **"Sign In with LinkedIn using OpenID Connect"** product — without it the `/v2/userinfo` endpoint won't return the email address | | GitHub | ~5 min | No | Only one callback URL per app — create a second OAuth App for local dev | | Microsoft | ~10 min | No | Same one-client-many-flows trap as Google — register the mailbox/calendar/drive redirect URIs alongside sign-in |

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,052 lines · 1 finding marked
  1. # Builderforce.ai
  2. > **A human-in-the-loop, fully agentic cloud** — train your own AI agents and use them inside your own agent, manage your whole workforce on a Kanban board, and review and approve every action without ever leaving VS Code.
  3. [![Deploy Status](https://img.shields.io/badge/deploy-Cloudflare%20Pages-orange)](https://builderforce.ai)
  4. [![Worker](https://img.shields.io/badge/api-Cloudflare%20Workers-blue)](https://workers.cloudflare.com)
  5. [![DB](https://img.shields.io/badge/db-Neon%20Postgres-green)](https://neon.tech)
  6. ---
  7. ## What's New
  8. - **2026-10-12 — Sequential batching in the local inference runtime.** `Engine::generate_batch` in [builderforce-inference](https://github.com/SeanHogg/builderforce-inference) runs multiple prompts on one loaded model without a reload (`e4c07ee`). Concurrent token mixing / paged attention is not in this drop. Changelog: [DONE.md](./DONE.md).
  9. ---
  10. ## What is Builderforce.ai?
  11. Builderforce.ai is a **human-in-the-loop, fully agentic cloud** where ideas become software and software becomes agents. You stay in control of every step while AI agents do the work — train your own specialist agents and put them to work *inside* your own agent, manage the whole workforce from a Kanban board, and review, validate, and approve everything without leaving your editor. It combines a full in-browser IDE with an AI training pipeline, a Workforce Registry for specialist agents, and an orchestration portal for self-hosted [BuilderForce Agents](https://builderforce.ai/agents) meshes.
  12. **Three capabilities at the core:**
  13. | Capability | What it does |
  14. |---|---|
  15. | **🔁 Train agents, use them inside your agent** | Train a custom agent in-browser (WebGPU LoRA + AI evaluation), publish it to the Workforce Registry, then hire it and call it from inside your own agent — your specialists become tools your main agent delegates to. |
  16. | **▦ Kanban board & project management** | Organize work into projects, then plan, assign, and track every task on a live Kanban board (swimlanes per status or per agent, plus table, calendar, and Gantt views). Humans and AI agents share the same board. |
  17. | **🧩 Never leave VS Code** | The BuilderForce VS Code extension runs the whole platform in your editor — chat with agents, assign and run tasks, review and validate their work, and approve human-in-the-loop actions without leaving your code. |
  18. **One platform. Three roles:**
  19. | Role | What it does |
  20. |---|---|
  21. | **Enterprise IDE** | An in-browser dev runtime ([BuilderForce WebContainers](https://github.com/SeanHogg/builderforce-webcontainers), our own MIT runtime) + Monaco + xterm.js; real-time collaboration; AI pair programming |
  22. | **AI Training Studio** | In-browser LoRA fine-tuning on instruction datasets; WebGPU-accelerated; models up to 2B parameters; no cloud GPU required |
  23. | **Orchestration Portal** | BuilderForce Agent fleet management; task assignment; heartbeat monitoring; agent-to-agent mesh relay; approval gates |
  24. ---
  25. ## Key Capabilities
  26. ### In-Browser IDE
  27. - **In-browser dev runtime** via [BuilderForce WebContainers](https://github.com/SeanHogg/builderforce-webcontainers) ([`@seanhogg/builderforce-webcontainers`](https://www.npmjs.com/package/@seanhogg/builderforce-webcontainers)) — our own open-source (MIT) runtime. Previews Vite (React, Vue, Svelte), Create React App and static projects by compiling each file on request with esbuild-wasm and loading packages from esm.sh; runs Node programs, `npm install` from the real registry and a `bfsh` shell, one Web Worker per process. No COOP/COEP headers and no session caps. Previews and processes are served from `preview.builderforce.ai`, isolated from your Builderforce session. Next.js/Nuxt/SvelteKit/Remix/Astro dev servers, native addons and install scripts are not supported — they are detected and declined with a reason.
  28. - **Monaco Editor** with syntax highlighting, IntelliSense, multi-file tabs, and real-time collaborative editing via Yjs CRDT
  29. - **xterm.js terminal** connected to the runtime's `bfsh` shell (line editing, history, pipes, `npm`, `npx`), shared across collaborators
  30. - **AI Chat Panel** — streaming AI assistant with full project file context; can apply code changes and create files directly
  31. - **Live Preview** — iframe served by the in-browser dev server; every open preview reloads on save
  32. - **Check and Publish in the tab** — type-check (`createChecker()`) and production build (`runtime.build()`) run in the browser with no install, so Check and Publish work on the files themselves
  33. ### AI Training Studio
  34. - **In-browser LoRA fine-tuning** — uses [@seanhogg/builderforce-memory](https://www.npmjs.com/package/@seanhogg/builderforce-memory) / Transformers.js with WebGPU; trains Mamba-1/2/3 and GPT-style models up to 2B parameters entirely client-side
  35. - **Hybrid Local Brain** — Mamba State Engine (`mamba-engine.ts`) runs an O(n) selective scan alongside transformer inference; agent state persists to IndexedDB as a compact Float32 state vector and is embedded in exported `AgentPackage` JSON
  36. - **Dataset generation** — LLM-assisted JSONL instruction dataset creation with SSE streaming progress
  37. - **AI evaluation** — independent judge scores model outputs on code correctness, reasoning quality, and hallucination rate (0.0–1.0)
  38. - **WebGPU fallback** — CPU software path via `forceFallbackAdapter: true`; platform reports `gpuMode: 'cpu-fallback'` transparently
  39. ### Workforce Registry
  40. - **Publish specialist agents** — bundle a LoRA adapter, capability profile, and `MambaStateSnapshot` into a portable `AgentPackage` JSON artifact
  41. - **Skill-based discovery** — agents are searchable by skills, evaluation score, and hire count
  42. - **Hire and deploy** — one click to register an agent in your [BuilderForce Agents](https://builderforce.ai/agents) mesh; PowerShell install script for local deployment
  43. - **Iterative improvement** — `training_sessions` table tracks dataset → training → evaluation → re-training loops for continuous agent quality improvement
  44. ### Local LLM Inference Pipeline
  45. - **Per-agent inference endpoint** — `POST /api/ide/agents/:id/chat` routes inference through OpenRouter with the agent's persona injected into the system prompt; `X-Inference-Mode: lora | hybrid | base | fallback-base` header signals which path ran
  46. - **Mamba state injection** — v2.0 agents carry a `MambaStateSnapshot`; each inference call prepends `[Memory: step=N signal=X context="..."]` to the system prompt, giving the agent persistent conversational memory without re-training
  47. - **Mamba state sync** — `PUT /api/ide/agents/:id/mamba-state` accepts a `MambaStateSnapshot` from the `builderforce` CLI after each session; upgrades the agent package to v2.0 and recomputes `inference_mode`; `GET /api/ide/agents/:id/mamba-state` retrieves the stored snapshot
  48. - **Package versioning** — agent packages are v1.0 (LoRA only) or v2.0 (LoRA + Mamba state); `GET /api/ide/agents/:id/package` returns the correct format and increments `request_count`
  49. - **Workforce routing in chat** — `POST /api/ai/chat` with `model: "builderforce/workforce-<agentId>"` auto-routes to the agent inference endpoint (the legacy `coderclawllm/` prefix is still accepted); no client-side changes required
  50. - **Inference logging** — `agent_inference_logs` table captures model ref, latency, token counts, status, and inference mode per request for observability and billing
  51. ### BuilderForce Agents Orchestration Portal
  52. Builderforce.ai is the cloud-side control plane for [BuilderForce Agents](https://builderforce.ai/agents) self-hosted agents:
  53. - **Fleet registration** — agent hosts register at `POST /api/agent-hosts` with machine profile (IP, workspace dirs, ports, tunnel metadata)
  54. - **Heartbeat + capability sync** — `PATCH /api/agent-hosts/:id/heartbeat` keeps capability maps and machine profiles current
  55. - **Assignment context** — `GET /api/agent-hosts/:id/assignment-context` delivers assigned project metadata and context hints; the runtime syncs to `.builderforce/context.yaml`
  56. - **Host-to-host mesh relay** — the `AgentHostRelayDO` Durable Object proxies WebSocket connections between agent hosts; `POST /api/agent-hosts/:id/forward` dispatches tasks to a remote host, authenticated with the SOURCE host's own API key (`?from=<id>&key=…`, or the `X-AgentHost-From` header) and refused across tenants
  57. - **Approval gates** — human-in-the-loop control for high-impact agent actions; agents request approval before executing; outcomes are audited
  58. - **Task management** — `tasks` and `executions` tables track work assigned to specific agent hosts; `POST /api/tasks/next` feeds the next task to a waiting agent
  59. - **Legacy mounts** — `/api/claws` and `/api/agentNodes` still answer for fleets that have not moved, with `Deprecation: true` and a `Link: rel="successor-version"` pointing at `/api/agent-hosts` (`presentation/middleware/legacyAlias.ts`). New callers use the canonical path.
  60. ### Multi-Tenant Platform
  61. - **JWT auth** with web token (global) + tenant token (workspace-scoped) dual-token model
  62. - **Multi-auth** — email/password, OAuth social login (Google, GitHub, LinkedIn, Microsoft), and magic link sign-in all coexist on the same account
  63. - **Tenant isolation** — all resources (projects, agent hosts, agents, training jobs) are scoped to a tenant; no cross-tenant data access
  64. - **Multi-workspace** — users belong to multiple tenants; `bf_default_tenant_id` auto-selects on login
  65. - **Admin observability** — `/admin` surface for platform admins (superadmin flag); `logs/global-errors.txt` in R2; `/observability` LLM usage metrics
  66. ### Billing & Subscriptions (Stripe)
  67. - **Stripe only** — `src/infrastructure/payment/StripeProvider.ts` (Stripe Checkout + Billing, hosted payment page, webhook-activated). There is deliberately no provider switch and no manual fallback: a fallback that activated plans without charging meant an unconfigured deploy handed out paid plans for free.
  68. - **PaymentProvider interface** — `src/infrastructure/payment/PaymentProvider.ts` keeps `TenantService` off the concrete Stripe client and lets tests inject a fake; it is not a provider-swap seam.
  69. - **Checkout flow** — `POST /api/tenants/:id/subscription/checkout` always returns a hosted `checkoutUrl`. The plan activates only when the signed webhook confirms payment — never from the request itself.
  70. - **Webhook handler** — `POST /api/webhooks/payment` receives Stripe events; HMAC-verified with a 5-minute replay window; activates/cancels subscriptions via normalised `WebhookEvent`
  71. - **Configuration** — set the `STRIPE_*` Worker secrets (see `src/infrastructure/payment/index.ts`). They are validated lazily: absent secrets return **503** from the billing routes and never break Worker boot.
  72. ### Dev Analytics & Team Intelligence
  73. - **Contributor profiles** — cross-platform developer identity reconciliation (GitHub, Jira, Bitbucket); `GET /api/contributors`
  74. - **Activity ingestion** — `POST /api/contributors/activity` receives PR opened/merged/reviewed, commit, issue events with automatic daily metric aggregation
  75. - **Weighted activity score** — per-contributor daily score (commits×1 + PRs×3 + reviews×2 + issues×1.5); active dev day = ≥1 commit or PR action
  76. - **PR cycle time** — end-to-end hours from `pr_opened` to `pr_merged` events tracked on each activity record
  77. - **Integration credential manager** — AES-256-GCM encrypted platform credentials stored per-tenant; `GET/POST/PUT/DELETE /api/integrations`; per-provider connectivity tests (`POST /api/integrations/:id/test`)
  78. - **Team hierarchy** — nested dev teams with manager–member relationships; `GET/POST/PATCH/DELETE /api/dev-teams`; member add/remove endpoints
  79. - **Standup report** — `GET /api/reports/standup` — daily summary: active contributors, commits, PRs merged, issues resolved; recent PRs and resolved issues
  80. - **Code review report** — `GET /api/reports/code-review` — 14-day window; stale PRs (>7 days old), average cycle time, reviewer activity
  81. - **Executive summary** — `GET /api/reports/executive` — KPIs over configurable date range: contributor counts, total commits, PRs merged, lines added, average activity score, top contributors
  82. - **Report schedules** — `GET/POST/PATCH/DELETE /api/reports/schedules`; cron-style delivery config (daily/weekly) with hour-of-day and recipient list
  83. - **Report subscriptions** — `GET/POST /api/reports/subscriptions`; per-user opt-in/opt-out per report type
  84. ### Platform Infrastructure
  85. - **Per-tenant rate limiting** — `TenantRateLimiterDO` Cloudflare Durable Object; sliding window (60 RPM FREE, 300 RPM PRO, 1000 RPM TEAMS); `X-RateLimit-Limit/Remaining/Reset` + `Retry-After` headers
  86. - **Auto-approval rules** — `GET/POST/PATCH/DELETE /api/approval-rules`; rule evaluation on `POST /api/approvals` by actionType, max cost, max files changed; bypasses human gate when conditions match
  87. - **Approval notifications** — Slack webhook + Resend email alerts on new approval requests and decisions; configurable via `SLACK_APPROVAL_WEBHOOK_URL` + `RESEND_API_KEY`
  88. - **Escalation cron** — `GET /api/approvals/escalate?secret=` expires timed-out pending approvals and fires Slack alert; suitable for Cloudflare Cron Triggers
  89. - **OTel telemetry proxy** — `POST /api/telemetry/spans` ingest; `GET /api/telemetry/spans` query; `GET /api/telemetry/traces` list; costs stored as millicent integers; W3C `X-Trace-Id` header forwarded from the `builderforce` CLI
  90. ---
  91. ## Latest Capabilities
  92. The platform has grown from an IDE-plus-training studio into a full **system of record for agentic work**. These are the most recent additions — the enterprise delivery, quality, knowledge, and FinOps surfaces that sit on top of the agent workforce.
  93. ### Planning Spine — Portfolio to Task (mig 0213, 0225)
  94. - **One dated, cost-bearing hierarchy** — `portfolio → initiative → epic → task`, with **Objectives and Key Results** attaching as a goal layer at any level. Every level is dated and rendered on a single nested Gantt (`PlanningSpineGantt`).
  95. - **Cost rolls up from the leaf** — LLM spend (priced at write time from `llm_usage_log`) plus human effort (member cost rate × hours) rolls up to every ancestor. No parallel finance system, no backfill.
  96. - **CAPEX / OPEX split** — each node carries a `cost_class` resolved in priority order (explicit → inherited → agent-classified by investment category → GAAP-conservative default). A child class that contradicts its parent is flagged as an **anomaly** for PM reconciliation.
  97. - **Endpoints** — `GET /api/pmo/spine`, `GET /api/pmo/spine/export.csv`, `GET /api/pmo/rollup` (portfolio/initiative/workspace), `PATCH /api/pmo/cost-class`, `POST /api/pmo/cost-class/classify`, initiative `POST/DELETE /api/pmo/dependencies` (cycle-checked) → on-demand critical path. Surface: `/projects?tab=portfolio`, gated by `insights.portfolio` / `insights.pm`.
  98. ### Quality — Error Observability + One-Click Agent Fix (mig 0240)
  99. - **Multi-source ingest** — one canonical event shape behind five adapters: **native** (the `@seanhogg/builderforce-quality` browser SDK), **OTLP**, **Sentry**, **PostHog**, **LogRocket** (webhooks HMAC-verified; Sentry connections can backfill).
  100. - **Fingerprint grouping** — events upsert into `error_groups` keyed by `(tenant, project, fingerprint)` — explicit fingerprint or derived from the top stack frame + normalized message; occurrence + exact distinct-user counts; resolved bugs reopen on recurrence.
  101. - **One-click fix loop** — `POST /api/quality/groups/:id/fix` creates a board task (titled + prioritized from the error, briefed with the stack trace) and dispatches a cloud agent that ships a **pull request**. Crash → group → task → PR on one surface.
  102. - **Endpoints** — authenticated `/api/quality/*` (collectors, integrations, rules, groups, fix); public keyed/HMAC ingest `/api/quality-ingest/{events,otlp/v1/logs,otlp/v1/traces,webhooks/:collectorId/:provider}`. Dashboard: `/quality`. Metered as `error_events`.
  103. ### Knowledge Management & Compliance (mig 0227)
  104. - **Versioned SOPs, processes & docs** — live editable body plus an **immutable snapshot on every publish** (version number + change note + publisher).
  105. - **Audit-ready acknowledgements** — read-acknowledgements bind to a specific version with a timestamp; per-user state is **acknowledged / pending / overdue**, with manager rollups at `GET /api/knowledge/compliance` — evidence for **SOX, TISAX, ISO 27001**.
  106. - **AI authoring + analysis** — `POST /api/knowledge/ai/draft` streams a Markdown draft; `POST /api/knowledge/documents/:id/analyze` returns structured findings (inefficiency / gap / risk / clarity) + an improved flow. Metered through the LLM gateway.
  107. - **Real-time co-editing** — Yjs CRDT over `NEXT_PUBLIC_COLLAB_WS_URL` with presence awareness; per-document **editor/viewer** collaborators on top of workspace roles; falls back to autosave when collaboration is unconfigured. Surface: `/knowledge`.
  108. ### Single-Pane Board Connectors (mig 0221)
  109. - **Two-way sync across 10 systems** — each provider implements `fetchTicketsSince(cursor)` + `pushUpdate(externalId, changeSet)`, normalizing to one ticket shape stamped with its source.
  110. - **PM / work:** GitHub Issues, Jira, Linear, monday.com, Asana, ClickUp
  111. - **ITSM:** ServiceNow, Freshservice
  112. - **Incident:** Sentry, PagerDuty
  113. - **Webhooks where supported** (GitHub, Jira, Linear, monday, Sentry, PagerDuty), polling otherwise. Agents act on a ticket or incident wherever it originates; changes flow back to the system of origin — single pane, no migration.
  114. - **Endpoints** — `GET /api/board-connections/providers` (catalog), CRUD `/api/board-connections`, `POST /api/board-connections/:id/sync`, `GET /api/board-connections/:id/links`.
  115. ### Platform Migration & Integration Hub (mig 0256)
  116. Move off a competitor tracker without fear, or just sync data in — a **staged** importer on top of the connector framework. Nothing lands in real projects/tasks/members until you commit.
  117. - **Provider discovery** — `discover()` enumerates external projects, item types, and users for **Jira, monday, Rally, GitLab, Bitbucket, GitHub** (the migration-eligible providers; new Rally/GitLab/Bitbucket adapters added).
  118. - **Staging buffer** — `import_runs` + `import_staged_{projects,items,users}` + `import_type_mappings`; combine several external projects into one BuilderForce project, map item types → task type/status, and invite/map users — all reviewed before import.
  119. - **Migrate / sync / both** — one-time historical import, an ongoing `board_connections` sync, or both. The persistent `board_type_mappings` makes ongoing sync land tasks in the mapped type/status (not a hardcoded backlog). Imported items keep their **assignee** (mapped to a member) and **story points**.
  120. - **Integrations gallery** — `/settings/integrations` is the workspace home: cards by category (PM / SCM / ITSM / incident), per-provider config panel (Credentials · Connections · Activity/diagnostics), and a "Start migration" launcher. GitHub/GitLab/Bitbucket connect **both** issues (migration) **and** repositories (code).
  121. - **Brain-drivable** — the whole flow is in the gateway MCP catalog (`integrations.create_credential`/`test`, `migrations.start`/`set_mappings`/`stage`/`commit`); the Brain (right-docked) opens the migration panel on the **left** via `open_migration_panel`.
  122. - **Endpoints** — `/api/migrations` (start/list/get/`:id/mappings`/`:id/stage`/`:id/commit`, MANAGER+, cached + version-bumped).
  123. ### Agentic Tester — Autonomous QA (mig 0063, 0206)
  124. - **Heatmap-ranked exploration** — journey events (`POST /api/qa/events`) rank route-and-element zones by recency-weighted frequency (`GET /api/qa/heatmap`); explorations plan from the hottest zones within a budget.
  125. - **AI-generated Playwright** — `POST /api/qa/generate` turns a flow into an executable spec and resolves a persona credential; a deterministic heatmap-only plan is also available (no model cost).
  126. - **Authenticated container runs** — a harness claims an exploration, logs in as a real persona (encrypted, developer-gated credentials), walks the plan, and captures console/page errors, failed requests, assertion failures, and crashes.
  127. - **Findings → board → fix** — findings dedupe by fingerprint; with auto-routing enabled, any finding at/above the severity threshold becomes a board task in a fix lane, firing the **same lane auto-run a human board drag triggers** → a fix agent opens a PR. Schedules run it on cron. Quality trend (escaped vs caught defects) at `GET /api/qa/quality`.
  128. ### Consumption Metering (mig 0218)
  129. - **Meter on consumption, not visibility** — one framework (`/api/consumption`) reports month-to-date usage for `ai_tokens`, `ingestion` (bytes), and `error_events` against the plan allowance, using the **same accountants the gateway and ingestion gate enforce** — so the "% used" a member sees equals the cap that's enforced. Cached 60s, keyed per tenant + calendar month.
  130. ### Coordinated Role Participation & Accountability (mig 0334)
  131. - **The right role does the work** — first-class agent↔role capability (`ide_agents.role_keys`) drives role-aware assignment: a producer stage resolves the role from the ticket's `action_type` and dispatches a role-capable agent/human, never a mis-assigned one. Stops the "a Product Manager was dispatched to write code" class of failure.
  132. - **A participation manifest per ticket** — `ticket_participants` derives the required roles from the board's swimlane requirements, resolves each slot by capability, and tracks per-participant state (pending / assigned / in_progress / completed / changes_requested / waived / unstaffed).
  133. - **An immutable Accountability Report** — an append-only `ticket_role_signoffs` ledger records Who / When / Verdict / Comments / Contribution per role; default-deny RBAC (only role-capable members may sign off as a role); every sign-off emits to the unified activity log. A **Resource Assessment** control adds a needed role beyond the template — an unresolved add surfaces as a blocking resource gap.
  134. - **Endpoints** — `GET /api/kanban/tasks/:id/accountability`, `/participants`, `POST /participants` (assess) / `/materialize`, plus MCP `kanban.participants` / `kanban.accountability` / `kanban.assess_resource`. Surface: the ticket-drawer **Accountability** tab + a board `X/Y` participants chip.
  135. ### Pre-Sales RFP / RFQ Response (mig 0335)
  136. - **Turn a repo into a proposal** — CTO + Product Owner built-in agents generate a branded, costed proposal from a project's analyzed capabilities: cost / P&L, a phase Gantt, risks, dependencies, and a capability roster matched to the ask.
  137. - **Co-branded output** — the requester's palette + logo blend with the responder's for a branded, self-contained proposal document (print-to-PDF / download), with freshness-gated grounding (a >5-day-stale scan re-runs the deterministic system audits before answering).
  138. - **Surface** — a Projects **RFP tab** (list / create) + `/projects/rfp/[id]` detail; `/api/rfp` routes.
  139. ### Incident Management & Active Monitoring (mig 0292)
  140. - **Incidents close the loop** — a Help-Desk / Incident-Manager agent, a Freshdesk connector, on-call rotations, timed escalation, Teams / Slack / email paging, and a per-incident war-room feed. On resolution the RCA is published to Knowledge **and** fed to the project's Evermind, so the workforce learns and stops repeating causes.
  141. - **A monitoring canvas** — pin heartbeat / HTTP / webhook / metric monitors onto an uploaded architecture diagram; a `*/5` sweep evaluates them and a breach **auto-starts the on-call investigation** (monitor → signal → incident → paging), with reporting on the timeline.
  142. ### Meetings & Live Collaboration (mig 0292, 0330)
  143. - **Video / audio meetings with agents in the room** — mesh WebRTC over a `CeremonyRoomDO` relay; agent attendees speak live via a caption / transcript bridge; recording + transcription produce **AI minutes**. Google / Microsoft calendar sync. Surface: `/meetings`.
  144. ### AI Managers — Types & Coaching (mig 0327)
  145. - **Typed managers tied to the role catalog** — Dev / QA / Service-Desk / DevOps manager types map to `roleCatalog` (custom roles become `role:<key>` types); a human → manager **Coaching Session** carries directive | task modes with expiry / done state, steering how a manager agent runs its reports.
  146. ### Memory-First Answering — skip the paid LLM
  147. - **Answer from the project's own memory before spending a model call** — the web and VS Code webview Brain consult the project's `project_facts` fact tier + its Evermind SSM first and short-circuit the LLM on a confident hit (an exact-repeat Q&A cache + opt-in Evermind-first inference), single-sourced in `resolveMemoryAnswer`. Learning fans out to **every** Evermind under a project (its own head + its IDE builds' heads) via one shared `contributeTextToProjectEverminds`. Endpoints: `GET/POST /api/projects/:id/answer`, `GET /api/projects/:id/evermind/targets`.
  148. ---
  149. ## Authentication
  150. Builderforce.ai supports three sign-in methods that coexist on the same account. A single user can link multiple OAuth providers, set a password, and use magic links interchangeably.
  151. ### Sign-in methods
  152. | Method | How it works |
  153. |---|---|
  154. | **Email + password** | `POST /api/auth/web/login` — PBKDF2 (100k iterations, SHA-256); same generic error for wrong email or wrong password |
  155. | **OAuth social login** | `GET /api/auth/oauth/:provider` → provider consent → `GET /api/auth/oauth/:provider/callback` → JWT issued; browser redirected to `/auth/callback?token=…` |
  156. | **Magic link** | `POST /api/auth/magic-link` sends a 15-minute single-use token by email; `GET /api/auth/magic-link/verify?token=…` issues JWT; always returns 200 (no email enumeration) |
  157. Supported OAuth providers: `google`, `github`, `linkedin`, `microsoft`.
  158. ### Auth flow diagram
  159. ```
  160. Browser
  161. │
  162. ├─ Email/password ──────────────────────────► POST /api/auth/web/login
  163. │ Returns JWT in JSON body
  164. │
  165. ├─ OAuth (click button) ────────────────────► GET /api/auth/oauth/:provider
  166. │ 302 → provider consent screen
  167. │ Provider → GET /api/auth/oauth/:provider/callback
  168. │ API issues JWT
  169. │ 302 → /auth/callback?token=JWT
  170. │ Frontend page writes token to localStorage
  171. │
  172. └─ Magic link ──────────────────────────────► POST /api/auth/magic-link
  173. Email sent with /auth/magic-link?token=…
  174. Frontend page calls GET /api/auth/magic-link/verify
  175. Returns JWT in JSON body
  176. ```
  177. ### JWT strategy
  178. - **Web token** (`localStorage key: bf_web_token`) — 24-hour HMAC-SHA-256 JWT; payload: `{ sub, email, username, amr?, sa?, jti, sid }`
  179. - **Tenant token** (`localStorage key: bf_tenant_token`) — 1-hour workspace-scoped JWT; issued by `POST /api/auth/tenant-token`
  180. - Every issued token is tracked in the `auth_tokens` table (JTI + session ID); `webAuthMiddleware` validates against this table on every request, enabling instant revocation
  181. ### Account management endpoints
  182. | Endpoint | Auth | Description |
  183. |---|---|---|
  184. | `GET /api/auth/linked-accounts` | Web JWT | List linked OAuth providers + whether account has a password |
  185. | `DELETE /api/auth/unlink/:provider` | Web JWT | Unlink a provider; blocked if it would remove the last sign-in method |
  186. | `POST /api/auth/add-password` | Web JWT | Add a password to an OAuth-only account |
  187. ### OAuth security
  188. - **CSRF protection** — OAuth `state` parameter is HMAC-SHA-256 signed (using `JWT_SECRET`) with a nonce and 10-minute expiry; no database required
  189. - **Account linking** — if an OAuth email matches an existing account, the provider is linked automatically; the user controls their email so this is safe
  190. - **Email-only users** — OAuth users who haven't set a password are protected from the unlink endpoint; they must `POST /api/auth/add-password` first
  191. ### Enabling OAuth providers
  192. Each provider is activated by supplying its client credentials as Cloudflare Worker secrets. Providers with missing credentials silently return `503` — you only need to configure the providers you want.
  193. ```bash
  194. # Google
  195. wrangler secret put GOOGLE_CLIENT_ID
  196. wrangler secret put GOOGLE_CLIENT_SECRET
  197. # GitHub
  198. wrangler secret put GITHUB_CLIENT_ID
  199. wrangler secret put GITHUB_CLIENT_SECRET
  200. # LinkedIn
  201. wrangler secret put LINKEDIN_CLIENT_ID
  202. wrangler secret put LINKEDIN_CLIENT_SECRET
  203. # Microsoft
  204. wrangler secret put MICROSOFT_CLIENT_ID
  205. wrangler secret put MICROSOFT_CLIENT_SECRET
  206. ```
  207. Register the OAuth callback URL in each provider's dashboard:
  208. ```
  209. https://api.builderforce.ai/api/auth/oauth/{provider}/callback
  210. ```
  211. Replace `{provider}` with the lowercase provider name: `google`, `github`, `linkedin`, `microsoft`.
  212. #### Provider setup
  213. | Provider | Setup time | Manual review? | Key gotcha |
  214. |---|---|---|---|
  215. | Google | ~10 min | No for sign-in; **yes** for Gmail/Calendar/Drive/YouTube scopes | One OAuth client serves every Google flow — register a redirect URI **per flow**, or the connector 400s with `redirect_uri_mismatch` even though sign-in works |
  216. | LinkedIn | ~10 min | No (auto-approved) | Must add the **"Sign In with LinkedIn using OpenID Connect"** product — without it the `/v2/userinfo` endpoint won't return the email address |
  217. | GitHub | ~5 min | No | Only one callback URL per app — create a second OAuth App for local dev |
  218. | Microsoft | ~10 min | No | Same one-client-many-flows trap as Google — register the mailbox/calendar/drive redirect URIs alongside sign-in |
  219. ---
  220. #### Google
  221. 1. Go to [console.cloud.google.com](https://console.cloud.google.com), create or select a project
  222. 2. **APIs & Services → OAuth consent screen**
  223. - User Type: **External**
  224. - App name, support email, add scopes: `email`, `profile`, `openid` (non-sensitive, no review required)
  225. - Connectors need their scopes listed here too, and they are **not** free: Gmail
  226. (`gmail.modify`, `gmail.send`) is a *restricted* scope, Calendar/Drive/YouTube are
  227. *sensitive*. Both classes work for accounts listed as test users while the app is in
  228. Testing, but going public with them requires Google's verification review.
  229. - Add your email as a test user while in development
  230. 3. **APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID**
  231. - Application type: **Web application**
  232. - Authorized redirect URIs — **one entry per flow, not just sign-in.** `GOOGLE_CLIENT_ID`
  233. is shared by every Google-family connector, and each builds its own callback path from
  234. the request origin. A path that is missing here fails with
  235. `Error 400: redirect_uri_mismatch` at consent time — sign-in working proves nothing about
  236. the others. Add the production entry for every flow you intend to use, plus the
  237. `http://localhost:8787` twin of each one you develop against:
  238. ```
  239. https://api.builderforce.ai/api/auth/oauth/google/callback # sign-in / create account
  240. https://api.builderforce.ai/api/mailbox/callback/google # Connect inbox (Gmail)
  241. https://api.builderforce.ai/api/calendar/callback/google # Google Calendar
  242. https://api.builderforce.ai/api/drive/callback/google # Google Drive
  243. https://api.builderforce.ai/api/youtube/callback # YouTube publishing
  244. ```
  245. 4. Copy Client ID and Client Secret:
  246. ```bash
  247. wrangler secret put GOOGLE_CLIENT_ID
  248. wrangler secret put GOOGLE_CLIENT_SECRET
  249. ```
  250. 5. **OAuth consent screen → App domain** — fill in the **Application privacy policy link** and
  251. **Application terms of service link**. Google will not verify an app without them, and until they
  252. are set the consent screen tells the user it cannot show links to your policies:
  253. ```
  254. https://builderforce.ai/legal/privacy
  255. https://builderforce.ai/legal/terms
  256. ```
  257. Both are public, server-rendered pages of the CURRENT published document version (see
  258. `frontend/src/lib/legalDocs.ts` — one route table, shared by the pages, the footer link, the
  259. trust-centre nav and the sitemap). Also add `builderforce.ai` under **Authorized domains**.
  260. > **Publishing:** While in "Testing" mode only test users can sign in — and only test users can
  261. > complete a connector consent, however many redirect URIs are registered. Click **Publish App** on
  262. > the consent screen when ready for production — `email/profile/openid` are standard scopes and are
  263. > typically approved immediately with no manual review, but the Gmail/Calendar/Drive/YouTube scopes
  264. > above are sensitive or restricted and go to Google's verification review, which requires the
  265. > privacy-policy and terms links from step 5 plus a demo video of the consent flow.
  266. ---
  267. #### LinkedIn
  268. 1. Go to [linkedin.com/developers](https://www.linkedin.com/developers) → **Create App**
  269. - App name, LinkedIn Company Page (required — create one if needed), logo
  270. 2. **Auth tab** → Authorized redirect URLs — add both:
  271. ```
  272. https://api.builderforce.ai/api/auth/oauth/linkedin/callback
  273. http://localhost:8787/api/auth/oauth/linkedin/callback
  274. ```
  275. 3. **Products tab** → request **"Sign In with LinkedIn using OpenID Connect"** — click Request access (auto-approved instantly). This unlocks the `openid profile email` scopes used by the code. Without it the `/v2/userinfo` endpoint will not return the email address.
  276. 4. Back on the **Auth tab**, copy Client ID and Client Secret:
  277. ```bash
  278. wrangler secret put LINKEDIN_CLIENT_ID
  279. wrangler secret put LINKEDIN_CLIENT_SECRET
  280. ```
  281. ---
  282. #### GitHub
  283. 1. GitHub → **Settings → Developer settings → OAuth Apps → New OAuth App**
  284. - Homepage URL: `https://builderforce.ai`
  285. - Authorization callback URL:
  286. ```
  287. https://api.builderforce.ai/api/auth/oauth/github/callback
  288. ```
  289. 2. Click **Register application**, then **Generate a new client secret**
  290. 3. Set secrets:
  291. ```bash
  292. wrangler secret put GITHUB_CLIENT_ID
  293. wrangler secret put GITHUB_CLIENT_SECRET
  294. ```
  295. > **Local dev:** GitHub allows only one callback URL per app. Create a separate OAuth App (e.g. "builderforce-dev") pointing to `http://localhost:8787/api/auth/oauth/github/callback` and use its credentials in `api/.dev.vars`.
  296. ---
  297. #### Microsoft
  298. 1. [Azure Portal](https://portal.azure.com/) → **Microsoft Entra ID → App registrations → New registration**
  299. - Supported account types: **"Accounts in any organizational directory and personal Microsoft accounts"**
  300. - Redirect URIs (Web) — `MICROSOFT_CLIENT_ID` is shared by every Microsoft flow, so
  301. register one per flow you intend to use (add the `http://localhost:8787` twin for local dev):
  302. ```
  303. https://api.builderforce.ai/api/auth/oauth/microsoft/callback # sign-in / create account
  304. https://api.builderforce.ai/api/mailbox/callback/microsoft # Connect inbox (Outlook)
  305. https://api.builderforce.ai/api/calendar/callback/microsoft # Outlook Calendar
  306. https://api.builderforce.ai/api/drive/callback/microsoft # OneDrive / SharePoint
  307. ```
  308. 2. **Certificates & secrets → New client secret** — copy the value immediately (it's only shown once)
  309. 3. Copy the **Application (client) ID** from the Overview page
  310. 4. Set secrets:
  311. ```bash
  312. wrangler secret put MICROSOFT_CLIENT_ID
  313. wrangler secret put MICROSOFT_CLIENT_SECRET
  314. ```
  315. ---
  316. #### Local development
  317. For local development, use `api/.dev.vars` — Wrangler loads this file automatically for `wrangler dev`, and it is gitignored:
  318. ```ini
  319. # api/.dev.vars
  320. GOOGLE_CLIENT_ID=your_google_client_id
  321. GOOGLE_CLIENT_SECRET=your_google_client_secret
  322. LINKEDIN_CLIENT_ID=your_linkedin_client_id
  323. LINKEDIN_CLIENT_SECRET=your_linkedin_client_secret
  324. GITHUB_CLIENT_ID=your_github_dev_app_client_id
  325. GITHUB_CLIENT_SECRET=your_github_dev_app_client_secret
  326. APP_URL=http://localhost:3000
  327. ```
  328. The OAuth callback URL is derived from the incoming request's `Origin` header at runtime, so no extra `API_URL` variable is needed — it resolves to `http://localhost:8787` locally and `https://api.builderforce.ai` in production automatically.
  329. ### Magic link email
  330. The `sendMagicLinkEmail` function in `api/src/presentation/routes/oauthRoutes.ts` is a placeholder that logs the link to the console. Wire it to your email provider (Resend, SendGrid, Mailgun, etc.) before using magic links in production:
  331. ```typescript
  332. // api/src/presentation/routes/oauthRoutes.ts ~line 253
  333. async function sendMagicLinkEmail(to, name, token, frontendUrl) {
  334. const magicUrl = `${frontendUrl}/auth/magic-link?token=${encodeURIComponent(token)}`;
  335. // TODO: call your email provider here
  336. }
  337. ```
  338. ### Frontend routes added
  339. | Route | File | Purpose |
  340. |---|---|---|
  341. | `/auth/callback` | `frontend/src/app/auth/callback/page.tsx` | Receives `?token=JWT` from OAuth redirect, persists session, navigates |
  342. | `/auth/magic-link` | `frontend/src/app/auth/magic-link/page.tsx` | Calls `/api/auth/magic-link/verify`, persists session, navigates |
  343. ---
  344. ## Integration with BuilderForce Agents
  345. ```
  346. Developer workstation
  347. └─ BuilderForce Agents (self-hosted, MIT)
  348. ├─ 7-role agent DAG (Code, Review, Test, Debug, Refactor, Document, Architect)
  349. ├─ Staged diff review (accept/reject before writing to disk)
  350. ├─ Agent-to-agent mesh (remote:<id>, remote:auto[caps], HMAC-signed dispatch)
  351. ├─ Workflow telemetry → .builderforce/telemetry/ + portal timeline
  352. ├─ Execution lifecycle → running/completed/failed reported to portal
  353. ├─ Approval gate → blocks on manager decision from portal
  354. ├─ Skill registry → loads portal-assigned skills at startup
  355. ├─ Cron scheduler → executes portal-managed jobs on schedule
  356. └─ BUILDERFORCE_API_KEY → heartbeat → Builderforce.ai
  357. │ ←task.assign / task.broadcast
  358. │ ←approval.decision
  359. │ ←cron jobs / skill assignments
  360. ┌───────▼───────┐
  361. │ Builderforce │
  362. │ .ai │
  363. │ │
  364. │ • Fleet view │
  365. │ • Task assign │
  366. │ • Approvals │
  367. │ • Audit log │
  368. │ • AI training │
  369. │ • Registry │
  370. │ • Cron jobs │
  371. │ • Skills mkt │
  372. └───────────────┘
  373. ```
  374. **Configure BuilderForce Agents to connect** (install with `npm install -g @seanhogg/builderforce-agents` or `curl -fsSL https://builderforce.ai/install.sh | bash`):
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 468 on GitHub
  375. ```bash
  376. export BUILDERFORCE_API_KEY=<your-api-key>
  377. export BUILDERFORCE_URL=https://api.builderforce.ai
  378. builderforce gateway
  379. ```
  380. BuilderForce Agents operates fully standalone without Builderforce. The connection unlocks fleet visibility, task assignment with live execution tracking, enforced approval gates, portal-managed skill assignments, scheduled cron execution, and access to the Workforce Registry.
  381. ---
  382. ## On-Device AI Stack
  383. Builderforce.ai is built on the open-source `@seanhogg/builderforce-memory` stack for on-device AI:
  384. ```
  385. @seanhogg/builderforce-memory-engine (engine)
  386. └─ WebGPU WGSL kernels: Mamba-1 (S6), Mamba-2 (SSD), Mamba-3 (complex MIMO+ET), causal attention
  387. ↓
  388. @seanhogg/builderforce-memory (runtime)
  389. └─ MambaSession.create() — one-call GPU init, tokenizer, model, checkpoint, persistence
  390. └─ Inference routing · distillation · semantic memory · SSMAgent
  391. ↓
  392. Builderforce.ai IDE
  393. └─ mamba-engine.ts — Hybrid Local Brain (SSM state + IndexedDB)
  394. └─ agent-runtime.ts — step() → inference → confidence scoring → cloud escalation
  395. └─ training/ — browser LoRA fine-tuning in a Web Worker on the @webdit/torch engine (WebGPU, CPU fallback)
  396. ```
  397. The on-device AI layer runs in O(n) time (vs O(n²) for attention), making it suitable for continuous low-latency state updates and fine-tuning entirely in the browser.
  398. > Both packages are published on npm: `@seanhogg/builderforce-memory-engine` (engine) and `@seanhogg/builderforce-memory` (runtime).
  399. ### Cross-surface semantic cache (token savings)
  400. The biggest cost lever in the stack is an **embedding-keyed semantic cache** that reuses a prior answer when a new prompt is a *paraphrase* of one already answered — so the frontier model is never called for semantically-repeated work. It is two-tier and shared across surfaces:
  401. - **L1 (local, free):** in-process cosine match using on-device SSM embeddings — runs in the browser IDE and in each agent.
  402. - **L2 (shared):** the gateway's `POST /v1/semantic-cache/{lookup,store}` (tenant-scoped, KV-backed). A paraphrase answered in the **web app** is reusable by an **agent**, and vice-versa.
  403. The same portable [`SemanticCache`](https://github.com/SeanHogg/builderforce-memory) from `@builderforce/memory` powers both surfaces — the embedder (on-device SSM) and the L2 backend are injected, so there is no browser/Node fork. On-device embeddings make L1 free; the gateway L2 turns one tenant's cache hits into platform-wide savings.
  404. ### Hybrid retrieval & answer evaluation
  405. Builderforce.ai implements the full **seven-layer agent stack** — and the two layers most stacks leave conventional-thin (RAG retrieval and evaluation) are built out:
  406. - **Hybrid RAG.** Retrieval fuses **dense** (SSM / OpenAI embeddings, cosine) and **sparse** (Okapi **BM25** keyword) signals with **Reciprocal Rank Fusion**, then reranks with **MMR** for relevance *and* diversity — over documents chunked with a recursive splitter + overlap. Dense search alone misses exact tokens (identifiers, error codes, rare names); the hybrid path catches them. It degrades gracefully (no embedding → BM25-only; no overlap → dense-only). Lives zero-dependency in `@seanhogg/builderforce-memory/retrieval` (`chunkText`, `bm25Search`, `reciprocalRankFusion`, `maximalMarginalRelevance`, `hybridRetrieve`, `MemoryStore.recallHybrid`) and powers the LanceDB long-term-memory extension.
  407. - **Semantic evaluation + drift.** Every cloud run is scored for **faithfulness**, **answer relevance**, and **hallucination rate** — inline and zero-cost (lexical), with an **LLM-as-judge** upgrade on demand at `POST /api/eval` (billed through the metered gateway). Scores persist on the run record; a **drift monitor** (mean-shift z-score + Population Stability Index) compares baseline vs recent windows per *(action-type × model)* and raises an alert when quality regresses — daily on cron and on demand at `GET /api/eval/drift`. A wrong answer no longer hides behind a green dashboard.
  408. See the write-up: [The AI Agent Tech Stack, Built](https://builderforce.ai/blog/agent-tech-stack-all-seven-layers).
  409. ---
  410. ## Open source
  411. The runtimes Builderforce.ai is built on are open source under MIT, and built to be forked. Overview: [builderforce.ai/open-source](https://builderforce.ai/open-source).
  412. | Package | What it brings |
  413. |---|---|
  414. | [builderforce-webcontainers](https://github.com/SeanHogg/builderforce-webcontainers) | The in-browser dev runtime behind the IDE and canvas previews: live preview, production build, type-check, Node processes, `npm install` and a shell, with no COOP/COEP and no session caps. npm: `@seanhogg/builderforce-webcontainers`. |
  415. | [builderforce-memory](https://github.com/SeanHogg/builderforce-memory) | Persistent, browser-trainable SSM memory for any agent: WebGPU Mamba engine, runtime, semantic cache and the Evermind write-through memory, plus an MCP server. npm: `@seanhogg/builderforce-memory`. |
  416. | [builderforce-inference](https://github.com/SeanHogg/builderforce-inference) | Synapse, the desktop app and local AI runtime: runs models on your own machine with the native `bfi` engine, keeps a private Evermind memory and hosts MCP connectors. |
  417. | [builderforce-spawn](https://github.com/SeanHogg/builderforce-spawn) | Spawn, the desktop app that builds Roblox games by talking, with a Roblox Studio bridge. |
  418. ---
  419. ## Architecture
  420. ```
  421. ┌─────────────────────────── Browser ──────────────────────────────┐
  422. │ │
  423. │ Next.js (App Router) BuilderForce WebContainers │
  424. │ ┌─────────────────────┐ ┌──────────────────────────────┐ │
  425. │ │ Monaco Editor │◄──────►│ Dev server (esbuild-wasm) │ │
  426. │ │ xterm.js Terminal │ │ Node processes · npm · bfsh │ │
  427. │ │ Preview <iframe> │ │ Service worker on preview.* │ │
  428. │ │ AI Chat Panel │ │ Virtual FS (synced to R2) │ │
  429. │ │ Train Panel │ └──────────────────────────────┘ │
  430. │ │ Agent Publish │ │
  431. │ └──────────┬──────────┘ │
  432. │ │ HTTP / WebSocket │
  433. └─────────────┼────────────────────────────────────────────────────┘
  434. │
  435. ┌─────────────▼──────────── Cloudflare Edge ──────────────────────┐
  436. │ │
  437. │ API (api.builderforce.ai — Hono) Durable Objects │
  438. │ ┌────────────────────────────┐ ┌──────────────────────┐ │
  439. │ │ /api/auth /api/tenants │ │ AgentHostRelayDO │ │
  440. │ │ /api/agent-hosts /api/tasks│ │ - host mesh relay │ │
  441. │ │ /api/brain /api/projects │ │ - heartbeat proxy │ │
  442. │ │ /api/runtime/executions │ └──────────────────────┘ │
  443. │ └────────────────────────────┘ ┌──────────────────────┐ │
  444. │ │ CollaborationRoom │ │
  445. │ Worker (worker.builderforce.ai) │ - Yjs CRDT sync │ │
  446. │ ┌────────────────────────────┐ │ - cursor presence │ │
  447. │ │ /api/projects (IDE files) │ │ - terminal relay │ │
  448. │ │ /api/datasets /api/training│ └──────────────────────┘ │
  449. │ │ /api/agents (Registry) │ │
  450. │ │ /api/ai/chat (streaming) │ R2 Buckets │
  451. │ └────────────────────────────┘ ┌──────────────────────┐ │
  452. │ │ project files │ │
  453. │ Neon Postgres │ datasets (.jsonl) │ │
  454. │ ┌────────────────────────────┐ │ LoRA artifacts │ │
  455. │ │ users · tenants · projects │ │ agent packages │ │
  456. │ │ agent_hosts · tasks │ └──────────────────────┘ │
  457. │ │ agents · training_jobs │ │
  458. │ │ agent_inference_logs │ │
  459. │ │ contributors · dev_teams │ │
  460. │ │ activity_events · metrics │ │
  461. │ │ integrations · telemetry │ │
  462. │ └────────────────────────────┘ │
  463. └───────────────────────────────────────────────────────────────────┘
  464. ```
  465. **Two Cloudflare Workers, one platform:**
  466. | | `api` (api.builderforce.ai) | `worker` (worker.builderforce.ai) |
  467. |---|---|---|
  468. | **Purpose** | Auth, tenants, agent hosts, tasks, brain, marketplace, dev analytics | IDE projects, files, datasets, training, collaboration |
  469. | **Auth** | JWT + tenant isolation | CORS (no auth currently) |
  470. | **Durable Objects** | AgentHostRelayDO (host mesh relay) | CollaborationRoom (Yjs sync) |
  471. | **Storage** | R2 `UPLOADS` (brain files, agent-host assets) | R2 `STORAGE` (project files, artifacts, datasets) |
  472. ---
  473. ## Quick Start
  474. ### Local development
  475. ```bash
  476. git clone https://github.com/SeanHogg/Builderforce.ai
  477. cd Builderforce.ai
  478. # Install deps
  479. pnpm install # or npm install in each sub-directory
  480. # Configure
  481. echo "NEXT_PUBLIC_WORKER_URL=http://localhost:8787" > frontend/.env.local
  482. echo "NEON_DATABASE_URL=postgresql://..." > worker/.env
  483. # Run migrations
  484. cd worker && npm run migrate && cd ..
  485. # Start (in separate terminals)
  486. cd worker && npx wrangler dev # :8787
  487. cd frontend && npm run dev # :3000
  488. ```
  489. Open [http://localhost:3000](http://localhost:3000). WebGPU training requires Chrome 113+.
  490. ### Deploy to Cloudflare
  491. ```bash
  492. cd api && npm run secrets:from-env && npm run deploy
  493. # Frontend: CI/CD via .github/workflows/deploy-frontend.yml
  494. ```
  495. **Required secrets:** `CF_API_TOKEN`, `CF_ACCOUNT_ID`, `NEON_DATABASE_URL`, `JWT_SECRET`, `OPENROUTER_API_KEY`. (SDK publishing uses npm Trusted Publishing OIDC — no `NPM_TOKEN` secret needed; see below.)
  496. **Releases:** [release.yml](.github/workflows/release.yml) runs four independent jobs in parallel: npm packaging, API deployment, frontend deployment, and help-site deployment. The `package-npm` job builds, tests, and publishes each public package only when its `package.json` version is absent from npm, making re-runs idempotent. Auth uses npm Trusted Publishing OIDC (with `NPM_TOKEN` as an optional bootstrap fallback). Configure each package's trusted publisher for Organization `SeanHogg`, Repository `Builderforce.ai`, and Workflow `release.yml`.
  497. **Optional OAuth secrets** (add only the providers you want):
  498. `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `LINKEDIN_CLIENT_ID`, `LINKEDIN_CLIENT_SECRET`, `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`
  499. ---
  500. ## Browser Requirements
  501. | Feature | Required |
  502. |---|---|
  503. | In-browser IDE runtime ([BuilderForce WebContainers](https://github.com/SeanHogg/builderforce-webcontainers)) | Any modern browser with service workers, in a secure context (https or localhost). No COOP/COEP headers. |
  504. | WebGPU LoRA training | Chrome 113+ |
  505. | Collaborative editing | Any modern browser |
  506. | CPU fallback training | Any browser (via `forceFallbackAdapter`) |
  507. The IDE runtime works in current Chrome, Edge, Firefox and Safari. Only the WebGPU features (training, on-device inference) carry their own browser requirements, listed above.
  508. ---
  509. ## Design System
  510. The UI follows the **BuilderForce deep space** aesthetic — consistent across Builderforce.ai and the BuilderForce Agents runtime:
  511. | Token | Dark | Light |
  512. |---|---|---|
  513. | `--bg-deep` | `#050810` | `#fcfeff` |
  514. | `--bg-surface` | `#0a0f1a` | `#ffffff` |
  515. | `--coral-bright` | `#4d9eff` | `#3b82f6` |
  516. | `--cyan-bright` | `#00e5cc` | `#008f87` |
  517. | `--font-display` | Clash Display | Clash Display |
  518. | `--font-body` | Satoshi | Satoshi |
  519. Theme persists to `localStorage('bf-theme')` with an anti-FOUC inline script applied before first paint.
  520. ---
  521. ## Roadmap & Gap Register
  522. Open work lives in the **Consolidated Gap Register** in **[ROADMAP.md](./ROADMAP.md)**, grouped by stage of the arc. Finished work moves to **[DONE.md](./DONE.md)**.
  523. ---
  524. ## Cloud Agent Types
  525. Builderforce runs agents on two execution **planes** — **On-Prem (Hosted)** and **Cloud**. There is ONE agent engine (the current version), so the Cloud plane is a single **Cloud Agent** that runs on one of **two surfaces**: a **Durable Object** or a **Node/Container**. The routing decision is a single source of truth in [cloudDispatch.ts](api/src/application/runtime/cloudDispatch.ts) (`resolveCloudSurface` / `cloudAgentTypeLabel`) and [runtimeRoutes.ts](api/src/presentation/routes/runtimeRoutes.ts) (`resolveCloudAgent`); the surface column lives on `ide_agents` (`runtime_surface` migration 0105). The engine is never read from the DB — it is always the current version.
  526. > **Cloud vs. On-Prem is a hard boundary.** A cloud agent executes **only** in the cloud (everything is Cloudflare — Worker, Durable Object, or Container). A cloud agent is **never** dispatched to a client machine. An **On-Prem (Hosted)** agent — an *agentHost*, of which many can run on one machine — runs a task only when a host is **explicitly pinned** to it. See the agent taxonomy ([[agent-types-taxonomy]]).
  527. ### At a glance
  528. | Cloud Agent surface | Where it runs | Persistent shell? | Best for |
  529. |---|---|---|---|
  530. | **Cloud Agent (Durable Object)** | `durable` — `CloudRunnerDO`, one LLM step per `alarm()` tick. **Default surface.** | No (CI verifies builds) | Most cloud tasks: on-demand, no always-on compute, survives long runs |
  531. | **Cloud Agent (Node/Container)** | `container` — long-lived Cloudflare Container (`AgentContainerDO`) | **Yes** (`run_command`) | Very long / continuous tasks needing a real shell to install deps + run builds/tests/lint |
  532. | *(On-Prem Hosted — for contrast)* | Client machine (agentHost), only when pinned | Yes (the host's own machine) | BYO-machine execution; not a cloud agent |
  533. ### Cloud Agent (Durable Object) — surface `durable`
  534. The default. Runs the Claude Agent SDK tool loop fully in the cloud across Durable Object `alarm()` ticks — **one LLM step per tick**, conversation state persisted in DO storage between ticks (`CloudRunnerDO`). Inference routes through the **LLM Gateway** using the tenant's **BYO Anthropic key**.
  535. **Features**
  536. - One step per `alarm()` tick; each tick is a fresh Worker invocation with a fresh CPU/subrequest budget, so a multi-step run **never hits the ~30s `waitUntil` wall** that kills the interim Worker executor.
  537. - A cursor in `state.storage` is the idempotency/resume anchor — the loop resumes exactly where it left off.
  538. - Heartbeats `executions.updated_at` every tick, so the orphan reaper treats an actively-ticking run as alive and only reaps a genuinely silent one.
  539. - The DO surface pins the **same model** for every tick of a run.
  540. **Pros**
  541. - On-demand serverless — no always-on compute, nothing to keep warm.
  542. - Robust to long runs and eviction; the canonical, recommended cloud surface.
  543. - Full Claude Agent SDK loop: per-tool timeline, steering/chat, approval gates.
  544. **Cons**
  545. - **No shell** — it cannot run builds/tests itself; correctness is verified by CI, not by the agent before finishing.
  546. - Per-tick overhead (alarm scheduling, state rehydrate) makes it less efficient for a single very long, chatty session than a persistent process.
  547. - Requires a tenant Anthropic key wired through the Gateway.
  548. > When the `CloudRunnerDO` binding is absent there is **no fallback executor** — dispatch resolves to `unavailable` and the run fails fast with that reason. An in-request Worker executor used to be documented here as an interim fallback, but it could not survive the ~30s `waitUntil` wall on a multi-step run, so it was never selectable and has been removed: a clear "no executor bound" error beats a run that silently dies mid-task and gets orphan-reaped.
  549. ### Cloud Agent (Node/Container) — surface `container`
  550. The Claude Agent SDK loop running in a **persistent Node process inside a real Cloudflare Container** (`AgentContainerDO`). The container boots a small HTTP server; the DO is the Cloudflare-Containers control plane that starts/stops it and proxies the run. The container drives the loop and calls back into the Worker for every LLM step, repo telemetry, and the final PR — so the Worker stays the single source of truth for the Gateway, usage metering, and PR finalize.
  551. **Features**
  552. - **Real shell** (`run_command`): clone the repo, install deps, run actual builds / tests / lint, and verify before finishing.
  553. - Persistent process — runs continuously for very long tasks without per-tick overhead.
  554. - `enableInternet` for Gateway + GitHub reach from inside the container; stays warm `20m` after the last request, then sleeps to stop billing.
  555. - This is also the surface an **explicitly-pinned host** maps to (a long-lived runtime reached via the relay).
  556. **Pros**
  557. - Genuine end-to-end verification (the agent runs the build/tests itself, not just CI).
  558. - Best fit for long-running, continuous, or shell-heavy work.
  559. **Cons**
  560. - **Container infra is a future build.** Until it lands, a `container` run **falls back to the durable DO** so it still executes in the cloud — so today you do not actually get a persistent shell from this selection.
  561. - Heaviest/most expensive surface (always-on-ish process, warm-keep billing).
  562. - Same Gateway / tenant-Anthropic-key requirement as the durable surface.
  563. ### How a type is selected at dispatch
  564. `resolveCloudAgent` reads the agent's `runtime_surface` from `ide_agents` (the engine is always the current version, never read); `resolveCloudSurface(agentSurface, hasExplicitHost)` then picks the surface — an explicitly-pinned host ⇒ `container`, otherwise the agent's chosen surface, defaulting to `durable`. `cloudAgentTypeLabel(surface)` produces the human label used for run attribution (`Cloud Agent (Durable Object)` / `Cloud Agent (Node/Container)`).
  565. ---
  566. ## LLM Surfaces
  567. Builderforce exposes **three distinct LLM systems** — they are easy to conflate, and each has its own code path. Scope work against the right one:
  568. | # | Surface | What it is | Status | Entry point |
  569. |---|---------|------------|--------|-------------|
  570. | **A** | **LLM Gateway** | Multi-vendor hosted chat proxy (failover, cooldowns, per-tenant budgets). Powers IDE Brain chat and studio prompt-expansion. | ✅ Shipped | [api/src/application/llm/](api/src/application/llm/), [DONE.md](DONE.md) (gateway PRD shipped; long tail in [ROADMAP.md](ROADMAP.md)) |
  571. | **B** | **Custom LLM Support** | Serve a user's fine-tuned LoRA agent to the `builderforce` CLI (`POST /api/agents/:id/chat`). | 🟡 Specced — P0 gaps open (see below) | "## Custom LLM Support" section below |
  572. | **C** | **In-IDE `llm` modality** | Build + train a custom model in the browser (dataset → WebGPU LoRA/Mamba → publish), then chat with it. | 🟢 Cloud path live; Local/Hybrid pending | [frontend/src/lib/modality.ts](frontend/src/lib/modality.ts), [LlmStudioPanel.tsx](frontend/src/components/LlmStudioPanel.tsx) |
  573. Cloud inference for the in-IDE modality (C) routes through the Gateway (A). On-device **Local** and **Hybrid** inference for (C) are gated until the Mamba WGSL kernel and R2 weights land — see the Consolidated Gap Register.
  574. ---
  575. ## Custom LLM Support
  576. > **IDE spec reference:** `ide-architecture (1).md` in the repository root — the Builderforce.ai IDE
  577. > architecture document (v2.0, March 2026).
  578. This section details every change the Builderforce.ai platform (IDE frontend +
  579. Cloudflare Worker backend) must make to fully support custom LLMs built through the IDE —
  580. so that fine-tuned agents can be stored, served, versioned, and consumed by `builderforce` CLI
  581. clients in production.
  582. ### Current State vs. Required State
  583. #### What exists today
  584. | Component | Status | Notes |
  585. | ------------------------------------- | ------ | ------------------------------------------------ |
  586. | In-browser LoRA training (WebGPU) | ✅ | `frontend/src/lib/training/` |
  587. | Adapter storage in R2 | ✅ | `artifacts/{projectId}/{jobId}/adapter.bin` |
  588. | Workforce Registry (publish / browse) | ✅ | `POST /api/agents`, `GET /api/agents` |
  589. | Agent package download | ✅ | `GET /api/agents/:id/package` → v1.0 JSON |
  590. | AI chat inference | ✅ | `POST /api/ai/chat` → Cloudflare AI / OpenRouter |
  591. | Mamba State Engine (in-browser) | ✅ | `frontend/src/lib/mamba-engine.ts` |
  592. | Agent Runtime SDK (in-browser) | ✅ | `frontend/src/lib/agent-runtime.ts` |
  593. #### What is missing
  594. | Gap | Impact | Priority |
  595. | ----------------------------------------------- | ------------------------------------------------- | -------- |
  596. | **No inference endpoint for custom agents** | `builderforce` CLI cannot run a trained agent | P0 |
  597. | **No LoRA adapter loading on inference server** | Training produces `.bin` but nothing serves it | P0 |
  598. | **No `mamba_state` in DB / package** | v2.0 agents cannot round-trip their memory | P0 |
  599. | **No CLI auth token** | CLI has no way to call Builderforce inference API | P0 |
  600. | **`POST /api/ai/chat` ignores `model` field** | Cannot route to `workforce-<id>` | P1 |
  601. | **No agent streaming inference** | CLI needs SSE chunked responses | P1 |
  602. | **No rate limiting per API key** | Inference endpoint open to abuse | P1 |
  603. | **No agent package v2.0** | Mamba state not shipped with download | P1 |
  604. | **No usage tracking per agent** | Cannot bill or monitor custom model usage | P2 |
  605. | **No model artifact versioning** | Cannot distinguish adapter generations | P2 |
  606. ### Database Schema Changes
  607. #### `agents` table — new columns
  608. ```sql
  609. ALTER TABLE agents
  610. ADD COLUMN package_version TEXT NOT NULL DEFAULT '1.0',
  611. ADD COLUMN mamba_state JSONB,
  612. ADD COLUMN inference_mode TEXT NOT NULL DEFAULT 'base',
  613. -- 'base' → use base_model directly (no adapter)
  614. -- 'lora' → load LoRA adapter from r2_artifact_key
  615. -- 'hybrid' → LoRA + Mamba state injection
  616. ADD COLUMN request_count INTEGER NOT NULL DEFAULT 0,
  617. ADD COLUMN last_used_at TIMESTAMPTZ;
  618. ```
  619. #### New `cli_api_keys` table
  620. ```sql
  621. CREATE TABLE cli_api_keys (
  622. id TEXT PRIMARY KEY,
  623. user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  624. key_hash TEXT NOT NULL UNIQUE,
  625. label TEXT,
  626. scopes TEXT NOT NULL DEFAULT 'inference:read',
  627. last_used_at TIMESTAMPTZ,
  628. request_count INTEGER NOT NULL DEFAULT 0,
  629. rate_limit INTEGER NOT NULL DEFAULT 1000,
  630. created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  631. revoked_at TIMESTAMPTZ
  632. );
  633. CREATE INDEX cli_api_keys_user_idx ON cli_api_keys(user_id);
  634. CREATE INDEX cli_api_keys_hash_idx ON cli_api_keys(key_hash);
  635. ```
  636. #### New `agent_inference_logs` table
  637. ```sql
  638. CREATE TABLE agent_inference_logs (
  639. id TEXT PRIMARY KEY,
  640. agent_id TEXT NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
  641. cli_key_id TEXT REFERENCES cli_api_keys(id) ON DELETE SET NULL,
  642. model_ref TEXT NOT NULL,
  643. prompt_tokens INTEGER,
  644. completion_tokens INTEGER,
  645. latency_ms INTEGER,
  646. status TEXT NOT NULL,
  647. error_message TEXT,
  648. created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
  649. );
  650. CREATE INDEX agent_inference_logs_agent_idx ON agent_inference_logs(agent_id);
  651. CREATE INDEX agent_inference_logs_key_idx ON agent_inference_logs(cli_key_id);
  652. ```
  653. ### New Worker Routes
  654. #### `POST /api/agents/:id/chat` — Agent Inference
  655. Accepts an OpenAI-compatible chat completion request, resolves the agent's LoRA adapter, runs inference, and streams tokens back.
  656. ```typescript
  657. app.post("/api/agents/:id/chat", async (c) => {
  658. const keyId = await authenticateCliKey(c);
  659. if (!keyId) return c.json({ error: "Unauthorized" }, 401);
  660. const agent = await db.query("SELECT * FROM agents WHERE id = $1", [c.req.param("id")]);
  661. if (!agent) return c.json({ error: "Agent not found" }, 404);
  662. const body = await c.req.json<ChatRequest>();
  663. const result = await runAgentInference({ agent, messages: body.messages, stream: body.stream ?? false, env: c.env });
  664. c.executionCtx.waitUntil(logInference({ agentId: agent.id, keyId, ...result.usage, env: c.env }));
  665. return result.response;
  666. });
  667. ```
  668. #### `GET/PUT /api/agents/:id/mamba-state` — Mamba State Sync
  669. - `GET` — returns the stored Mamba state snapshot (if any)
  670. - `PUT` — accepts an updated state from a CLI session; keeps server-side state in sync with `.builderforce/memory/mamba-state.json`
  671. #### `POST /api/auth/cli-key` — Issue CLI API Key
  672. Issues a new CLI key scoped to inference. Requires a valid web token. The `rawKey` is returned once and stored only as a SHA-256 hash. The user saves it as `BUILDERFORCE_AGENTS_LINK_API_KEY`.
  673. #### `DELETE /api/auth/cli-key/:keyId` — Revoke CLI Key
  674. ### Updated Worker Routes
  675. #### `POST /api/ai/chat` — Workforce Routing
  676. Detects the `workforce-<agentId>` model prefix and delegates to the agent inference service:
  677. ```typescript
  678. // `coderclawllm/` is the legacy prefix, still accepted for existing clients.
  679. const workforceMatch = body.model?.match(/^(?:(?:builderforce|coderclawllm)\/)?workforce-(.+)$/);
  680. if (workforceMatch) {
  681. return forwardToAgentInference(c, workforceMatch[1], body);
  682. }
  683. return runStandardInference(c, body);
  684. ```
  685. The `builderforce` CLI can use `model: "builderforce/workforce-<agentId>"` with no endpoint change required.
  686. #### `POST /api/agents` — Accept Mamba State on Publish
  687. Accepts `mamba_state` and `package_version` fields. Sets `inference_mode`:
  688. - `"base"` if no `r2_artifact_key`
  689. - `"lora"` if `r2_artifact_key` present but no `mamba_state`
  690. - `"hybrid"` if both are present
  691. ### Inference Service Architecture
  692. The Hono Worker selects the inference backend using this priority:
  693. ```
  694. 1. r2_artifact_key IS NOT NULL AND inference service available
  695. → Custom inference service (LoRA adapter applied)
  696. 2. base_model matches a Cloudflare Workers AI model id
  697. → Cloudflare Workers AI (base model only)
  698. 3. base_model matches an OpenRouter model id
  699. → OpenRouter (base model only)
  700. 4. Fallback
  701. → Return 503 with { error: "Inference unavailable for this agent" }
  702. ```
  703. When the LoRA inference service is unavailable, the system degrades gracefully. The CLI surfaces the `X-Inference-Mode` header (`lora | hybrid | base | fallback-base | unavailable`) in the session banner.
  704. **Inference service call path:**
  705. ```
  706. builderforce CLI
  707. │
  708. ▼ POST /api/agents/:id/chat (Hono Worker)
  709. Cloudflare Worker (api.builderforce.ai)
  710. │ pre-sign R2 URL for adapter.bin (1hr TTL)
  711. ▼ POST https://inference.builderforce.ai/v1/lora-chat
  712. Inference Service (GPU Worker / Durable Object)
  713. │ LRU-cached adapter loading, base model, LoRA application
  714. ▼ SSE chunks forwarded back through the Hono Worker
  715. builderforce CLI
  716. ```
  717. **Recommended tech stack:** Rust/Axum or Python/FastAPI; `candle` or `transformers+PEFT`; SSE streaming; LRU cache for adapter bytes and loaded models.
  718. ### BuilderForce Agents CLI Authentication
  719. ```
  720. 1. builderforce init → link wizard
  721. 2. POST /api/auth/cli-key { label: machineName }
  722. 3. rawKey saved to ~/.builderforce/.env as BUILDERFORCE_AGENTS_LINK_API_KEY
  723. 4. Future requests: Authorization: Bearer <rawKey>
  724. ```
  725. ### IDE Frontend Changes
  726. **Training Panel (`AITrainingPanel.tsx`):**
  727. - Add "Export Mamba state" button after successful hybrid training run
  728. - Show inference mode indicator on completed jobs: `LoRA (r=8) 🧠 +Mamba → Hybrid`
  729. **Publish Panel (`AgentPublishPanel.tsx`):**
  730. - Include Mamba state checkbox in publish payload (v2.0)
  731. - Show `v2.0 🧠` / `v1.0` package version badge
  732. - Show CLI install command: `builderforce agent install <agentId>`
  733. **Agent State Viewer (`AgentStateViewer.tsx` — new component):**
  734. - Right-panel **🔬 State** tab showing Mamba state summary, channel heatmap, interaction history
  735. - "Sync to server" button calling `PUT /api/agents/:id/mamba-state`
  736. ### API Reference — New and Changed Endpoints
  737. | Method | Path | Auth | Description |
  738. | -------- | ----------------------------- | --------- | ------------------------------------------------------- |
  739. | `POST` | `/api/agents/:id/chat` | CLI key | Run inference on a custom agent (streaming SSE or JSON) |
  740. | `GET` | `/api/agents/:id/mamba-state` | CLI key | Fetch the stored Mamba SSM state snapshot |
  741. | `PUT` | `/api/agents/:id/mamba-state` | CLI key | Push an updated Mamba state from CLI session |
  742. | `POST` | `/api/auth/cli-key` | Web token | Issue a new CLI API key |
  743. | `DELETE` | `/api/auth/cli-key/:keyId` | Web token | Revoke a CLI API key |
  744. | `GET` | `/api/auth/cli-keys` | Web token | List all CLI API keys for the current user |
  745. | Method | Path | Change |
  746. | ------ | ------------------------- | ---------------------------------------------------------------------- |
  747. | `POST` | `/api/agents` | Accept `mamba_state`, `package_version` in body; set `inference_mode` |
  748. | `GET` | `/api/agents/:id/package` | Return v2.0 format when `mamba_state` is present |
  749. | `POST` | `/api/ai/chat` | Detect `workforce-<id>` model prefix → delegate to agent inference |
  750. ### End-to-End Flow: CLI Inference via Custom LLM
  751. ```
  752. 1. [CLI] Load project context → modelRef = "builderforce/workforce-<agentId>"
  753. 2. [CLI] Advance Mamba state → memoryContext
  754. 3. [CLI] POST https://api.builderforce.ai/api/ai/chat { model, messages, stream: true }
  755. 4. [Worker] Detect workforce prefix → agentId
  756. 5. [Worker] Authenticate CLI key → check rate limit
  757. 6. [Worker] Load agent from Neon → generate pre-signed R2 URL
  758. 7. [Worker] POST https://inference.builderforce.ai/v1/lora-chat
  759. 8. [Inference] Load/cache adapter → apply LoRA → stream tokens
  760. 9. [CLI] Render tokens in TUI
  761. 10. [CLI] Persist updated Mamba state → PUT /api/agents/<agentId>/mamba-state
  762. ```
  763. ---
  764. ## Avatar Filter
  765. The Avatar Filter is a user-facing feature that provides visibility into project status across multiple dimensions—primarily through a red-amber-green (RAG) status indicator per project. This feature enables stakeholders to quickly assess project health and prioritize work appropriately.
  766. ### Features
  767. | Feature | Description |
  768. |---------|-------------|
  769. | **Project Status Indicators** | Projects display a color-coded status: <br>• 🟢 **Green** – Healthy, on track, or resolved <br>• 🟡 **Amber** – At risk, delayed, or needs attention <br>• 🔴 **Red** – Blocked, critical, or requires immediate action |
  770. | **Audit Trail** | Every status change is logged to the `audit_log`, providing transparency into who made changes and when |
  771. | **List & Detail Views** | Projects can be filtered and sorted by status across list, table, and detail views; the project detail page exposes the reason and timestamp for each status change, with per-project audit entries viewable from the detail panel |
  772. | **Portfolio Widget** | A portfolio-level widget surfaces aggregate RAG status summaries for all projects under a portfolio, enabling high-level program health review across the entire portfolio |
  773. | **Notifications** | Configurable notifications can target projects by RAG status segment — e.g., notify when a project turns Amber or Red, or alert on all projects at risk — with user opt-in and retention policies |
  774. ### How It Works
  775. 1. **Status assignment:** Projects receive a RAG status based on configurable business rules. The default status is Green. Status is updated via manual action (with a documented reason) or through automated rules.
  776. 2. **Audit recording:** Every status change populates the `audit_log` with `project_id`, `old_status`, `new_status`, `changed_by`, `reason`, and a timestamp for full traceability.
  777. 3. **Presentation:** Portfolio widgets and board list/detail views expose the current status and recent status transitions, with per-status filtering and sorting.
  778. 4. **Notifications:** Segments (e.g., at-risk projects) can be selected for proactive alerts when a project's status changes below a threshold, subject to user notification preferences.
  779. ### Configuration Options
  780. - **Default project status:** Green (configurable per portfolio or tenant).
  781. - **Compliance flags (360 indicators):** Controls whether 360 "Direction" health tracks and surfaces the RAG status meta indicator.
  782. - **Sentiment threshold:** Rules that determine when a project transitions to Amber vs. Red (e.g., number of recent issues, deviation from plan, or overdue tasks).
  783. - **Retention:** Configure how long audit log entries for status changes are retained (per tenant / row-level policy).
  784. ### Implementation Stages
  785. 1. **Schema enrichment:** Extend project and audit_log records to include RAG status fields and reason for change.
  786. 2. **Business rules & weights:** Define the logic for converting project signals (issues, deviations, overdue tasks) into a RAG status.
  787. 3. **Status change workflow:** Provide UI widgets for manual status change with required reason capture, and automated rule-based transitions.
  788. 4. **Depth of audit detail:** Configure how granular each status audit entry is — normalized fields, change summaries, or free-form notes.
  789. 5. **Portfolio & board surfaces:** Build list/detail views and portfolio widgets showing aggregate RAG distribution with drill-down filtering.
  790. 6. **Notifications by segment:** Implement per-trigger notification segments for at-risk program alerts.
  791. ### Project Health Dashboard
  792. - **List and detail views** show a status pill (Green/Amber/Red) with per-status filters and sorting.
  793. - **Project detail pages** expose the last status change (who changed it, when, and the reason) along with the complete audit entry history.
  794. - **Portfolio widget** surfaces aggregate counts by RAG status and supports drill-down to filtered project lists.
  795. - **Notifications** can target groups of projects organized by RAG status for proactive health monitoring.
  796. ### Status Transitions
  797. - Projects flagged as Amber can be downgraded to Green upon creation of an actionable remediation subtask or resolution of the triggering event.
  798. - Projects flagged as Red can return to Green after the blocking condition is resolved and the resolution is approved through the standard workflow.
  799. - All transitions are recorded in the audit log with the change reason, ensuring a complete lineage of project health decisions.
  800. ---
  801. ## Contributing
  802. Please see **[CONTRIBUTING.md](./CONTRIBUTING.md)** for the full contribution guidelines, including the branch naming convention, PR template, code quality gates, and the pull request lifecycle.
  803. ---
  804. ## License
  805. This project is licensed under the **MIT License** — see the [LICENSE](./LICENSE) file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.