Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(assistant): turn Alfa into MSO cockpit

Rahmana857d0e5b86c
diff --git a/README.md b/README.md
index 2cb5395a..839dd411 100644
--- a/README.md
+++ b/README.md
@@ -74,6 +74,8 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
**Extend** — Alfa AI, modular slices, and custom apps.
- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
+- **Use Alfa Cockpit** — the in-browser assistant now surfaces selected high-value MSO runtime context at the point of execution: active provider/model, searchable project context, trusted host Skills, typed-memory status, native agent sessions, same-principal local-agent presence, pending approvals, and one Activity & Runs timeline. The Cockpit intentionally does **not** claim full CLI parity; credentials/server wiring stay in Settings and dangerous actions still use Alfa's existing approval cards. The same read-model is scriptable as `mso cockpit [project]` / `mso cockpit search <query>`, so the UI does not own a parallel project/session/memory implementation.
+- **Run saved Automations for real** — browser-local automation recipes now re-enter Alfa's normal tool loop instead of only narrating their steps. Reads execute through the existing host bindings; write/exec steps keep the same per-call human approval gate. Playbook starter prompts also appear as bounded quick actions in an empty chat.
- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — MSO exposes one generic OAuth MCP server. ChatGPT gets a source-generated compact static profile with complete title/safety/security metadata, resource-bound OAuth + rotating refresh tokens, while other MCP clients can use the full catalog. Exact current counts and hashes live in [the generated MCP catalog](./docs/generated/MCP-CATALOG.md) so this README does not freeze a stale scanner count. Project-owned MCP tool names never enter the global list: discover/call them dynamically through the generic `project_mcp_tools` / `project_mcp_call` seam. See the [ChatGPT custom MCP guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves only agents with a current lease **and** a live receiver subscription, then creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. For ChatGPT/MCP sessions, `local_agent_inbox(wait_ms=...)` temporarily turns the foreground MCP call into that live receiver for up to 20 seconds, enabling direct two-way session messaging without a worker, DB, webhook, or broker. See [Local Agents](./docs/LOCAL-AGENTS.md).
@@ -426,6 +428,7 @@ An authenticated **Owner** session can read allowed files and run commands as th
- That boundary is browser-only: a plugin installed into Hermes or OpenClaw runs inside that daemon and can run host commands according to the daemon's own trust model.
- With a model provider configured, Alfa is a tool-calling agent, not a plain chatbot. Its complete current catalog and human-approval contract are generated from `frontend/slices/assistant/host-tools/*` and documented in `frontend/slices/assistant/CONTRACT.md`; avoid copying a tool count into overview docs because the catalog changes independently of MCP.
- Everything Alfa reads — file contents, command output, process lists — is sent to your model provider, and is re-sent on every following turn of the same run. BYOK means you own the key, not that the data stays on the box.
+- Choosing an Alfa Cockpit project adds a **bounded metadata snapshot** to each turn (project/path, branch/tree state, HEAD, knowledge availability, and recent project-memory topic titles). It does not inject raw project knowledge or raw repo-memory bodies. Cockpit also masks non-`normal` typed-memory keys/values as `Private memory`; selecting a project is context, never mutation permission.
- Treat any file Alfa reads as untrusted input. The approval card is the only thing between text hidden inside a file and an `exec.run`. Read the command on the card, not Alfa's summary of it.
- Agents and Skills group tools for your own convenience. They are not a permission boundary: every agent can call every tool.
- `exec.run` is not sandboxed. Its cwd is bounded to your write roots, but the command itself runs in your login shell as the service user. The destructive-command denylist is a short accident tripwire, not a guard.
diff --git a/app/api/v1/alfa/cockpit/route.test.ts b/app/api/v1/alfa/cockpit/route.test.ts
new file mode 100644
index 00000000..e6df1e4c
--- /dev/null
+++ b/app/api/v1/alfa/cockpit/route.test.ts
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const mocks = vi.hoisted(() => ({
+ context: { current: { role: "owner", session: { device_id: "owner-device" } } as null | { role: string; session: { device_id: string } } },
+ readConfig: vi.fn(), listProjects: vi.fn(), resolveProjectHint: vi.fn(), projectGitSnapshot: vi.fn(), inspectProject: vi.fn(),
+ readServers: vi.fn(), publicServers: vi.fn(), detectConvex: vi.fn(), readKnowledge: vi.fn(), repoMemory: vi.fn(),
+ sessions: vi.fn(), agents: vi.fn(), memories: vi.fn(), typed: vi.fn(), telemetry: vi.fn(),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: vi.fn(async () => mocks.context.current) }));
+vi.mock("@/lib/config/store", () => ({ readConfig: mocks.readConfig, DEFAULT_PROVIDER: "anthropic" }));
+vi.mock("@/lib/models/defaults", () => ({ defaultModelFor: vi.fn(() => "default-model") }));
+vi.mock("@/lib/host/projects-api", () => ({
+ listProjects: mocks.listProjects, resolveProjectHint: mocks.resolveProjectHint, projectGitSnapshot: mocks.projectGitSnapshot,
+ inspectProject: mocks.inspectProject, readProjectMcpServers: mocks.readServers, publicProjectMcpServers: mocks.publicServers,
+ detectProjectConvex: mocks.detectConvex, readProjectKnowledge: mocks.readKnowledge,
+}));
+vi.mock("@/lib/orchestration/repo-memory", () => ({ searchRepoMemory: mocks.repoMemory }));
+vi.mock("@/lib/agent/session-query", () => ({ ownerSessionSummaries: mocks.sessions }));
+vi.mock("@/lib/agent/local-agent-directory", () => ({ listLocalAgents: mocks.agents }));
+vi.mock("@/lib/agent/legacy-owner-memory", () => ({ listMemories: mocks.memories }));
+vi.mock("@/lib/agent/memory-store", () => ({ queryAgentMemory: mocks.typed, agentMemoryTelemetry: mocks.telemetry }));
+
+const { GET } = await import("./route");
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.context.current = { role: "owner", session: { device_id: "owner-device" } };
+ mocks.readConfig.mockResolvedValue({ provider: "openai", model: "gpt-test", tokenSaver: "ponytail" });
+ mocks.listProjects.mockResolvedValue({ total: 1, hasMore: false, scan: { truncated: false }, projects: [{ id: "root/mso", name: "mso", path: "/srv/mso", packageName: "mso", git: { branch: "main", head: "abcdef" } }] });
+ mocks.sessions.mockResolvedValue([{ id: "s1", name: "luna", source: "cli", title: "Debug updater", updatedAt: "2026-09-04T00:00:00Z", estimatedTokens: 1200, eventCount: 4 }]);
+ mocks.agents.mockResolvedValue([{ id: "s2", name: "milo", label: "[milo]", status: "idle", title: "Worker", lastSeenAt: "2026-09-04T00:00:00Z" }]);
+ mocks.memories.mockResolvedValue([{ id: "legacy1", text: "prefers concise output", createdAt: 1 }]);
+ mocks.typed.mockResolvedValue({ records: [
+ { record: { id: "m1", document: "USER.md", key: "editor", value: "zed", kind: "semantic", confidence: 1, sensitivity: "normal", provenance: { authority: "explicit", observedAt: "2026-09-04T00:00:00Z" } }, conflicts: [] },
+ { record: { id: "m2", document: "MEMORY.md", key: "secret", value: "do-not-leak", kind: "semantic", confidence: 1, sensitivity: "private", provenance: { authority: "explicit", observedAt: "2026-09-04T00:00:00Z" } }, conflicts: [] },
+ ] });
+ mocks.telemetry.mockResolvedValue({ liveRecords: 2, archivedRecords: 4, totalRecords: 6, resolvedKeys: 2, conflictKeys: 0, futureScheduled: 0, archiveSegments: 1 });
+});
+
+describe("Alfa cockpit read model", () => {
+ it("requires owner role before reading host state", async () => {
+ mocks.context.current = { role: "operator", session: { device_id: "operator" } };
+ const response = await GET(new NextRequest("http://localhost/api/v1/alfa/cockpit"));
+ expect(response.status).toBe(403);
+ expect(mocks.listProjects).not.toHaveBeenCalled();
+ });
+
+ it("aggregates existing SSOT domains and masks non-normal typed memory values", async () => {
+ const response = await GET(new NextRequest("http://localhost/api/v1/alfa/cockpit"));
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body.model).toEqual({ provider: "openai", model: "gpt-test", tokenSaver: "ponytail" });
+ expect(body.projects.rows[0]).toMatchObject({ id: "root/mso", name: "mso" });
+ expect(body.sessions[0]).toMatchObject({ name: "luna", source: "cli" });
+ expect(body.localAgents[0]).toMatchObject({ label: "[milo]", status: "idle" });
+ expect(body.typedMemory.records[0]).toMatchObject({ key: "editor", value: "zed" });
+ expect(body.typedMemory.records[1]).toMatchObject({ key: "Private memory", value: "Private memory", sensitivity: "private" });
+ expect(body.legacyMemoryCount).toBe(1);
+ expect(body.memories).toBeUndefined();
+ expect(mocks.agents).toHaveBeenCalledWith("cli:owner-device", { includeOffline: false });
+ });
+
+ it("searches projects without loading the heavier cockpit domains", async () => {
+ mocks.listProjects.mockResolvedValueOnce({ total: 1, hasMore: false, scan: { truncated: false }, projects: [{ id: "root/alpha", name: "alpha", path: "/srv/alpha" }] });
+ const response = await GET(new NextRequest("http://localhost/api/v1/alfa/cockpit?q=alpha"));
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({ projects: { rows: [{ id: "root/alpha", name: "alpha" }] } });
+ expect(mocks.listProjects).toHaveBeenCalledWith({ query: "alpha", limit: 30 });
+ expect(mocks.readConfig).not.toHaveBeenCalled();
+ expect(mocks.sessions).not.toHaveBeenCalled();
+ expect(mocks.typed).not.toHaveBeenCalled();
+ });
+
+ it("adds a compact selected-project snapshot without returning raw knowledge content", async () => {
+ mocks.resolveProjectHint.mockResolvedValue({ id: "root/mso", name: "mso", path: "/srv/mso", rootId: "root", root: "/srv", aliases: [] });
+ mocks.projectGitSnapshot.mockResolvedValue({ available: true, branch: "main", clean: false, head: { sha: "abcdef123456", subject: "change" } });
+ mocks.inspectProject.mockResolvedValue({ package: { name: "mso", version: "1.0.0" }, capabilities: { mcp: true } });
+ mocks.readServers.mockResolvedValue([{ name: "github" }]);
+ mocks.publicServers.mockReturnValue([{ name: "github" }]);
+ mocks.detectConvex.mockResolvedValue({ detected: true, configured: true, mode: "self-hosted" });
+ mocks.readKnowledge.mockResolvedValue({ exists: true, bytes: 123, sha256: "deadbeef", content: "private project knowledge" });
+ mocks.repoMemory.mockResolvedValue([{ score: 0.9, record: { id: "rm1", kind: "decision", status: "confirmed", title: "Use bounded context", result: "raw result must stay server-side", updatedAt: "2026-09-04T00:00:00Z" } }]);
+
+ const response = await GET(new NextRequest("http://localhost/api/v1/alfa/cockpit?project=root%2Fmso"));
+ const body = await response.json();
+ expect(body.selectedProject).toMatchObject({
+ project: { id: "root/mso", name: "mso" },
+ git: { branch: "main", clean: false },
+ knowledge: { exists: true, bytes: 123, sha256: "deadbeef" },
+ recentMemory: [{ title: "Use bounded context", kind: "decision" }],
+ });
+ expect(JSON.stringify(body.selectedProject)).not.toContain("private project knowledge");
+ expect(JSON.stringify(body.selectedProject)).not.toContain("raw result must stay server-side");
+ });
+});
diff --git a/app/api/v1/alfa/cockpit/route.ts b/app/api/v1/alfa/cockpit/route.ts
new file mode 100644
index 00000000..229de1f9
--- /dev/null
+++ b/app/api/v1/alfa/cockpit/route.ts
@@ -0,0 +1,152 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { readConfig, DEFAULT_PROVIDER } from "@/lib/config/store";
+import { defaultModelFor } from "@/lib/models/defaults";
+import {
+ detectProjectConvex,
+ inspectProject,
+ listProjects,
+ projectGitSnapshot,
+ publicProjectMcpServers,
+ readProjectKnowledge,
+ readProjectMcpServers,
+ resolveProjectHint,
+} from "@/lib/host/projects-api";
+import { searchRepoMemory } from "@/lib/orchestration/repo-memory";
+import { ownerSessionSummaries } from "@/lib/agent/session-query";
+import { listLocalAgents } from "@/lib/agent/local-agent-directory";
+import { listMemories } from "@/lib/agent/legacy-owner-memory";
+import { agentMemoryTelemetry, queryAgentMemory } from "@/lib/agent/memory-store";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+const PROJECT_PAGE_SIZE = 60;
+const RECENT_MEMORY_LIMIT = 6;
+
+function routeError(error: unknown) {
+ const message = error instanceof Error ? error.message : "Alfa cockpit failed";
+ const status = /not found/i.test(message) ? 404 : /ambiguous/i.test(message) ? 409 : 500;
+ return NextResponse.json({ error: message.slice(0, 240) }, { status });
+}
+
+export async function GET(req: NextRequest) {
+ const context = await getSessionContext();
+ if (context?.role !== "owner") return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
+
+ const principal = `cli:${context.session.device_id}`;
+ const projectHint = String(req.nextUrl.searchParams.get("project") || "").trim();
+ const projectQuery = String(req.nextUrl.searchParams.get("q") || "").trim().slice(0, 120);
+
+ try {
+ if (projectQuery) {
+ const projectList = await listProjects({ query: projectQuery, limit: 30 });
+ return NextResponse.json({
+ projects: {
+ total: projectList.total, hasMore: projectList.hasMore, scan: projectList.scan,
+ rows: projectList.projects.map((project) => ({
+ id: project.id, name: project.name, path: project.path,
+ packageName: project.packageName, packageVersion: project.packageVersion, git: project.git,
+ })),
+ },
+ });
+ }
+
+ const [cfg, projectList, sessions, agents, memories, typedMemory, memoryTelemetry] = await Promise.all([
+ readConfig(),
+ listProjects({ limit: PROJECT_PAGE_SIZE }),
+ ownerSessionSummaries(10),
+ listLocalAgents(principal, { includeOffline: false }),
+ listMemories(),
+ queryAgentMemory(principal, { limit: 10 }),
+ agentMemoryTelemetry(principal),
+ ]);
+ const provider = cfg.provider || DEFAULT_PROVIDER;
+
+ let selectedProject: Record<string, unknown> | null = null;
+ if (projectHint) {
+ const project = await resolveProjectHint(projectHint);
+ if (!project) throw new Error(`project not found: ${projectHint}`);
+ const [git, inspected, servers, database, knowledge, recentMemory] = await Promise.all([
+ projectGitSnapshot(project.path),
+ inspectProject(project),
+ readProjectMcpServers(project.path),
+ detectProjectConvex(project.path),
+ readProjectKnowledge(project.path),
+ searchRepoMemory(project.path, { limit: RECENT_MEMORY_LIMIT }),
+ ]);
+ selectedProject = {
+ project: { id: project.id, name: project.name, path: project.path, rootId: project.rootId },
+ git,
+ package: inspected.package,
+ capabilities: inspected.capabilities ?? {},
+ database,
+ integrations: { projectMcp: publicProjectMcpServers(servers) },
+ knowledge: { exists: knowledge.exists, bytes: knowledge.bytes, sha256: knowledge.sha256 },
+ recentMemory: recentMemory.map(({ record, score }) => ({
+ id: record.id,
+ kind: record.kind,
+ status: record.status,
+ title: record.title,
+ updatedAt: record.updatedAt,
+ score,
+ })),
+ };
+ }
+
+ return NextResponse.json({
+ model: { provider, model: cfg.model || defaultModelFor(provider), tokenSaver: cfg.tokenSaver ?? "off" },
+ projects: {
+ total: projectList.total,
+ hasMore: projectList.hasMore,
+ scan: projectList.scan,
+ rows: projectList.projects.map((project) => ({
+ id: project.id,
+ name: project.name,
+ path: project.path,
+ packageName: project.packageName,
+ packageVersion: project.packageVersion,
+ git: project.git,
+ })),
+ },
+ selectedProject,
+ sessions: sessions.map((session) => ({
+ id: session.id,
+ name: session.name,
+ source: session.source,
+ title: session.title,
+ updatedAt: session.updatedAt,
+ cwd: session.cwd,
+ estimatedTokens: session.estimatedTokens,
+ eventCount: session.eventCount,
+ })),
+ localAgents: agents.map((agent) => ({
+ id: agent.id,
+ name: agent.name,
+ label: agent.label,
+ status: agent.status,
+ title: agent.title,
+ cwd: agent.cwd,
+ lastSeenAt: agent.lastSeenAt,
+ })),
+ legacyMemoryCount: memories.length,
+ typedMemory: {
+ telemetry: memoryTelemetry,
+ records: typedMemory.records.map(({ record, conflicts }) => ({
+ id: record.id,
+ document: record.document,
+ key: record.sensitivity === "normal" ? record.key : "Private memory",
+ value: record.sensitivity === "normal" ? record.value : "Private memory",
+ kind: record.kind,
+ confidence: record.confidence,
+ sensitivity: record.sensitivity,
+ authority: record.provenance.authority,
+ observedAt: record.provenance.observedAt,
+ conflictCount: conflicts.length,
+ })),
+ },
+ });
+ } catch (error) {
+ return routeError(error);
+ }
+}
diff --git a/bin/mso b/bin/mso
index a5f13725..1861f40c 100755
--- a/bin/mso
+++ b/bin/mso
@@ -62,6 +62,7 @@
#
# AI + state
# ai <prompt…> One turn with the assistant
+# cockpit [project] Alfa/MSO runtime context; search with `cockpit search <query>`
# threads * Conversation history: list | show | rm
# agent-sessions * Durable MSO Agent sessions: list | show | create
# agents * Native local session agents: list | send | inbox
@@ -128,7 +129,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.12.0"
+VERSION="1.12.1"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 8888c776..1db346f5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
## 2026-09-04
+**Added**
+
+- `assistant` turn Alfa into MSO cockpit
+
**Changed**
- `mcp` dedupe ChatGPT CSP metadata
diff --git a/docs/CLI.md b/docs/CLI.md
index e445088b..5b665090 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -102,6 +102,7 @@ Commands:
AI + state
ai <prompt…> One turn with the assistant
+ cockpit [project] Alfa/MSO runtime context; search with `cockpit search <query>`
threads * Conversation history: list | show | rm
agent-sessions * Durable MSO Agent sessions: list | show | create
agents * Native local session agents: list | send | inbox
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 3af3c00a..b5550432 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -7,6 +7,12 @@
- **MCP App contextual landing hardening (2026-09-03):** `Open in MSO` no longer lands on an idle desktop. Workflow/VPS/project/diff cards target `/assistant/mcp`, `/monitor`, `/files`, and `/code`; the shell also recognizes ChatGPT's root `redirectUrl=https://chatgpt.com/c/...` handoff and redirects it to Alfa → MCP Activity so an already-cached v2 widget still produces a visible result. Assistant deep-link payloads now select their requested tab even when reusing an existing singleton window. MCP tool count, scopes, output schemas, and v2 resource URIs are unchanged.
- **Live-build chunk corruption eliminated (2026-09-03):** a production browser repro proved the shell/Settings crash was not a Settings logic regression: an in-place `next build` in the active service checkout replaced `.next` while the old Next process still served its boot-time manifest, making all 19 root-referenced chunks disappear and one observed JS request return `500 text/plain`. Production was recovered through `mso deploy`; shell + Settings then passed real authenticated Playwright on desktop/mobile with zero failed requests/console errors. `bun run build` is now a fail-closed wrapper that holds the checkout exclusion and refuses a same-checkout live runtime; `mso build` remains the out-of-tree proof and guarded deploy/update lifecycles invoke raw Next only after quiescence. Post-replacement validation now checks every root-referenced JS/CSS asset status+MIME, not one CSS/chunk. The Fresh 3 smoke scratch path moved out of protected `~/.mso`, and recursive `fs_mkdir` now securely supports missing parents while rejecting symlink escapes.
+## 2026-09-04 — Alfa Cockpit exposes MSO runtime context without duplicating the CLI (DONE)
+
+Alfa's browser surface had real host tools and approvals, but much of the runtime state that makes `mso` powerful was hidden behind terminal/MCP surfaces. The Assistant now has a responsive **Alfa Cockpit**: active provider/model with in-place model switch/test, bounded + searchable project selection, branch/tree/HEAD/package/knowledge metadata, trusted Host Skills, typed-memory telemetry/current records, native session summaries, same-principal local-agent presence, pending approval count, and an **Activity & Runs** view that combines Alfa host-tool events with MCP workflow activity at the presentation layer. The read-model route reuses existing project/session/memory/config domains; it does not create parallel stores. CLI parity is preserved with `mso cockpit [project]` / `mso cockpit search <query>`, which calls the same read-model instead of reimplementing the aggregation. Project scan truncation stays explicit, project search works beyond the first bounded page, raw `KNOWLEDGE.md`/repo-memory bodies are not returned, and private/restricted typed-memory keys/values are masked; legacy Alfa fact text and repo-memory result bodies are not copied into the Cockpit response.
+
+Selected project context is persisted as an `alfa.*` preference and sent per turn only as a capped metadata snapshot; it is explicitly not mutation permission and does not change Alfa's stable global host-tool catalog. The dock/mobile Alfa thread shows the same selected project and pending approvals. Browser-local “Skills” are now labelled **Playbooks**, Host Skills remain the real `SKILL.md` catalog, Playbook starters finally render as quick prompts, and saved Automations now execute by re-entering Alfa's normal agent/tool loop instead of only logging pretend steps—so read calls use the existing bindings and mutations still stop on the same human approval cards. Native agent sessions remain read-only summaries rather than being falsely presented as the current browser chat. Focused typecheck/ESLint/docs gates and cockpit/context/activity/automation tests pass; full repository verify and the official production build also pass on the combined CSP v5 + Alfa baseline.
+
## 2026-09-03 — Cognitive Runtime P10 memory retention & lifecycle
- **Cold-history retention before hard caps:** typed agent memory now starts deterministic retention at 1,400 live records or ~1.4 MiB and targets <=1,000 records / ~1 MiB by archiving only records whose effective interval has already ended. Current or future-effective facts are never selected; the existing 2,000-record / 2 MiB live-ledger limits remain fail-closed.
diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.md
index bfaf970a..579c5d2a 100644
--- a/docs/TESTING-HANDOFF.md
+++ b/docs/TESTING-HANDOFF.md
@@ -5,12 +5,15 @@ Update this file at the end of every manual or automated test session. Keep it f
## Current status
-The current release target is **MSO CLI 1.12.0**, MCP server `1.9.4`, toolset `2026.09.04.5`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.
+The current release target is **MSO CLI 1.12.1**, MCP server `1.9.4`, toolset `2026.09.04.5`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.
Current verified behavior:
- **2026-09-04 Cognitive Runtime public-claim audit:** source/main/origin + loopback/public production were revalidated on the latest concurrent baseline. Fresh reruns pass `bench:cognitive`, `bench:memory`, P9 200-correction calibration, P10 lifecycle, and P10 retrieval calibration. Current deterministic evidence: 100% required-tool recall, 96.6% active-schema reduction, memory 8/8, P9 6/6, P10 lifecycle 8/8, lexical/local-semantic 4/6 vs 3/6, graph fixture 3/3. Canonical raw comparison artifacts were re-hashed: P6 `e0b5e1e30a9f1e5b34624e42d4bb5195792e50129b74de7d4006906a99716ba5`, P7 two-run `a0c12961d142420f6ac334ff021bde7ab82faa89f9294107d3bd46823606a530`, P8 three-run `f70e2f5e8132f0808976ed69e2cb6769d2cec861d58612a8cca2ef5d80a7d838`, P8 cache `b4a2b1be5dc6edfb2ce8282eae64e3a4fc206cd043ecb825a1eae6a617c9f871`. The canonical P7 file is `mso-p7-repeat-full-2x9.json`; the similarly named `mso-p7-repeat-full-2runs.json` is a different, non-canonical run. Recomputed P7+P8 evidence is 5/5 perfect for both MSO and Hermes with 74.7% fewer normalized tokens/attempt, 12.8% lower mean average latency, and 34.1% lower mean per-run p50 for MSO on that exact matched nine-scenario corpus. P4/P5 exact numeric tables are historical-only because their exact raw artifacts were not independently revalidated in this audit. Cost/cache/OpenClaw remain unranked. Tool Forge source/non-Docker tests pass, but the local Forge Docker image was absent, so three Docker-only tests were correctly skipped and executable evaluation fails closed until explicitly provisioned.
- Fresh 3 current MCP contract: server `1.9.4` / toolset `2026.09.04.5`; ChatGPT receives **64 transport tools = 63 model/operator actions (34 read / 17 write / 12 exec) + app-only `workflow_status`**, while the full transport catalog is 88 tools / 87 model tools. Every ChatGPT action advertises `outputSchema`, the dedicated MCP Apps widget origin is `https://mso-ui.rahmanef.com`, and five official digest-verified Skills are exposed through the MCP Skills/resource extension. Exactly two MCP App resources are published: dedicated `ui://mso/workflow-progress-v3.html` plus universal `ui://mso/surface-v5.html`. `project_get`, `project_diff`, and `vps_status` are pure data tools with no UI template; Surface native views refresh them through MCP Apps `tools/call`. The Surface accepts no raw HTML/arbitrary URL; its only frame domain is `https://game.rahmanef.com`, and every Play Together iframe URL must remain under `/embed`. The normal Play Together shell stays anti-frame, while the dedicated embed namespace allows only `mso-ui.rahmanef.com`. Other MSO server scopes are not copied into this catalog.
-- MCP App navigation acceptance: a ChatGPT-opened root URL carrying `redirectUrl=https://chatgpt.com/c/...` must 307 to `/assistant/mcp`, then authenticated browser E2E must show the Alfa `MCP Activity` view. The dedicated workflow card targets `/assistant/mcp`; VPS/project/diff are native routes inside universal Surface v5 rather than independent widgets. Surface v5 plus workflow-progress-v3 are cache-busting resource URI changes, so ChatGPT must re-scan Fresh 3 after deployment.
+- MCP App navigation acceptance: a ChatGPT-opened root URL carrying `redirectUrl=https://chatgpt.com/c/...` must 307 to `/assistant/mcp`, then authenticated browser E2E must show the Alfa `Activity & Runs` view. The dedicated workflow card targets `/assistant/mcp`; VPS/project/diff are native routes inside universal Surface v5 rather than independent widgets. Surface v5 plus workflow-progress-v3 are cache-busting resource URI changes, so ChatGPT must re-scan Fresh 3 after deployment.
+- Alfa Cockpit acceptance: Assistant → Chat shows a compact project/model/activity bar; Cockpit opens as a desktop panel and mobile drawer; project search can select a project outside the first bounded page; selected project metadata reaches the next Alfa system prompt but raw `KNOWLEDGE.md`/repo-memory bodies do not; private typed-memory keys/values render as `Private memory`; Host Skills lazy-load from `/api/skills`; model switch stays within the configured provider; Activity & Runs shows local Alfa tool state alongside MCP workflow activity without treating the browser run as MCP `workflow_finish`.
+- Alfa Automation acceptance: a saved recipe's Run action switches to its configured persona and submits the ordered recipe through normal Alfa execution. Read steps may execute directly; write/exec steps must still park on the existing approval card. Playbook starter prompts appear as bounded empty-chat quick actions.
+
- P10 memory retention/lifecycle: isolated fixtures now archive only cold finished claims before the hard 2,000-record / 2 MiB live-ledger limits. Trigger/target are 1,400 -> <=1,000 live records (or ~1.4 MiB -> ~1 MiB); archive segments are content-addressed, owner-only and archive-before-ledger atomic. `bench:memory:lifecycle` is **8/8 deterministic** with a 1,400-correction seed ending at **1,000 live + 401 archived / two segments** and a 56-byte resolved projection. It verifies explicit archived-history retrieval, historical temporal resolution, aggregate-only no-content telemetry, `0700/0600` permissions, interrupted-commit live-wins semantics, backdated replacement over immutable archive, and frozen session A / fresh session B / resume-copy behavior. The P10 retrieval gate is **4/6 lexical** (synonym + Indonesian/English misses remain explicit); P10D also calibrates the existing local `mso-local-hybrid-v1` encoder on the same rows and gets **3/6** with zero network calls / zero persisted memory vectors, so production vector storage stays blocked by measured non-improvement rather than assumption. **3/3 two-hop relationship fixtures** keep graph storage blocked. The exact-history crowding bug (`Runtime-1` vs `Runtime-10...`) is fixed by exact phrase/token scoring; legacy `bench:memory` remains 100%.
- P9 memory calibration: isolated temporary-memory fixtures now cover repeated corrections, explicit-vs-observed authority, confidence/recency, future validity, forget, and history integrity. P9 fixed a real temporal privacy bug where `forget` could leave a future-scheduled claim that resurrected later; forget now closes all current/future-capable intervals while preserving already-ended history. Final 200-correction stress from source `d249da4`: **6/6 calibration scenarios**, existing memory benchmark **100%**, Cognitive Runtime memory gates **100%**; 200 ledger rows / 135,180 bytes resolve to 1 row / 58-byte compatibility projection (**99.96% smaller**) and history retrieval remains capped at 100. No calibrated case requires graph memory.
- P8 calibration: repeat aggregation now reports descriptive per-run spread without inferential claims; three new complete nine-scenario runs from source `51ae31f` were **27/27 task + 27/27 scenario-policy and 3/3 perfect runs for both agents**, with 54/54 row identity/provider/model/token-arithmetic checks passing. Combined with P7, both agents are **5/5 perfect**; five-run means are MSO vs Hermes 16,907.6 vs 66,791.1 normalized tokens/attempt (~74.7% lower for MSO), 18,985.9 vs 21,779.8 ms average latency, and 14,130.8 vs 21,457.2 ms per-run p50. New `bench:cache-calibration` final 4-round/12K-prefix run was 8/8 success; MSO cache-read was zero on 4/4 while Hermes naturally reported positive cache reads on 2/4 (9,728 + 19,968), but cache frequency is unranked because request envelopes differ. P8 also fixes false token non-comparability when independently valid normalized proof shapes vary across cache/no-cache rows. Cost remains non-comparable because attribution is asymmetric.
diff --git a/frontend/slices/appshell/components/alfa-thread.tsx b/frontend/slices/appshell/components/alfa-thread.tsx
index fb83207a..ccb70ad2 100644
--- a/frontend/slices/appshell/components/alfa-thread.tsx
+++ b/frontend/slices/appshell/components/alfa-thread.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
-import { Sparkles } from "lucide-react";
+import { FolderGit2, ShieldCheck, Sparkles } from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
import { useAlfaBusy, useAlfaMessages, sendToAlfa, alfaReady, stopAlfa, type AlfaContext } from "../lib/alfa";
@@ -10,7 +10,8 @@ import { openWindow } from "../lib/store";
import { ChatComposer } from "./chat-composer";
import { ApprovalCard } from "./approval-card";
import type { ToolCard } from "./message-bubble";
-import { resolveAlfaApproval } from "../lib/alfa-approvals";
+import { resolveAlfaApproval, useAlfaApprovalCount } from "../lib/alfa-approvals";
+import { useAlfaProjectContext } from "../lib/alfa-work-context";
// The Alfa conversation, rendered wherever it is needed — the desktop right dock,
// the mobile sheet, anywhere else later. It owns NO conversation state: everything
@@ -26,6 +27,8 @@ export function AlfaThread({ ctx, placeholder }: { ctx: AlfaContext; placeholder
const busy = useAlfaBusy();
const apps = useApps();
const bottom = useRef<HTMLDivElement>(null);
+ const project = useAlfaProjectContext();
+ const approvals = useAlfaApprovalCount();
useEffect(() => {
bottom.current?.scrollIntoView({ behavior: "smooth", block: "end" });
@@ -50,6 +53,17 @@ export function AlfaThread({ ctx, placeholder }: { ctx: AlfaContext; placeholder
return (
<div className="flex h-full min-h-0 flex-col">
+ {project || approvals ? (
+ <button
+ type="button"
+ className="flex min-h-9 shrink-0 items-center gap-2 border-b border-border/70 px-3 text-left text-[10px] text-muted-foreground hover:bg-secondary/40"
+ onClick={() => openWindow("assistant", "Alfa")}
+ >
+ {project ? <><FolderGit2 className="size-3.5" /><span className="max-w-[55%] truncate font-medium text-foreground">{project.name}</span>{project.branch ? <span className="truncate">· {project.branch}</span> : null}</> : null}
+ <span className="flex-1" />
+ {approvals ? <span className="flex items-center gap-1 text-warning"><ShieldCheck className="size-3.5" />{approvals} pending</span> : null}
+ </button>
+ ) : null}
<ScrollArea className="min-h-0 flex-1">
<div className="flex flex-col gap-2.5 p-3">
{messages.length === 0 ? (
diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.ts
index 69f8a325..8e325f70 100644
--- a/frontend/slices/appshell/index.ts
+++ b/frontend/slices/appshell/index.ts
@@ -128,6 +128,7 @@ export * from "./lib/mentions";
export * from "./lib/alfa";
export * from "./lib/alfa-sources";
export * from "./lib/alfa-approvals";
+export * from "./lib/alfa-work-context";
export { MessageBubble } from "./components/message-bubble";
export type { ChatMessage, ToolCard } from "./components/message-bubble";
export { ApprovalCard } from "./components/approval-card";
diff --git a/frontend/slices/appshell/lib/alfa-approvals.ts b/frontend/slices/appshell/lib/alfa-approvals.ts
index 7471ba59..be229a78 100644
--- a/frontend/slices/appshell/lib/alfa-approvals.ts
+++ b/frontend/slices/appshell/lib/alfa-approvals.ts
@@ -1,5 +1,7 @@
"use client";
+import { useSyncExternalStore } from "react";
+
// Where a parked mutate-tool call waits for the user.
//
// This map used to live inside the Assistant panel, which made an approval
@@ -16,10 +18,26 @@
type Decision = { approve: boolean; remember: boolean };
const pending = new Map<string, (d: Decision) => void>();
+const subscribers = new Set<() => void>();
+let pendingCount = 0;
+
+const emit = () => subscribers.forEach((fn) => fn());
+const subscribe = (fn: () => void) => { subscribers.add(fn); return () => subscribers.delete(fn); };
+const getPendingCount = () => pendingCount;
+const refreshCount = () => {
+ const next = pending.size;
+ if (next === pendingCount) return;
+ pendingCount = next;
+ emit();
+};
+
+export function useAlfaApprovalCount(): number {
+ return useSyncExternalStore(subscribe, getPendingCount, () => 0);
+}
/** Called by the tool binding; resolves when any surface answers the card. */
export function awaitAlfaApproval(id: string): Promise<Decision> {
- return new Promise<Decision>((resolve) => pending.set(id, resolve));
+ return new Promise<Decision>((resolve) => { pending.set(id, resolve); refreshCount(); });
}
/** Called by whichever surface rendered the card. */
@@ -27,6 +45,7 @@ export function resolveAlfaApproval(id: string, approve: boolean, remember: bool
const r = pending.get(id);
if (!r) return;
pending.delete(id);
+ refreshCount();
r({ approve, remember });
}
@@ -34,4 +53,5 @@ export function resolveAlfaApproval(id: string, approve: boolean, remember: bool
export function clearAlfaApprovals(): void {
pending.forEach((r) => r({ approve: false, remember: false }));
pending.clear();
+ refreshCount();
}
diff --git a/frontend/slices/appshell/lib/alfa-work-context.ts b/frontend/slices/appshell/lib/alfa-work-context.ts
new file mode 100644
index 00000000..7b13dc38
--- /dev/null
+++ b/frontend/slices/appshell/lib/alfa-work-context.ts
@@ -0,0 +1,67 @@
+"use client";
+
+import { useSyncExternalStore } from "react";
+
+export type AlfaProjectContext = {
+ id: string;
+ name: string;
+ path: string;
+ branch?: string;
+ clean?: boolean;
+ head?: string;
+ knowledge?: boolean;
+ recentMemoryTitles?: string[];
+};
+
+const KEY = "alfa.selectedProject";
+let selectedProjectId = "";
+let projectContext: AlfaProjectContext | null = null;
+const subs = new Set<() => void>();
+const emit = () => subs.forEach((fn) => fn());
+const subscribe = (fn: () => void) => { subs.add(fn); return () => subs.delete(fn); };
+const getSelected = () => selectedProjectId;
+const getContext = () => projectContext;
+
+function storage(): Storage | null {
+ try { return typeof localStorage === "undefined" ? null : localStorage; } catch { return null; }
+}
+
+if (typeof window !== "undefined") {
+ selectedProjectId = storage()?.getItem(KEY) ?? "";
+ window.addEventListener("storage", (event) => {
+ if (event.key !== KEY && event.key !== null) return;
+ selectedProjectId = storage()?.getItem(KEY) ?? "";
+ projectContext = null;
+ emit();
+ });
+}
+
+export function useAlfaSelectedProject(): string {
+ return useSyncExternalStore(subscribe, getSelected, () => "");
+}
+
+export function alfaSelectedProject(): string { return selectedProjectId; }
+
+export function setAlfaSelectedProject(id: string): void {
+ const next = id.trim();
+ if (next === selectedProjectId) return;
+ selectedProjectId = next;
+ projectContext = null;
+ try {
+ if (next) storage()?.setItem(KEY, next);
+ else storage()?.removeItem(KEY);
+ } catch { /* in-memory selection still works */ }
+ emit();
+}
+
+export function useAlfaProjectContext(): AlfaProjectContext | null {
+ return useSyncExternalStore(subscribe, getContext, () => null);
+}
+
+export function alfaProjectContext(): AlfaProjectContext | null { return projectContext; }
+
+export function setAlfaProjectContext(value: AlfaProjectContext | null): void {
+ if (JSON.stringify(value) === JSON.stringify(projectContext)) return;
+ projectContext = value;
+ emit();
+}
diff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.md
index a4829ee5..aec64a59 100644
--- a/frontend/slices/assistant/CONTRACT.md
+++ b/frontend/slices/assistant/CONTRACT.md
@@ -50,15 +50,14 @@ derived, never authored. `lib/tools.test.ts` fails if the two ever diverge.
## Playbook (the localStorage `Skill` type)
-**A named bundle of instructions a user assembles.** Shown in the Assistant's
-Skills tab.
+**A named bundle of instructions a user assembles.** Shown in the Assistant's **Playbooks** tab.
| | |
|---|---|
| Shape | `Skill` — `lib/types.ts` |
| Source of truth | `localStorage["alfa.skills"]`, seeded from `PRESET_SKILLS` |
| Lifecycle | Per browser, user-editable |
-| Written by | The user, via the Skills tab |
+| Written by | The user, via the Playbooks tab |
Tool ids are MIGRATED on read (`lib/store.ts` `migrateRows`), not dropped: a bundle
saved before the catalogs converged has its old ids mapped to the current ones, and
@@ -66,10 +65,9 @@ only ids that never had an executable counterpart are removed. Dropping instead
mapping would have emptied the five builtin bundles for every existing install —
`store-migration.test.ts` is what holds that line.
-> **Naming.** This type is called `Skill` in code and "Skills" in the UI, which
-> collides with the unrelated concept below. The rename is **Playbook**, not
-> "Toolset": once scoping is deleted a bundle grants no tools, so "Toolset" would
-> just be the next false name. Not done yet — see Known gaps.
+> **Naming.** The persisted TypeScript type remains `Skill` for compatibility, but the
+> product surface calls it **Playbook**. This avoids colliding with host `SKILL.md`
+> while preserving existing `alfa.skills` backups and migrations.
## Skill (a `SKILL.md` on disk)
@@ -118,15 +116,27 @@ the wrong persona.
---
+## Alfa Cockpit: one execution surface, existing sources of truth
+
+The Assistant chat now has a compact **Cockpit** bar + responsive panel (desktop side panel, mobile drawer). It is a presentation/read-model over existing MSO domains, not a second runtime:
+
+- `GET /api/v1/alfa/cockpit` owner-gates and aggregates model selection, bounded/searchable project discovery, selected-project Git/package/capabilities/knowledge metadata, native session summaries, same-principal local-agent presence, the legacy Alfa fact count, and typed-memory state.
+- Project search has a lightweight `?q=` path so the first bounded page is not treated as the whole host. A truncated scan is shown as incomplete rather than as an absence claim.
+- The selected project id persists under `alfa.selectedProject`, so Settings → Backup includes it automatically. The loaded snapshot is shared with the dock/mobile Alfa surface.
+- Host `SKILL.md` rows stay on the existing `/api/skills` SSOT and lazy-load only when Cockpit opens. `untrusted` rows are visible for review but are not one-click executable; trusted rows send an exact-id `skills.read` request through Alfa's existing host-tool loop.
+- Typed memory is owner-visible as metadata/current records, but non-`normal` keys/values are masked as `Private memory`. Raw `KNOWLEDGE.md` content and raw repo-memory bodies are not copied into the Cockpit response.
+- `Activity & Runs` merges client-side Alfa host-tool events with server MCP workflow activity only at the presentation layer. The execution engines remain separate; this is observability, not a fake shared workflow id.
+- Native MSO Agent sessions shown in Cockpit are **read-only summaries** and are explicitly separate from Alfa's browser YAML chat threads.
+- Provider/credential management remains Settings' responsibility. Cockpit can switch/test a model only inside the provider that is already configured.
+
+Browser Automations likewise do not introduce a second executor. `Run` turns the saved ordered recipe into one Alfa task; the normal host-tool schemas, server guards, and approval rendezvous remain the execution path.
+
## What actually reaches the model
Exactly three things, assembled in `chat-panel.tsx`:
-1. **System prompt** — `composeSystem(agent, modeNote)` in `lib/agent-request.ts`,
- the ONE place that decides this. `HOST_SYSTEM` first (identical every request,
- so the cached prefix is shared), then the mode note, then the active agent's
- name and persona. Rebuilt **every turn**, which is what makes switching agent
- mid-thread take effect.
+1. **System prompt** — `composeSystem(agent, modeNote, projectContext)` in `lib/agent-request.ts`,
+ the ONE place that decides this. It contains `HOST_SYSTEM`, the live/mock note, an optional **bounded selected-project metadata snapshot**, then the active agent's name/persona. Raw knowledge and repo-memory bodies are not injected. It is rebuilt **every turn**, so agent/project switches take effect on the next request. Because the route has one cache breakpoint at the end of the system block, a changed persona/project suffix can still miss that provider cache; keeping the global tool array stable avoids adding another source of prompt-prefix variation.
2. **Tools** — `HOST_AI_TOOLS`, i.e. *all* of them, always. See the scoping decision.
3. **History** — the wire turns. Nothing else. The persona is not in here.
@@ -178,23 +188,16 @@ jail and believing otherwise.
## Known gaps — stated, not hidden
-These survive because fixing them is a redesign, not a cleanup. Listed so nobody
-re-discovers them as bugs.
-
-1. **`Skill.starters`** is typed, edited and labelled "shown as quick chips" — and
- nothing renders it. (`instructions` IS rendered, as the card body in the library
- grid; it just never reaches the model.)
-2. **`/api/skills` is uncached**, `force-dynamic`, and now walks the global roots PLUS
- every project's skill roots on each call. Every cap is enforced and reported
- (12 containers, 400 entries each, 60 projects, 200 entries per skill root, 300
- project skills, 4 s per walk), so the worst case is bounded — but a wide box pays it
- every time. A TTL cache is the obvious next step and was deliberately not added with
- the discovery change.
-3. **The `Skill` → `Playbook` rename has not happened.** The code and the UI still
- say "Skill" for the localStorage type.
+1. **`/api/skills` is uncached**, `force-dynamic`, and now walks the global roots PLUS
+ every project's skill roots on each call. Every cap is enforced and reported, so
+ the worst case is bounded. Alfa Cockpit therefore lazy-loads Host Skills only when
+ the cockpit opens; a TTL cache remains the obvious next optimization.
### Closed
+- ~~Playbook starter prompts were dead data~~ — `Skill.starters` now feed the chat empty-state quick actions, deduplicated and bounded.
+- ~~Browser automations only narrated steps~~ — Run now sends the ordered recipe through Alfa's normal host-tool loop; reads execute and mutations keep the same approval cards.
+- ~~`Skill` and host `SKILL.md` both appeared as “Skills”~~ — the browser-local product surface now says **Playbooks**; persisted `alfa.skills` remains compatible.
- ~~`@agent` is cosmetic~~ — the store is module-level and a pick carries
`MentionItem.onPick`, which switches the active agent. Verified on a phone:
picking `@Ops` writes `alfa.activeAgent`.
diff --git a/frontend/slices/assistant/app.tsx b/frontend/slices/assistant/app.tsx
index 579f7d95..41cfd4d0 100644
--- a/frontend/slices/assistant/app.tsx
+++ b/frontend/slices/assistant/app.tsx
@@ -17,6 +17,7 @@ import { ThreadList } from "./components/thread-list";
import { LibraryGrid } from "./components/library-grid";
import { SkillForm } from "./components/skill-form";
import { McpActivityView } from "./components/mcp-activity-view";
+import { AlfaCockpitBar } from "./components/alfa-cockpit-bar";
import { assistantRouteFromPayload, type AssistantTab } from "./lib/navigation";
type Tab = AssistantTab;
@@ -29,9 +30,9 @@ type FormState =
const TABS: [Tab, string][] = [
["chat", "Chat"],
["agents", "Agents"],
- ["skills", "Skills"],
+ ["skills", "Playbooks"],
["automations", "Automations"],
- ["mcp", "MCP"],
+ ["mcp", "Activity"],
];
// Alfa: tabbed assistant. Chat keeps the real Claude stream; the other tabs
@@ -53,9 +54,10 @@ export default function Assistant({ payload }: AppProps) {
(auto: Automation) => {
setTab("chat");
const agent = store.agents.find((a) => a.id === auto.agentId);
+ if (agent) store.setActiveAgentId(agent.id);
setTimeout(() => chatRef.current?.runSteps(auto, agent), 30);
},
- [store.agents, setTab],
+ [store, setTab],
);
// Surface Alfa's own library state to the shell AI Inspector. Called above the
@@ -68,7 +70,7 @@ export default function Assistant({ payload }: AppProps) {
props: [
{ label: "Active agent", value: agentName },
{ label: "Agents", value: String(store.agents.length) },
- { label: "Skills", value: String(store.skills.length) },
+ { label: "Playbooks", value: String(store.skills.length) },
{ label: "Automations", value: String(store.automations.length) },
],
context: `Alfa assistant, agent ${agentName}`,
@@ -116,6 +118,8 @@ export default function Assistant({ payload }: AppProps) {
<ChatPanel
ref={chatRef}
agent={store.activeAgent}
+ cockpit={<AlfaCockpitBar onActivity={() => setTab("mcp")} />}
+ prompts={[...new Set(store.skills.flatMap((playbook) => playbook.starters ?? []))].slice(0, 6)}
switcher={
<>
<Button size="sm" variant="ghost" aria-label="Chat history" className="shrink-0 [@media(pointer:coarse)]:min-h-[44px]" onClick={() => setHistoryOpen(true)}>
diff --git a/frontend/slices/assistant/components/alfa-cockpit-bar.tsx b/frontend/slices/assistant/components/alfa-cockpit-bar.tsx
new file mode 100644
index 00000000..2dae36c0
--- /dev/null
+++ b/frontend/slices/assistant/components/alfa-cockpit-bar.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import { useState } from "react";
+import { Activity, FolderGit2, Gauge, ShieldCheck } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { useAlfaApprovalCount, useAlfaBusy } from "@/features/appshell";
+import { useAlfaCockpit } from "./use-alfa-cockpit";
+import { AlfaCockpitDialog } from "./alfa-cockpit-dialog";
+
+export function AlfaCockpitBar({ onActivity }: { onActivity: () => void }) {
+ const [open, setOpen] = useState(false);
+ const { data, loading, error, selectedProjectId, selectProject, refresh } = useAlfaCockpit();
+ const approvals = useAlfaApprovalCount();
+ const busy = useAlfaBusy();
+ const project = data?.selectedProject?.project.name ?? data?.projects.rows.find((row) => row.id === selectedProjectId)?.name;
+
+ return (
+ <>
+ <div className="flex items-center gap-1.5 overflow-x-auto border-b border-border/70 bg-background/80 px-3 py-1.5 [scrollbar-width:none]">
+ <Button size="sm" variant="ghost" className="h-8 shrink-0 gap-1.5 px-2 text-[11px]" onClick={() => setOpen(true)}>
+ <FolderGit2 className="size-3.5" />{project || "Choose project"}
+ </Button>
+ <Button size="sm" variant="ghost" className="h-8 shrink-0 gap-1.5 px-2 text-[11px]" onClick={() => setOpen(true)}>
+ <Gauge className="size-3.5" />{data ? `${data.model.provider}/${data.model.model}` : loading ? "Loading…" : "Runtime"}
+ </Button>
+ <div className="flex-1" />
+ {approvals ? <Button size="sm" variant="outline" className="h-8 shrink-0 gap-1 px-2 text-[10px]" onClick={() => setOpen(true)}><ShieldCheck className="size-3.5" />{approvals} approval{approvals === 1 ? "" : "s"}</Button> : null}
+ <Button size="sm" variant="ghost" className="h-8 shrink-0 gap-1.5 px-2 text-[11px]" onClick={onActivity}>
+ <Activity className={busy ? "size-3.5 animate-pulse" : "size-3.5"} />{busy ? "Running" : "Activity"}
+ </Button>
+ <Button size="sm" variant={error ? "outline" : "ghost"} className="h-8 shrink-0 px-2 text-[11px]" onClick={() => setOpen(true)}>{error ? "Needs attention" : "Cockpit"}</Button>
+ </div>
+ <AlfaCockpitDialog
+ open={open}
+ onOpenChange={setOpen}
+ data={data}
+ loading={loading}
+ error={error}
+ selectedProjectId={selectedProjectId}
+ onSelectProject={selectProject}
+ onRefresh={refresh}
+ onActivity={onActivity}
+ />
+ </>
+ );
+}
diff --git a/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx b/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx
new file mode 100644
index 00000000..5eee5e9d
--- /dev/null
+++ b/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import { Activity, Brain, Bot, Cpu, FolderGit2, RefreshCw, Settings2 } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { ResponsiveDialog, openWindow, sendToAlfa } from "@/features/appshell";
+import type { AlfaCockpitData, HostSkillRow } from "../lib/cockpit-types";
+import { HostSkillsSection } from "./host-skills-section";
+import { ModelQuickControl } from "./model-quick-control";
+import { ProjectQuickSelect } from "./project-quick-select";
+
+function Section({ title, icon: Icon, children }: { title: string; icon: typeof Cpu; children: React.ReactNode }) {
+ return (
+ <section className="space-y-2 rounded-xl border border-border/70 bg-card/35 p-3">
+ <div className="flex items-center gap-2 text-xs font-semibold"><Icon className="size-3.5 text-muted-foreground" />{title}</div>
+ {children}
+ </section>
+ );
+}
+
+export function AlfaCockpitDialog({
+ open, onOpenChange, data, loading, error, selectedProjectId, onSelectProject, onRefresh, onActivity,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ data: AlfaCockpitData | null;
+ loading: boolean;
+ error: string | null;
+ selectedProjectId: string;
+ onSelectProject: (id: string) => void;
+ onRefresh: () => void;
+ onActivity: () => void;
+}) {
+ const selected = data?.selectedProject;
+ const projectMcp = selected?.integrations?.projectMcp?.length ?? 0;
+
+ const useSkill = (skill: HostSkillRow) => {
+ const project = selected?.project;
+ const projectNote = project ? ` Apply it in the selected project ${project.name} (${project.path}).` : "";
+ void sendToAlfa(`Use the host skill \"${skill.id}\" for this task. Read it first with skills.read and follow only trusted instructions.${projectNote}`);
+ onOpenChange(false);
+ };
+
+ return (
+ <ResponsiveDialog open={open} onOpenChange={onOpenChange} variant="panel" size="lg" sheetSide="right">
+ <ResponsiveDialog.Header>
+ <ResponsiveDialog.Title>Alfa Cockpit</ResponsiveDialog.Title>
+ <ResponsiveDialog.Description>Execution context and MSO runtime state. Read-only unless Alfa asks for an approved action.</ResponsiveDialog.Description>
+ </ResponsiveDialog.Header>
+ <ResponsiveDialog.Body className="space-y-3">
+ {error ? <p className="rounded-lg border border-destructive/30 bg-destructive/10 p-2.5 text-xs text-destructive">{error}</p> : null}
+ <Section title="Runtime" icon={Cpu}>
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <Badge variant="secondary">{data ? data.model.provider : loading ? "Loading provider…" : "Provider unavailable"}</Badge>
+ {data?.model.tokenSaver && data.model.tokenSaver !== "off" ? <Badge variant="outline">token saver · {data.model.tokenSaver}</Badge> : null}
+ <Button size="sm" variant="ghost" className="ml-auto h-8" onClick={() => openWindow("settings", "Settings", undefined, { tab: "ai" })}><Settings2 className="size-3.5" />AI settings</Button>
+ </div>
+ {data ? <ModelQuickControl provider={data.model.provider} model={data.model.model} onSaved={onRefresh} /> : null}
+ </Section>
+
+ <Section title="Project Context" icon={FolderGit2}>
+<ProjectQuickSelect rows={data?.projects.rows ?? []} selected={selected ?? null} value={selectedProjectId} onChange={onSelectProject} />
+ {data?.projects.hasMore || data?.projects.scan?.truncated ? (
+ <p className="text-[10px] text-warning">Project list is bounded/incomplete; Alfa will not assume an absent project does not exist.</p>
+ ) : null}
+ {selected ? (
+ <div className="grid grid-cols-2 gap-2 text-[11px] sm:grid-cols-3">
+ <div><span className="text-muted-foreground">Branch</span><p className="truncate font-medium">{selected.git.branch || "—"}</p></div>
+ <div><span className="text-muted-foreground">Tree</span><p className="font-medium">{selected.git.clean === true ? "clean" : selected.git.clean === false ? "changed" : "—"}</p></div>
+ <div><span className="text-muted-foreground">HEAD</span><p className="truncate font-mono">{selected.git.head?.sha?.slice(0, 10) || "—"}</p></div>
+ <div><span className="text-muted-foreground">Package</span><p className="truncate font-medium">{selected.package?.name || "—"}</p></div>
+ <div><span className="text-muted-foreground">Knowledge</span><p className="font-medium">{selected.knowledge?.exists ? "available" : "none"}</p></div>
+ <div><span className="text-muted-foreground">Integrations</span><p className="font-medium">{projectMcp} MCP · {selected.database?.detected ? "DB" : "no DB"}</p></div>
+ </div>
+ ) : <p className="text-[11px] text-muted-foreground">Choose a project to ground Alfa in its repo, branch, knowledge presence, and recent project-memory topics.</p>}
+ {(selected?.recentMemory?.length ?? 0) > 0 ? (
+ <div className="space-y-1">
+ <p className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Recent project memory</p>
+ {selected!.recentMemory!.slice(0, 4).map((row) => <p key={row.id} className="truncate text-[11px]">{row.kind} · {row.title}</p>)}
+ </div>
+ ) : null}
+ </Section>
+
+ <HostSkillsSection open={open} onUse={useSkill} />
+
+ <Section title="Persistent Memory" icon={Brain}>
+ <div className="flex flex-wrap gap-1.5 text-[10px]">
+ <Badge variant="outline">{data?.typedMemory.telemetry.resolvedKeys ?? 0} resolved keys</Badge>
+ <Badge variant="outline">{data?.typedMemory.telemetry.archivedRecords ?? 0} archived</Badge>
+ {(data?.typedMemory.telemetry.conflictKeys ?? 0) > 0 ? <Badge variant="outline">{data!.typedMemory.telemetry.conflictKeys} conflicts</Badge> : null}
+ </div>
+ {(data?.typedMemory.records ?? []).slice(0, 5).map((row) => (
+ <div key={row.id} className="flex items-start gap-2 text-[11px]"><span className="min-w-0 flex-1"><b>{row.key}</b> · {row.value}</span><Badge variant="secondary" className="text-[9px]">{row.kind}</Badge></div>
+ ))}
+ {(data?.legacyMemoryCount ?? 0) > 0 ? <p className="text-[10px] text-muted-foreground">Plus {data!.legacyMemoryCount} Alfa owner fact{data!.legacyMemoryCount === 1 ? "" : "s"} in the legacy chat-memory store; raw text is not copied into Cockpit.</p> : null}
+ </Section>
+
+ <Section title="Native Sessions & Agents" icon={Bot}>
+ {(data?.sessions ?? []).slice(0, 4).map((session) => <div key={session.id} className="flex gap-2 text-[11px]"><span className="min-w-0 flex-1 truncate">@{session.name} · {session.title}</span><Badge variant="outline" className="text-[9px]">{session.source}</Badge></div>)}
+ {(data?.localAgents ?? []).length ? <div className="flex flex-wrap gap-1.5 pt-1">{data!.localAgents.slice(0, 8).map((agent) => <Badge key={agent.id} variant="secondary">{agent.label} · {agent.status}</Badge>)}</div> : <p className="text-[10px] text-muted-foreground">No active same-owner local agents.</p>}
+ <p className="text-[10px] text-muted-foreground">These are durable MSO Agent sessions, separate from Alfa&apos;s browser chat history.</p>
+ </Section>
+ </ResponsiveDialog.Body>
+ <ResponsiveDialog.Footer>
+ <Button variant="outline" onClick={onRefresh} disabled={loading}><RefreshCw className={loading ? "size-3.5 animate-spin" : "size-3.5"} />Refresh</Button>
+ <Button variant="outline" onClick={() => { onActivity(); onOpenChange(false); }}><Activity className="size-3.5" />Activity</Button>
+ <Button onClick={() => onOpenChange(false)}>Done</Button>
+ </ResponsiveDialog.Footer>
+ </ResponsiveDialog>
+ );
+}
diff --git a/frontend/slices/assistant/components/automation-form.tsx b/frontend/slices/assistant/components/automation-form.tsx
index f6a86601..5941a214 100644
--- a/frontend/slices/assistant/components/automation-form.tsx
+++ b/frontend/slices/assistant/components/automation-form.tsx
@@ -84,7 +84,7 @@ export function AutomationForm({
<Field label="Color">
<ColorPick value={color} onChange={setColor} options={SKILL_COLORS} />
</Field>
- <Field label="Run as agent" hint="Steps run with this agent's tools.">
+ <Field label="Run as agent" hint="Sets the persona for this run. Alfa still uses the same global host-tool catalog and approval policy.">
<select
value={agentId}
onChange={(e) => setAgentId(e.target.value)}
@@ -99,7 +99,7 @@ export function AutomationForm({
</Field>
<Field
label="Steps"
- hint="Each step runs a tool in order. Args: plain text → first parameter."
+ hint="Each step names the intended host tool in order. Args/context stay plain text; Alfa validates and maps them to the tool schema at run time."
>
<div className="flex flex-col gap-2">
{steps.length === 0 ? (
diff --git a/frontend/slices/assistant/components/automation-view.tsx b/frontend/slices/assistant/components/automation-view.tsx
index c6745242..c11eb1ae 100644
--- a/frontend/slices/assistant/components/automation-view.tsx
+++ b/frontend/slices/assistant/components/automation-view.tsx
@@ -9,7 +9,7 @@ import { toolById } from "../lib/tools";
import type { Automation } from "../lib/types";
import { GlyphTile } from "./agent-avatar";
-// Saved multi-step flows. "Run" only toasts/logs the steps — no real execution.
+// Saved multi-step flows. Run uses Alfa's normal tool loop, so mutations keep the same approval gate.
export function AutomationView({
store,
onRun,
diff --git a/frontend/slices/assistant/components/chat-panel.tsx b/frontend/slices/assistant/components/chat-panel.tsx
index 946f41e3..72f37e2b 100644
--- a/frontend/slices/assistant/components/chat-panel.tsx
+++ b/frontend/slices/assistant/components/chat-panel.tsx
@@ -26,10 +26,10 @@ import {
type AlfaMessage,
} from "@/features/appshell";
import { runToolAgent, useOsApi, type AgentMsg } from "../lib/host";
-import { toolById } from "../lib/tools";
import type { Agent, Automation } from "../lib/types";
import { activeAgent } from "../lib/store";
import { composeSystem } from "../lib/agent-request";
+import { composeAutomationRequest } from "../lib/automation-request";
import { useHostCommands, type HostToolUi } from "../host-tools/use-host-commands";
import { MessageBubble, type ChatMessage, type ToolCard } from "@/features/appshell";
import { ApprovalCard } from "@/features/appshell";
@@ -37,6 +37,8 @@ import { ApprovalCard } from "@/features/appshell";
import { EmptyState } from "./empty-state";
import { useThreadPersistence } from "./use-thread-persistence";
import { useAlfaRunner } from "./use-alfa-runner";
+import { beginAlfaRun, finishAlfaRun } from "../lib/alfa-activity";
+import { alfaProjectContext } from "@/features/appshell";
const SUGGESTED = ["Show system stats", "List ~/projects", "Create notes.txt in ~/projects with a TODO"];
@@ -60,10 +62,14 @@ export type ChatHandle = {
export function ChatPanel({
agent,
switcher,
+ cockpit,
+ prompts = [],
ref,
}: {
agent: Agent;
switcher: React.ReactNode;
+ cockpit?: React.ReactNode;
+ prompts?: string[];
ref?: Ref<ChatHandle>;
}) {
const api = useOsApi();
@@ -158,6 +164,8 @@ export function ChatPanel({
api.mode === "live"
? " You are in LIVE mode on a production VPS; tool actions are real."
: " You are in MOCK mode: fs, exec and sys tools are simulated (no real VPS). The skills.* and memory.* tools are NOT simulated — they read and write real host state even here.";
+ const runId = beginAlfaRun(text);
+ let runOk = false;
try {
const { history: next } = await runToolAgent(
historyRef.current,
@@ -174,16 +182,18 @@ export function ChatPanel({
// as a fake user message injected once when the thread was empty. That old
// shape is why switching agent mid-thread changed nothing: the first
// agent's persona was frozen into turn zero forever.
- composeSystem(a, modeNote),
+ composeSystem(a, modeNote, alfaProjectContext()),
ctrl.signal,
);
historyRef.current = next;
+ runOk = true;
} catch (err) {
if (!ctrl.signal.aborted) {
const note = errText(err);
appendToLastAssistant((t) => (t ? `${t}\n\n⚠ ${note}` : note));
}
} finally {
+ finishAlfaRun(runId, ctrl.signal.aborted ? "cancelled" : runOk ? "completed" : "failed");
if (abortRef.current === ctrl) abortRef.current = null;
// Drop the empty streaming placeholders (model ended on a tool / no text),
// then persist the finished turn to its thread.
@@ -199,19 +209,13 @@ export function ChatPanel({
useAlfaRunner(send, stop);
- // Automations narrate (no real execution) into the same thread. (v1 — later
- // each step can be pushed through the same agent.)
+ // Browser-local automations are execution recipes, not a second executor. One
+ // click feeds their exact ordered tool intent back through Alfa's normal agent
+ // loop, so reads use the same host bindings and every mutation still parks on
+ // the same approval card. This keeps automation safety DRY with ordinary chat.
useImperativeHandle(ref, () => ({
runSteps(auto, runAgent) {
- const lines = auto.steps.map((s, i) => {
- const t = toolById(s.tool);
- return ` ${i + 1}. ${t?.name ?? s.tool}${s.argText ? ` — ${s.argText}` : ""}`;
- });
- const body =
- `Running automation “${auto.name}” as ${(runAgent ?? agentRef.current).name}:\n` +
- (lines.join("\n") || " (no steps)") +
- "\n\n(Steps logged — no real execution in this build.)";
- setMessages((prev) => [...prev, { id: nextId(), role: "assistant", text: body }]);
+ void sendToAlfa(composeAutomationRequest(auto, (runAgent ?? agentRef.current).name));
},
stop,
loadThread,
@@ -223,6 +227,7 @@ export function ChatPanel({
<div className="flex items-center gap-2 overflow-x-auto border-b border-border bg-card/40 px-3 py-2 [scrollbar-width:none]">
{switcher}
</div>
+ {cockpit}
<div
className={cn(
"px-3 py-1 text-center text-[11px] font-medium",
@@ -235,7 +240,7 @@ export function ChatPanel({
</div>
{messages.length === 0 ? (
<div className="flex-1 overflow-y-auto">
- <EmptyState prompts={SUGGESTED} onPick={(t) => void sendToAlfa(t)} />
+ <EmptyState prompts={[...new Set([...prompts, ...SUGGESTED])].slice(0, 6)} onPick={(t) => void sendToAlfa(t)} />
</div>
) : (
<ScrollArea className="flex-1">
diff --git a/frontend/slices/assistant/components/host-skills-section.tsx b/frontend/slices/assistant/components/host-skills-section.tsx
new file mode 100644
index 00000000..3a61bfcf
--- /dev/null
+++ b/frontend/slices/assistant/components/host-skills-section.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { BookOpen, Search } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import type { HostSkillRow } from "../lib/cockpit-types";
+
+type SkillResponse = {
+ skills?: HostSkillRow[];
+ scan?: { truncated?: boolean; truncationReasons?: string[] };
+};
+
+export function HostSkillsSection({ open, onUse }: { open: boolean; onUse: (skill: HostSkillRow) => void }) {
+ const [rows, setRows] = useState<HostSkillRow[]>([]);
+ const [scan, setScan] = useState<SkillResponse["scan"]>();
+ const [query, setQuery] = useState("");
+ const [loading, setLoading] = useState(true);
+ const [loaded, setLoaded] = useState(false);
+
+ useEffect(() => {
+ if (!open || loaded) return;
+ const ctrl = new AbortController();
+ fetch("/api/skills", { cache: "no-store", signal: ctrl.signal })
+ .then(async (response) => {
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(body?.error || `HTTP ${response.status}`);
+ return body as SkillResponse;
+ })
+ .then((data) => {
+ setRows(data.skills ?? []);
+ setScan(data.scan);
+ })
+ .catch(() => undefined)
+ .finally(() => { if (!ctrl.signal.aborted) { setLoaded(true); setLoading(false); } });
+ return () => ctrl.abort();
+ }, [loaded, open]);
+
+ const visible = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return rows
+ .filter((row) => !q || `${row.id} ${row.description}`.toLowerCase().includes(q))
+ .slice(0, 10);
+ }, [query, rows]);
+
+ return (
+ <section className="space-y-2.5">
+ <div className="flex items-center gap-2">
+ <BookOpen className="size-4 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <h3 className="text-sm font-semibold">Host Skills</h3>
+ <p className="text-[11px] text-muted-foreground">Trusted SKILL.md catalog from MSO and your projects.</p>
+ </div>
+ </div>
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-2.5 size-3.5 text-muted-foreground" />
+ <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search host skills" className="h-9 pl-8 text-xs" />
+ </div>
+ {scan?.truncated ? (
+ <p className="rounded-lg border border-warning/30 bg-warning/10 px-2.5 py-2 text-[10px] text-warning">
+ Catalog incomplete: {(scan.truncationReasons ?? []).join(", ") || "scan limit reached"}.
+ </p>
+ ) : null}
+ <div className="space-y-1.5">
+ {loading ? <p className="text-xs text-muted-foreground">Loading host skills…</p> : null}
+ {!loading && loaded && visible.length === 0 ? <p className="text-xs text-muted-foreground">No matching skills.</p> : null}
+ {visible.map((skill) => {
+ const trusted = skill.trust !== "untrusted";
+ return (
+ <div key={skill.id} className="flex items-start gap-2 rounded-lg border border-border/70 bg-card/40 p-2.5">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="truncate text-xs font-medium">{skill.name}</span>
+ <Badge variant="outline" className="text-[9px]">{skill.trust}</Badge>
+ {skill.project?.name ? <Badge variant="secondary" className="text-[9px]">{skill.project.name}</Badge> : null}
+ </div>
+ <p className="mt-1 line-clamp-2 text-[10px] leading-relaxed text-muted-foreground">{skill.description || skill.id}</p>
+ </div>
+ <Button size="sm" variant={trusted ? "outline" : "ghost"} disabled={!trusted} className="h-8 shrink-0 text-[10px]" onClick={() => onUse(skill)}>
+ {trusted ? "Use" : "Review"}
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
diff --git a/frontend/slices/assistant/components/library-grid.tsx b/frontend/slices/assistant/components/library-grid.tsx
index d27a4010..e889bd12 100644
--- a/frontend/slices/assistant/components/library-grid.tsx
+++ b/frontend/slices/assistant/components/library-grid.tsx
@@ -10,7 +10,7 @@ import { OS_TOOLS } from "../lib/tools";
import type { Agent, Skill } from "../lib/types";
import { GlyphTile } from "./agent-avatar";
-// Agents/Skills card grid. Presets are non-deletable; agents can be set active.
+// Agents/Playbooks card grid. Presets are non-deletable; agents can be set active.
export function LibraryGrid({
kind,
store,
@@ -32,15 +32,15 @@ export function LibraryGrid({
<div className="p-5 [padding-bottom:calc(1.25rem+var(--sai-bottom))]">
<div className="mb-3.5 flex items-center">
<div>
- <div className="text-base font-bold tracking-tight">{isAgent ? "Agents" : "Skills"}</div>
+ <div className="text-base font-bold tracking-tight">{isAgent ? "Agents" : "Playbooks"}</div>
<div className="text-xs text-muted-foreground">
{isAgent
- ? "Personas share one global tool catalog; skills organize instructions, not grants."
- : "Bundles of tools + instructions you give to agents."}
+ ? "Personas share one global tool catalog; Playbooks organize instructions, not grants."
+ : "Personal instruction bundles for Alfa. They organize intent; they do not grant or remove tools."}
</div>
</div>
<Button size="sm" className="ml-auto [@media(pointer:coarse)]:min-h-[44px]" onClick={onNew}>
- <Plus className="size-3.5" /> New {isAgent ? "agent" : "skill"}
+ <Plus className="size-3.5" /> New {isAgent ? "agent" : "playbook"}
</Button>
</div>
<div className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3">
diff --git a/frontend/slices/assistant/components/mcp-activity-model.test.ts b/frontend/slices/assistant/components/mcp-activity-model.test.ts
index 76981523..a3719adb 100644
--- a/frontend/slices/assistant/components/mcp-activity-model.test.ts
+++ b/frontend/slices/assistant/components/mcp-activity-model.test.ts
@@ -24,6 +24,7 @@ describe("MCP activity workflow grouping", () => {
]);
expect(group.state).toBe("done");
});
+
it("marks a completed standalone call without calling it verified", () => {
const [group] = groupActivity([row({ id: "one", tool: "sys_stats", state: "completed" })]);
expect(group.state).toBe("completed");
@@ -37,4 +38,16 @@ describe("MCP activity workflow grouping", () => {
expect(group.state).toBe("cancelled");
});
+ it("marks a completed Alfa run completed without pretending it is verified", () => {
+ const [group] = groupActivity([
+ row({ id: "alfa:run", tool: "alfa.chat", state: "completed", workflowId: "alfa-1", workflowIntent: "inspect repo" }),
+ row({ id: "alfa:tool", tool: "fs.read", state: "completed", workflowId: "alfa-1" }),
+ ]);
+ expect(group).toMatchObject({ state: "completed", intent: "inspect repo" });
+ });
+
+ it("marks an aborted local Alfa run as cancelled", () => {
+ const [group] = groupActivity([row({ id: "alfa:run", tool: "alfa.chat", state: "cancelled", workflowId: "alfa-2" })]);
+ expect(group.state).toBe("cancelled");
+ });
});
diff --git a/frontend/slices/assistant/components/mcp-activity-model.ts b/frontend/slices/assistant/components/mcp-activity-model.ts
index 09151042..b47571a8 100644
--- a/frontend/slices/assistant/components/mcp-activity-model.ts
+++ b/frontend/slices/assistant/components/mcp-activity-model.ts
@@ -1,4 +1,4 @@
-export type McpActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited";
+export type McpActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited" | "cancelled";
export type McpActivityRow = {
id: string;
@@ -61,8 +61,9 @@ export function groupActivity(entries: McpActivityRow[]): McpActivityGroup[] {
group.rows.sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime());
if (group.rows.some((row) => row.state === "started")) group.state = "running";
else if (group.rows.some((row) => ["failed", "denied", "rate_limited"].includes(row.state))) group.state = "attention";
- else if (group.rows.some((row) => row.tool === "workflow_cancel" && row.state === "completed")) group.state = "cancelled";
+ else if (group.rows.some((row) => row.state === "cancelled" || (row.tool === "workflow_cancel" && row.state === "completed"))) group.state = "cancelled";
else if (group.rows.some((row) => row.tool === "workflow_finish" && row.state === "completed")) group.state = "done";
+ else if (group.rows.some((row) => row.tool === "alfa.chat" && row.state === "completed")) group.state = "completed";
else if (!group.workflowId && group.rows.every((row) => row.state === "completed")) group.state = "completed";
else group.state = "active";
}
diff --git a/frontend/slices/assistant/components/mcp-activity-view.tsx b/frontend/slices/assistant/components/mcp-activity-view.tsx
index dc3a0532..56e2ce22 100644
--- a/frontend/slices/assistant/components/mcp-activity-view.tsx
+++ b/frontend/slices/assistant/components/mcp-activity-view.tsx
@@ -8,6 +8,7 @@ import {
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { groupActivity, type McpActivityGroup, type McpActivityRow } from "./mcp-activity-model";
+import { useAlfaActivity } from "../lib/alfa-activity";
const stateMeta = {
started: { label: "running", Icon: CircleDashed, cls: "text-info" },
@@ -15,6 +16,7 @@ const stateMeta = {
failed: { label: "failed", Icon: XCircle, cls: "text-destructive" },
denied: { label: "denied", Icon: ShieldAlert, cls: "text-warning" },
rate_limited: { label: "limited", Icon: ShieldAlert, cls: "text-warning" },
+ cancelled: { label: "cancelled", Icon: XCircle, cls: "text-muted-foreground" },
} as const;
const groupMeta = {
@@ -28,7 +30,8 @@ const groupMeta = {
function toolMeta(row: McpActivityRow): { Icon: LucideIcon; label: string } {
const target = (row.target ?? "").toLowerCase();
- if (row.tool.startsWith("skills_")) return { Icon: BookOpen, label: "Skills" };
+ if (row.tool === "alfa.chat") return { Icon: Activity, label: "Alfa" };
+ if (row.tool.startsWith("skills_") || row.tool.startsWith("skills.")) return { Icon: BookOpen, label: "Skills" };
if (row.tool.startsWith("workflow_")) return { Icon: Route, label: "Workflow" };
if (row.tool === "screen_capture") return { Icon: Camera, label: "Screenshot" };
if (row.tool === "fs_search") return { Icon: Search, label: "Search" };
@@ -97,6 +100,7 @@ function WorkflowDetails({ group, initiallyOpen }: { group: McpActivityGroup; in
export function McpActivityView() {
const [entries, setEntries] = useState<McpActivityRow[]>([]);
+ const alfaEntries = useAlfaActivity();
const [paused, setPaused] = useState(false);
const load = useCallback(() => {
fetch("/api/mcp/activity?limit=200", { cache: "no-store" })
@@ -112,7 +116,7 @@ export function McpActivityView() {
return () => window.clearInterval(timer);
}, [load, paused]);
- const groups = useMemo(() => groupActivity(entries), [entries]);
+ const groups = useMemo(() => groupActivity([...alfaEntries, ...entries].sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime())), [alfaEntries, entries]);
const running = groups.filter((group) => group.state === "running").length;
return (
@@ -120,9 +124,9 @@ export function McpActivityView() {
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
<Activity className="size-4" />
<div className="min-w-0 flex-1">
- <p className="text-xs font-semibold">MCP Activity</p>
+ <p className="text-xs font-semibold">Activity & Runs</p>
<p className="text-[10px] text-muted-foreground">
- {running ? `${running} workflow${running === 1 ? "" : "s"} running now` : "Live workflows grouped by task and feature"}
+ {running ? `${running} run${running === 1 ? "" : "s"} active now` : "Alfa tool calls plus MSO workflows, grouped by task"}
</p>
</div>
<span className="flex items-center gap-1 rounded-full bg-secondary px-2 py-1 text-[10px] text-muted-foreground">
@@ -136,7 +140,7 @@ export function McpActivityView() {
<div className="min-h-0 flex-1 overflow-auto p-3">
{groups.length === 0 ? (
<div className="grid h-full place-items-center text-center text-xs text-muted-foreground">
- <div><Camera className="mx-auto mb-2 size-7 opacity-60" />No MCP activity yet.</div>
+ <div><Camera className="mx-auto mb-2 size-7 opacity-60" />No activity yet.</div>
</div>
) : (
<div className="space-y-2">
diff --git a/frontend/slices/assistant/components/model-quick-control.tsx b/frontend/slices/assistant/components/model-quick-control.tsx
new file mode 100644
index 00000000..6b798286
--- /dev/null
+++ b/frontend/slices/assistant/components/model-quick-control.tsx
@@ -0,0 +1,74 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { CheckCircle2, Loader2, TriangleAlert } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+
+type CatalogModel = { id: string; name?: string; tools?: boolean; reasoning?: boolean; vision?: boolean };
+
+export function ModelQuickControl({ provider, model, onSaved }: { provider: string; model: string; onSaved: () => void }) {
+ const [rows, setRows] = useState<CatalogModel[]>([]);
+ const [saving, setSaving] = useState(false);
+ const [test, setTest] = useState<{ ok: boolean; text: string } | null>(null);
+
+ useEffect(() => {
+ const ctrl = new AbortController();
+ fetch(`/api/models?provider=${encodeURIComponent(provider)}`, { cache: "no-store", signal: ctrl.signal })
+ .then((response) => response.ok ? response.json() : { models: [] })
+ .then((body) => setRows((body.models ?? []) as CatalogModel[]))
+ .catch(() => undefined);
+ return () => ctrl.abort();
+ }, [provider]);
+
+ const options = useMemo(() => rows.some((row) => row.id === model) ? rows : [{ id: model, name: model }, ...rows], [model, rows]);
+
+ async function select(next: string) {
+ if (!next || next === model || saving) return;
+ setSaving(true);
+ setTest(null);
+ try {
+ const response = await fetch("/api/config", {
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ provider, model: next }),
+ });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ onSaved();
+ } catch {
+ setTest({ ok: false, text: "Model switch failed" });
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function testSelected() {
+ setSaving(true);
+ setTest(null);
+ try {
+ const response = await fetch("/api/models/test", { method: "POST" });
+ const body = await response.json().catch(() => ({}));
+ setTest(body.ok ? { ok: true, text: "Connected" } : { ok: false, text: body.error || "Connection failed" });
+ } catch {
+ setTest({ ok: false, text: "Connection failed" });
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Select value={model} onValueChange={select} disabled={saving}>
+ <SelectTrigger className="min-w-0 flex-1"><SelectValue /></SelectTrigger>
+ <SelectContent position="popper" align="start">
+ {options.slice(0, 80).map((row) => <SelectItem key={row.id} value={row.id}>{row.name || row.id}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ <Button size="sm" variant="outline" className="h-9 shrink-0" onClick={testSelected} disabled={saving}>
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : "Test"}
+ </Button>
+ </div>
+ {test ? <p className={`flex items-center gap-1 text-[10px] ${test.ok ? "text-success" : "text-destructive"}`}>{test.ok ? <CheckCircle2 className="size-3" /> : <TriangleAlert className="size-3" />}{test.text}</p> : null}
+ <p className="text-[10px] text-muted-foreground">Switches only the model for the already-configured provider. Credentials and providers stay in Settings.</p>
+ </div>
+ );
+}
diff --git a/frontend/slices/assistant/components/project-quick-select.tsx b/frontend/slices/assistant/components/project-quick-select.tsx
new file mode 100644
index 00000000..8c906b68
--- /dev/null
+++ b/frontend/slices/assistant/components/project-quick-select.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { Search } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import type { CockpitProjectRow, CockpitSelectedProject } from "../lib/cockpit-types";
+
+export function ProjectQuickSelect({
+ rows, selected, value, onChange,
+}: {
+ rows: CockpitProjectRow[];
+ selected: CockpitSelectedProject | null;
+ value: string;
+ onChange: (id: string) => void;
+}) {
+ const [query, setQuery] = useState("");
+ const [searchRows, setSearchRows] = useState<CockpitProjectRow[]>([]);
+
+ useEffect(() => {
+ const q = query.trim();
+ if (!q) return;
+ const ctrl = new AbortController();
+ const timer = window.setTimeout(() => {
+ fetch(`/api/v1/alfa/cockpit?q=${encodeURIComponent(q)}`, { cache: "no-store", signal: ctrl.signal })
+ .then((response) => response.ok ? response.json() : { projects: { rows: [] } })
+ .then((body) => setSearchRows((body.projects?.rows ?? []) as CockpitProjectRow[]))
+ .catch(() => undefined);
+ }, 250);
+ return () => { window.clearTimeout(timer); ctrl.abort(); };
+ }, [query]);
+
+ const options = useMemo(() => {
+ const base = query.trim() ? searchRows : rows;
+ if (!selected || base.some((row) => row.id === selected.project.id)) return base;
+ return [{ id: selected.project.id, name: selected.project.name, path: selected.project.path }, ...base];
+ }, [query, rows, searchRows, selected]);
+
+ return (
+ <div className="space-y-2">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-2.5 size-3.5 text-muted-foreground" />
+ <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search projects on this host" className="h-9 pl-8 text-xs" />
+ </div>
+ <Select value={value || "__none"} onValueChange={(next) => onChange(next === "__none" ? "" : next)}>
+ <SelectTrigger className="w-full"><SelectValue placeholder="Select project" /></SelectTrigger>
+ <SelectContent position="popper" align="start">
+ <SelectItem value="__none">No project</SelectItem>
+ {options.map((project) => <SelectItem key={project.id} value={project.id}>{project.name}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/frontend/slices/assistant/components/skill-form.tsx b/frontend/slices/assistant/components/skill-form.tsx
index 9f6d3bc9..c1bc5a5d 100644
--- a/frontend/slices/assistant/components/skill-form.tsx
+++ b/frontend/slices/assistant/components/skill-form.tsx
@@ -21,7 +21,7 @@ export function SkillForm({
onClose: () => void;
}) {
const editing = !!skill;
- const [name, setName] = useState(skill?.name ?? "New Skill");
+ const [name, setName] = useState(skill?.name ?? "New Playbook");
const [glyph, setGlyph] = useState(skill?.glyph ?? "sparkles");
const [color, setColor] = useState(skill?.color ?? SKILL_COLORS[0]);
const [instructions, setInstructions] = useState(skill?.instructions ?? "");
@@ -47,7 +47,7 @@ export function SkillForm({
return (
<FormShell
- title={editing ? "Edit Skill" : "Create Skill"}
+ title={editing ? "Edit Playbook" : "Create Playbook"}
editing={editing}
onClose={onClose}
onSave={save}
@@ -68,7 +68,7 @@ export function SkillForm({
<Field label="Color">
<ColorPick value={color} onChange={setColor} options={SKILL_COLORS} />
</Field>
- <Field label="Instructions" hint="Your own note on how to use this skill. NOT sent to the model — only the agent's persona reaches the system prompt.">
+ <Field label="Instructions" hint="Your own note on how to use this playbook. NOT sent to the model — only the agent's persona reaches the system prompt.">
<Textarea
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
@@ -76,7 +76,7 @@ export function SkillForm({
className="min-h-16"
/>
</Field>
- <Field label="Tools" hint="Your own note of what this skill leans on. Not a grant — Alfa gets every tool on every turn.">
+ <Field label="Tools" hint="Your own note of what this playbook leans on. Not a grant — Alfa gets every tool on every turn.">
<ToolPicker value={tools} onChange={setTools} />
</Field>
<Field label="Starter prompts" hint="One per line — shown as quick chips.">
diff --git a/frontend/slices/assistant/components/use-alfa-cockpit.ts b/frontend/slices/assistant/components/use-alfa-cockpit.ts
new file mode 100644
index 00000000..db7348a5
--- /dev/null
+++ b/frontend/slices/assistant/components/use-alfa-cockpit.ts
@@ -0,0 +1,69 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import {
+ setAlfaProjectContext,
+ setAlfaSelectedProject,
+ useAlfaSelectedProject,
+} from "@/features/appshell";
+import type { AlfaCockpitData } from "../lib/cockpit-types";
+
+function publishProjectContext(data: AlfaCockpitData | null) {
+ const selected = data?.selectedProject;
+ if (!selected) {
+ setAlfaProjectContext(null);
+ return;
+ }
+ setAlfaProjectContext({
+ id: selected.project.id,
+ name: selected.project.name,
+ path: selected.project.path,
+ branch: selected.git.branch,
+ clean: selected.git.clean,
+ head: selected.git.head?.sha,
+ knowledge: selected.knowledge?.exists === true,
+ recentMemoryTitles: (selected.recentMemory ?? []).map((row) => row.title).slice(0, 6),
+ });
+}
+
+export function useAlfaCockpit() {
+ const selectedProjectId = useAlfaSelectedProject();
+ const [data, setData] = useState<AlfaCockpitData | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [reloadKey, setReloadKey] = useState(0);
+
+ useEffect(() => {
+ const ctrl = new AbortController();
+ const query = selectedProjectId ? `?project=${encodeURIComponent(selectedProjectId)}` : "";
+ fetch(`/api/v1/alfa/cockpit${query}`, { cache: "no-store", signal: ctrl.signal })
+ .then(async (response) => {
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(body?.error || `HTTP ${response.status}`);
+ return body as AlfaCockpitData;
+ })
+ .then((next) => {
+ setData(next);
+ setError(null);
+ publishProjectContext(next);
+ })
+ .catch((reason) => {
+ if (ctrl.signal.aborted) return;
+ setError(reason instanceof Error ? reason.message : "Failed to load Alfa cockpit");
+ publishProjectContext(null);
+ })
+ .finally(() => { if (!ctrl.signal.aborted) setLoading(false); });
+ return () => ctrl.abort();
+ }, [selectedProjectId, reloadKey]);
+
+ const refresh = useCallback(() => {
+ setLoading(true);
+ setReloadKey((key) => key + 1);
+ }, []);
+ const selectProject = useCallback((id: string) => {
+ setLoading(true);
+ setAlfaSelectedProject(id);
+ }, []);
+
+ return { data, loading, error, selectedProjectId, selectProject, refresh };
+}
diff --git a/frontend/slices/assistant/host-tools/use-host-commands.ts b/frontend/slices/assistant/host-tools/use-host-commands.ts
index b7282456..9b23277d 100644
--- a/frontend/slices/assistant/host-tools/use-host-commands.ts
+++ b/frontend/slices/assistant/host-tools/use-host-commands.ts
@@ -5,6 +5,7 @@ import { matchDestructive, useOsApi } from "../lib/host";
import type { AiTool, ToolInvocation, ToolOutcome } from "../lib/host";
import { useApps, type ToolCard } from "@/features/appshell";
import { findHostTool, HOST_AI_TOOLS } from "./registry";
+import { recordAlfaTool } from "../lib/alfa-activity";
// The chat panel supplies these so the binding can render each call as a card and
// park on an approval decision for mutate tools.
@@ -47,20 +48,25 @@ export function useHostCommands(ui: HostToolUi): {
const tool = findHostTool(name);
const id = `hc${seq.current++}`;
const args = input ?? {};
+ const startedAt = Date.now();
if (!tool) {
const msg = `unknown tool "${name}"`;
ui.pushCard(id, { name, effect: "mutate", input: args, status: "error", result: msg });
+ recordAlfaTool(id, name, "failed", msg, Date.now() - startedAt);
return { ok: false, result: msg };
}
const execute = async (): Promise<ToolOutcome> => {
ui.updateCard(id, { status: "running" });
+ recordAlfaTool(id, name, "started");
try {
const result = await tool.run(api, args, { apps });
ui.updateCard(id, { status: "ok", result });
+ recordAlfaTool(id, name, "completed", undefined, Date.now() - startedAt);
return { ok: true, result };
} catch (e) {
const msg = e instanceof Error ? e.message : "tool failed";
ui.updateCard(id, { status: "error", result: msg });
+ recordAlfaTool(id, name, "failed", msg, Date.now() - startedAt);
return { ok: false, result: msg };
}
};
@@ -74,8 +80,10 @@ export function useHostCommands(ui: HostToolUi): {
const danger = name === "exec.run" ? matchDestructive(String(args.cmd ?? "")) ?? undefined : undefined;
const sig = signature(name, args);
ui.pushCard(id, { name, effect: "mutate", input: args, status: "pending", danger });
+ recordAlfaTool(id, name, "started", "waiting for approval");
if (denied.current.has(sig)) {
ui.updateCard(id, { status: "denied", result: "Auto-denied (already declined this exact call)." });
+ recordAlfaTool(id, name, "denied", "auto-denied", Date.now() - startedAt);
return { ok: false, result: "Auto-denied: the user already declined this exact call. Stop retrying it — propose an alternative or ask." };
}
if (allowed.current.has(sig)) return execute();
@@ -83,6 +91,7 @@ export function useHostCommands(ui: HostToolUi): {
if (!approve) {
denied.current.add(sig);
ui.updateCard(id, { status: "denied", result: "Denied by the user." });
+ recordAlfaTool(id, name, "denied", "denied by user", Date.now() - startedAt);
return { ok: false, result: "Denied by the user. Do not retry this exact call; propose an alternative or ask what they'd prefer." };
}
if (remember && REMEMBERABLE.has(name)) allowed.current.add(sig);
diff --git a/frontend/slices/assistant/lib/agent-request.test.ts b/frontend/slices/assistant/lib/agent-request.test.ts
index dc771bc1..48176752 100644
--- a/frontend/slices/assistant/lib/agent-request.test.ts
+++ b/frontend/slices/assistant/lib/agent-request.test.ts
@@ -36,8 +36,20 @@ describe("composeSystem", () => {
expect(composeSystem(agent({ persona: " " }), " MODE")).toBe(base);
});
+
+ it("adds bounded selected-project context without turning it into permission", () => {
+ const out = composeSystem(agent(), " MODE", {
+ id: "root/mso", name: "mso", path: "/home/rahman/projects/mso", branch: "main",
+ clean: false, head: "abcdef123456", knowledge: true, recentMemoryTitles: ["Fix updater race", "Verify memory retention"],
+ });
+ expect(out).toContain("Selected MSO project: mso");
+ expect(out).toContain("Working tree has changes");
+ expect(out).toContain("Project knowledge is available");
+ expect(out).toContain("not permission to mutate");
+ });
+
it("stays well inside the route's 4000-char system cap", () => {
- const out = composeSystem(agent({ persona: "x".repeat(5000) }), " MODE");
+ const out = composeSystem(agent({ persona: "x".repeat(5000) }), " MODE", { id: "x", name: "x".repeat(500), path: "/" + "y".repeat(1000), recentMemoryTitles: Array(20).fill("z".repeat(200)) });
expect(out.length).toBeLessThan(4000);
});
});
diff --git a/frontend/slices/assistant/lib/agent-request.ts b/frontend/slices/assistant/lib/agent-request.ts
index e618621d..af5e86d1 100644
--- a/frontend/slices/assistant/lib/agent-request.ts
+++ b/frontend/slices/assistant/lib/agent-request.ts
@@ -21,9 +21,39 @@ import { HOST_SYSTEM } from "../host-tools/registry";
// bought nothing (see the scoping decision in CONTRACT.md). If per-agent material
// grows, the fix is a second breakpoint after the shared head, not reordering.
const PERSONA_CAP = 800;
+const PROJECT_CONTEXT_CAP = 1000;
-export function composeSystem(agent: Agent | undefined, modeNote: string): string {
+export type AlfaWorkContext = {
+ id: string;
+ name: string;
+ path: string;
+ branch?: string;
+ clean?: boolean;
+ head?: string;
+ knowledge?: boolean;
+ recentMemoryTitles?: string[];
+};
+
+function oneLine(value: string | undefined, cap: number): string {
+ return String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, cap);
+}
+
+function projectNote(project?: AlfaWorkContext | null): string {
+ if (!project) return "";
+ const parts = [
+ `Selected MSO project: ${oneLine(project.name, 80)} (${oneLine(project.path, 260)}).`,
+ project.branch ? `Branch ${oneLine(project.branch, 120)}.` : "",
+ project.clean === true ? "Working tree reported clean." : project.clean === false ? "Working tree has changes." : "",
+ project.head ? `HEAD ${oneLine(project.head, 64)}.` : "",
+ project.knowledge ? "Project knowledge is available." : "",
+ project.recentMemoryTitles?.length ? `Recent project-memory topics: ${project.recentMemoryTitles.map((title) => oneLine(title, 100)).filter(Boolean).slice(0, 6).join("; ")}.` : "",
+ "This is read-only work context, not permission to mutate the project.",
+ ].filter(Boolean).join(" ");
+ return parts ? ` ${parts.slice(0, PROJECT_CONTEXT_CAP)}` : "";
+}
+
+export function composeSystem(agent: Agent | undefined, modeNote: string, project?: AlfaWorkContext | null): string {
const persona = agent?.persona?.trim().slice(0, PERSONA_CAP);
const identity = agent && persona ? ` You are acting as ${agent.name}. ${persona}` : "";
- return HOST_SYSTEM + modeNote + identity;
+ return HOST_SYSTEM + modeNote + projectNote(project) + identity;
}
diff --git a/frontend/slices/assistant/lib/alfa-activity.ts b/frontend/slices/assistant/lib/alfa-activity.ts
new file mode 100644
index 00000000..a7912765
--- /dev/null
+++ b/frontend/slices/assistant/lib/alfa-activity.ts
@@ -0,0 +1,58 @@
+"use client";
+
+import { useSyncExternalStore } from "react";
+import type { McpActivityRow } from "../components/mcp-activity-model";
+
+const MAX_ROWS = 120;
+let rows: McpActivityRow[] = [];
+let currentRun: { id: string; intent: string } | null = null;
+const subs = new Set<() => void>();
+const emit = () => subs.forEach((fn) => fn());
+const subscribe = (fn: () => void) => { subs.add(fn); return () => subs.delete(fn); };
+const getRows = () => rows;
+const EMPTY: McpActivityRow[] = [];
+
+function upsert(row: McpActivityRow) {
+ const i = rows.findIndex((item) => item.id === row.id);
+ rows = i >= 0 ? rows.map((item, index) => index === i ? row : item) : [row, ...rows].slice(0, MAX_ROWS);
+ emit();
+}
+
+export function useAlfaActivity(): McpActivityRow[] {
+ return useSyncExternalStore(subscribe, getRows, () => EMPTY);
+}
+
+export function beginAlfaRun(intent: string): string {
+ const id = `alfa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+ currentRun = { id, intent: intent.replace(/\s+/g, " ").trim().slice(0, 120) || "Alfa task" };
+ upsert({
+ id: `${id}:run`, ts: new Date().toISOString(), actor: "alfa", tool: "alfa.chat",
+ state: "started", workflowId: id, workflowIntent: currentRun.intent, workflowProject: undefined,
+ });
+ return id;
+}
+
+export function finishAlfaRun(id: string, outcome: "completed" | "failed" | "cancelled") {
+ const row = rows.find((item) => item.id === `${id}:run`);
+ if (row) upsert({ ...row, state: outcome, ts: new Date().toISOString() });
+ if (currentRun?.id === id) currentRun = null;
+}
+
+export function recordAlfaTool(id: string, tool: string, state: McpActivityRow["state"], detail?: string, durationMs?: number) {
+ const run = currentRun;
+ const key = `${run?.id ?? "alfa-standalone"}:${id}`;
+ const prior = rows.find((item) => item.id === key);
+ upsert({
+ id: key,
+ ts: new Date().toISOString(),
+ actor: "alfa",
+ tool,
+ state,
+ scope: undefined,
+ workflowId: run?.id,
+ workflowIntent: run?.intent ?? "Alfa tool call",
+ detail: detail?.slice(0, 220),
+ durationMs,
+ ...(prior?.target ? { target: prior.target } : {}),
+ });
+}
diff --git a/frontend/slices/assistant/lib/automation-request.test.ts b/frontend/slices/assistant/lib/automation-request.test.ts
new file mode 100644
index 00000000..4887c676
--- /dev/null
+++ b/frontend/slices/assistant/lib/automation-request.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { composeAutomationRequest } from "./automation-request";
+import type { Automation } from "./types";
+
+const auto: Automation = {
+ id: "auto-1", name: "Inspect then write", glyph: "sparkles", color: "blue", agentId: "ag-1",
+ steps: [
+ { tool: "fs.read", argText: "README.md" },
+ { tool: "fs.write", argText: "notes.txt with verified summary" },
+ ],
+};
+
+describe("Alfa automation execution request", () => {
+ it("preserves ordered tool intent and explicit approval policy", () => {
+ const prompt = composeAutomationRequest(auto, "Ops");
+ expect(prompt).toContain("using the Ops persona");
+ expect(prompt.indexOf("1. fs.read")).toBeLessThan(prompt.indexOf("2. fs.write"));
+ expect(prompt).toContain("README.md");
+ expect(prompt).toContain("normal human approval cards");
+ expect(prompt).toContain("do not claim success without the tool result");
+ });
+
+ it("fails safely at the prompt layer when an automation has no steps", () => {
+ expect(composeAutomationRequest({ ...auto, steps: [] }, "Ops")).toContain("No steps are configured; explain that and stop.");
+ });
+});
diff --git a/frontend/slices/assistant/lib/automation-request.ts b/frontend/slices/assistant/lib/automation-request.ts
new file mode 100644
index 00000000..4e2da608
--- /dev/null
+++ b/frontend/slices/assistant/lib/automation-request.ts
@@ -0,0 +1,15 @@
+import { toolById } from "./tools";
+import type { Automation } from "./types";
+
+export function composeAutomationRequest(auto: Automation, agentName: string): string {
+ const lines = auto.steps.map((step, index) => {
+ const tool = toolById(step.tool);
+ const context = step.argText ? ` — requested args/context: ${step.argText}` : "";
+ return `${index + 1}. ${step.tool}${tool?.name ? ` (${tool.name})` : ""}${context}`;
+ });
+ return [
+ `Run my saved Alfa automation “${auto.name}” using the ${agentName} persona.`,
+ "Execute these steps in order through the listed MSO host tools. Inspect/validate before each dependent step; do not claim success without the tool result. Mutations must use the normal human approval cards.",
+ lines.join("\n") || "No steps are configured; explain that and stop.",
+ ].join("\n\n");
+}
diff --git a/frontend/slices/assistant/lib/cockpit-types.ts b/frontend/slices/assistant/lib/cockpit-types.ts
new file mode 100644
index 00000000..0fbef533
--- /dev/null
+++ b/frontend/slices/assistant/lib/cockpit-types.ts
@@ -0,0 +1,95 @@
+export type CockpitProjectRow = {
+ id: string;
+ name: string;
+ path: string;
+ packageName?: string;
+ packageVersion?: string;
+ git?: { branch?: string; head?: string };
+};
+
+export type CockpitSelectedProject = {
+ project: { id: string; name: string; path: string; rootId: string };
+ git: {
+ available?: boolean;
+ branch?: string;
+ clean?: boolean;
+ changes?: string[];
+ head?: { sha?: string; subject?: string; date?: string; author?: string };
+ };
+ package?: { name?: string; version?: string };
+ capabilities?: Record<string, unknown>;
+ database?: { detected?: boolean; configured?: boolean; mode?: string };
+ integrations?: { projectMcp?: Array<{ name?: string; description?: string }> };
+ knowledge?: { exists?: boolean; bytes?: number; sha256?: string };
+ recentMemory?: Array<{
+ id: string;
+ kind: string;
+ status: string;
+ title: string;
+ updatedAt: string;
+ score: number;
+ }>;
+};
+
+export type AlfaCockpitData = {
+ model: { provider: string; model: string; tokenSaver: string };
+ projects: {
+ total: number;
+ hasMore: boolean;
+ scan: { truncated?: boolean; truncationReasons?: string[] };
+ rows: CockpitProjectRow[];
+ };
+ selectedProject: CockpitSelectedProject | null;
+ sessions: Array<{
+ id: string;
+ name: string;
+ source: string;
+ title: string;
+ updatedAt: string;
+ cwd?: string;
+ estimatedTokens: number;
+ eventCount: number;
+ }>;
+ localAgents: Array<{
+ id: string;
+ name: string;
+ label: string;
+ status: string;
+ title: string;
+ cwd?: string;
+ lastSeenAt: string;
+ }>;
+ legacyMemoryCount: number;
+ typedMemory: {
+ telemetry: {
+ liveRecords: number;
+ archivedRecords: number;
+ totalRecords: number;
+ resolvedKeys: number;
+ conflictKeys: number;
+ futureScheduled: number;
+ archiveSegments: number;
+ };
+ records: Array<{
+ id: string;
+ document: string;
+ key: string;
+ value: string;
+ kind: string;
+ confidence: number;
+ sensitivity: string;
+ authority: string;
+ observedAt: string;
+ conflictCount: number;
+ }>;
+ };
+};
+
+export type HostSkillRow = {
+ id: string;
+ name: string;
+ description: string;
+ source: string;
+ trust: string;
+ project?: { id?: string; name?: string; path?: string };
+};
diff --git a/frontend/slices/assistant/lib/types.ts b/frontend/slices/assistant/lib/types.ts
index ab08b51e..94cee801 100644
--- a/frontend/slices/assistant/lib/types.ts
+++ b/frontend/slices/assistant/lib/types.ts
@@ -1,6 +1,7 @@
-// Shared types for the Alfa assistant slice. Agents own skills; an agent's
-// effective tools are the union of its skills' tools (or every tool when it is
-// a generalist). Automations are ordered tool steps run as one click.
+// Shared persisted types for the Alfa assistant slice. `Skill` is the legacy
+// storage name for the UI Playbook type. Agent `skills`/`allTools` and Playbook
+// `tools` are migration-compatible metadata, NOT capability grants; Alfa uses one
+// global host-tool catalog. Automations are ordered intents executed through Alfa.
// Only groups that have EXECUTABLE tools behind them. rendering/media/editor/
// browser/settings/video were removed with the 44 descriptors that described
// capabilities the model could never call.
diff --git a/scripts/cli/commands-state.sh b/scripts/cli/commands-state.sh
index d8eb4b0d..a0e86c4b 100755
--- a/scripts/cli/commands-state.sh
+++ b/scripts/cli/commands-state.sh
@@ -7,6 +7,18 @@ mso_cmd_state() {
case "$cmd" in
# ── assistant / state ────────────────────────────────────────────────────
ai) jpost "/api/assistant" "$(jq -n --arg m "$*" '{messages:[{role:"user",content:$m}]}')" ;;
+ cockpit)
+ case "${1:-show}" in
+ show)
+ if [ -n "${2-}" ]; then jget "/api/v1/alfa/cockpit?project=$(enc "$2")";
+ else jget "/api/v1/alfa/cockpit"; fi ;;
+ search)
+ shift; [ $# -gt 0 ] || die "usage: mso $U_cockpit"
+ jget "/api/v1/alfa/cockpit?q=$(enc "$*")" ;;
+ *)
+ # Bare argument is the ergonomic project form: `mso cockpit mso`.
+ jget "/api/v1/alfa/cockpit?project=$(enc "$1")" ;;
+ esac ;;
threads)
case "${1:-list}" in
list) jget "/api/threads" ;;
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index d12f7e19..83c17f24 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -33,6 +33,7 @@ U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner
U_service="service status|start|stop|restart|logs [n]"
U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"
U_update="update [--rebuild] | status | log"
+U_cockpit="cockpit [project] | cockpit show [project] | cockpit search <query…>"
U_threads="threads list|show <id>|save <json>|rm <id>"
U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"
U_agents="agents list [current-session-id]|send <source-session-id> <target> <message> [message|task]|inbox <session-id> [--all]"
@@ -86,7 +87,7 @@ mso_cli_main() {
mso_cmd_host "$cmd" "$@" ;;
agent|chat|model|setup|onboard|provider|providers|gateway|web|camoufox|apps|mapp|term)
mso_cmd_runtime "$cmd" "$@" ;;
- ai|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)
+ ai|cockpit|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;
devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|service|build|deploy|update|crud|api|completion)
mso_cmd_admin "$cmd" "$@" ;;
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index f483cba3..598f6e9d 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -30,7 +30,7 @@ const all = [cli, commandOwner, agentCli, configRoute, oauthRoute, slash, picker
describe("MSO model/provider/session CLI contract", () => {
it("keeps provider auth (`models`) separate from active selection (`model`)", () => {
- expect(cli).toContain('VERSION="1.12.0"');
+ expect(cli).toContain('VERSION="1.12.1"');
expect(cli).toContain("models * Configure AI providers/auth");
expect(cli).toContain("model [ref] Select active model");
expect(agentCli).toContain("run_models()");