Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(self-build): Built for you — see, keep, undo and stop everything the loop builds (#766)
Ruben Lütkeb610e58b4c35
diff --git a/docs/self-build.md b/docs/self-build.mdindex 267107f257..d4767d0b81 100644--- a/docs/self-build.md+++ b/docs/self-build.md@@ -162,6 +162,60 @@ At `full` a used trial is kept on its own too.`POST /{id}/accept`, `POST /{id}/keep`, `POST /{id}/undo`. Every changepublishes `SelfBuildChanged` on the app bus, and the WebSocket forwards it.+`GET /settings` and `PUT /settings` read and change `[self_build]`. The PUT is+validated against `SelfBuildConfig`, written to `jarvis.toml` through+`config_writer.set_self_build_settings` and applied at once: the loop reads+the config through a getter. `GET /provenance?type=skill` lists the artefacts+builds created, keyed `"<type>:<id>"`, for the "built by Dodaios" badge.++The settings, the pause and accepting or keeping a build are excluded from the+brain's app actions, and `self_build.*` is on the self-mod deny list: only the+person decides how far the loop goes (rule 3). Reading the ledger and undoing+a build stay reachable, so "what did you build?" works when asked.++The society kill switch (`POST /api/society/kill-switch`) also pauses the+loop. Releasing it does not resume the loop; the person resumes it in "Built+for you".++### Artefact ids++The badge joins on the artefact a builder records with `attach_artefact`. Use+these ids so the badge finds its build:++| `type` | `id` |+|---|---|+| `skill` | the skill's `name` as `/api/skills` lists it |+| `routine` | the routine's task id (`/api/society/agents/{id}/routines`) |+| `agent` | the society `agent_id` |+| `memory` | the wiki or memory path |+| `code` | the pull request URL |++Extra keys (`label`, `url`, `repo`) are allowed and shown in the build's+detail.++## In the app++- **Built for you** (sidebar, under Agents; section id `self-build`) lists+ every build on the shelf of what it asks of the person: waiting for a yes,+ on trial, being built, kept, archived and undone. A row shows the build's+ one sentence, its kind, how often the need was seen and a small lifecycle+ rail; proposals and trials carry their actions inline. A build opens into+ its case file: why, what it noticed, how it was checked, what it made, use,+ cost and every state change. Undo is one click with no confirmation.+- The **digest** is one line at the top: what was built, proposed, kept,+ archived or undone in the last 24 hours, and how much is live. The nav row+ shows how many proposals wait. Nothing is announced: no toast, no sound, no+ voice.+- **Pause building** is the loop's kill switch. **Stop all agents** engages+ the society kill switch after a confirmation (which pauses building too);+ while it is engaged the page says so and offers Release.+- **Settings → General → Self-building** edits `[self_build]`.+- A **"Built by {assistant}"** badge marks skills (Skills list and detail),+ routines (an agent's routines) and agents (the agent card) that a build+ created, and opens that build.+- Live: the WebSocket forwards `SelfBuildChanged` and the page re-reads the+ ledger.+## Rules enforced in code1. Background work for the loop never bills a per-token key. It runs ondiff --git a/dodaios/app_actions/catalog.py b/dodaios/app_actions/catalog.pyindex bb06b43576..8c0aa0542f 100644--- a/dodaios/app_actions/catalog.py+++ b/dodaios/app_actions/catalog.py@@ -21,12 +21,15 @@ _METHODS: Final[tuple[str, ...]] = ("get", "post", "put", "patch", "delete")#: action policy itself — Jarvis never edits its own permissions — the#: main-brain switch, which only the person may flip (the provider lock), and#: consent to spend money: the missions' paid-API fallback switch and a-#: mission's paid-use approval (dodaios/missions/capacity.py).+#: mission's paid-use approval (dodaios/missions/capacity.py) — and how far the+#: self-building loop may go: its settings, its kill switch, and accepting or+#: keeping a build (docs/self-build.md, rule 3; undo and reads stay reachable)._EXCLUDED: Final[re.Pattern[str]] = re.compile(r"(secret|api-?keys?|/keys?(/|$)|install-key|host-key|use-key|token|password|"r"credential|oauth|/auth(/|$)|login|pairing|/callback|/hooks/|openapi|/ws$|"r"^/api/control/|^/api/self-mod|^/api/app-actions|^/api/brain/switch$|"- r"^/api/mission-billing|/capacity-decision$)",+ r"^/api/mission-billing|/capacity-decision$|"+ r"^/api/self-build/(settings|pause)$|^/api/self-build/[^/]+/(accept|keep)$)",re.IGNORECASE,)diff --git a/dodaios/core/config_writer.py b/dodaios/core/config_writer.pyindex 366fbecd8d..5d16d78d2f 100644--- a/dodaios/core/config_writer.py+++ b/dodaios/core/config_writer.py@@ -1289,6 +1289,34 @@ def set_agent_server()+#: Keys ``[self_build]`` accepts from the Settings page (docs/self-build.md).+SELF_BUILD_SETTING_KEYS: frozenset[str] = frozenset(+ {+ "enabled", "silent_days", "memory", "skill", "routine", "agent", "code",+ "trial_days", "trial_uses", "max_builds_per_day", "max_agents_per_week",+ "max_open_trials", "max_code_runs_per_day", "max_rejections",+ }+)+++def set_self_build_settings(+ values: dict[str, str | bool | int], *, path: Path = DEFAULT_CONFIG_FILE+) -> None:+ """Persist a validated ``[self_build]`` patch in one atomic write.++ The caller validates against ``SelfBuildConfig`` first. Toml-only: the+ drift guard does not track the section, and the running loop reads the+ in-memory config the route updates, so a change applies without a restart.+ """+ unknown = set(values).difference(SELF_BUILD_SETTING_KEYS)+ if unknown:+ raise ValueError(f"unknown self_build setting(s): {sorted(unknown)!r}")+ if not values:+ return+ first, *rest = values.items()+ _patch_table(path, "self_build", first[0], first[1], extra=dict(rest))++def set_wiki_vault_root(vault_root: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist ``[wiki_integration] vault_root`` in jarvis.toml (AP-7).diff --git a/dodaios/core/self_mod/forbidden.py b/dodaios/core/self_mod/forbidden.pyindex d8504aa8d8..053334df42 100644--- a/dodaios/core/self_mod/forbidden.py+++ b/dodaios/core/self_mod/forbidden.py@@ -44,6 +44,9 @@ FORBIDDEN_PATTERNS: tuple[str, ...] = (# Settings route (x-jarvis-dangerous) or an explicit CLI call may flip it,# never voice, chat, self-mod or an agent (dodaios/missions/capacity.py)."missions.paid_api_fallback",+ # How far the self-building loop may go, and its kill switch: the person+ # decides that in Settings, never the loop or an agent (docs/self-build.md).+ "self_build.*","*_api_key","*_token","*_secret",diff --git a/dodaios/plugins/tool/navigate.py b/dodaios/plugins/tool/navigate.pyindex 427a2b95db..e062bce2bd 100644--- a/dodaios/plugins/tool/navigate.py+++ b/dodaios/plugins/tool/navigate.py@@ -73,6 +73,8 @@ KNOWN: frozenset[str] = frozenset("pets",# Keyboard shortcuts: every shortcut in one place, with a key tester."shortcuts",+ # Built for you: what the self-building loop made, with keep and undo.+ "self-build",})@@ -258,6 +260,12 @@ _ALIASES: dict[str, str] = {"claves de entrada de voz": "voice-api-keys", # i18n-allow: input vocab# The marketplace. "store"/"shop" are the words people actually reach for,# and none of these names anything else in the app.+ "built for you": "self-build",+ "self build": "self-build",+ "self-building": "self-build",+ "what you built": "self-build",+ "für dich gebaut": "self-build", # i18n-allow: input vocab+ "construido para ti": "self-build", # i18n-allow: input vocab"market": "marketplace","market place": "marketplace","store": "marketplace",diff --git a/dodaios/self_build/service.py b/dodaios/self_build/service.pyindex bcf32f878d..1d23af7de2 100644--- a/dodaios/self_build/service.py+++ b/dodaios/self_build/service.py@@ -171,6 +171,34 @@ class SelfBuild:"items": [r.to_json() for r in rows[:20]],}+ def provenance(self, artefact_type: str | None = None) -> dict[str, dict[str, Any]]:+ """Which artefacts a build created, keyed by ``"<type>:<id>"``.++ The "built by Dodaios" badge on agents, skills and routines joins on+ this. Only builds whose artefact still exists count: on trial, kept or+ archived (archived artefacts are kept, so the badge still links back).+ """+ wanted = (artefact_type or "").strip().lower()+ out: dict[str, dict[str, Any]] = {}+ rows = self.ledger.list(states=LIVE_STATES | {State.ARCHIVED}, limit=500)+ for record in rows:+ kind = str(record.artefact.get("type") or "").strip().lower()+ ident = str(record.artefact.get("id") or "").strip()+ if not kind or not ident or (wanted and kind != wanted):+ continue+ # Newest change first: the first row for an id is the current one.+ out.setdefault(+ f"{kind}:{ident}",+ {+ "build_id": record.id,+ "type": kind,+ "id": ident,+ "state": record.state.value,+ "title": record.title,+ },+ )+ return out+# ------------------------------------------------------------ plumbingdef spawn(self, coro: Awaitable[None], label: str) -> None:diff --git a/dodaios/society/runtime.py b/dodaios/society/runtime.pyindex c3df97e79e..92eb2b4974 100644--- a/dodaios/society/runtime.py+++ b/dodaios/society/runtime.py@@ -111,6 +111,26 @@ def set_current_runtime(runtime: SocietyRuntime | None) -> None:_current = runtime+def _pause_self_build() -> bool:+ """The society kill switch also pauses the self-building loop.++ Stopping every agent while the loop keeps building new ones would make the+ switch a half stop. Releasing the kill switch does not resume the loop:+ the person resumes it in "Built for you" (docs/self-build.md).+ """+ try:+ from dodaios.self_build import current as current_self_build++ service = current_self_build()+ if service is None:+ return False+ service.set_paused(True)+ return True+ except Exception: # noqa: BLE001 — the kill switch itself must never fail on this+ log.warning("society kill switch: pausing the self-build loop failed", exc_info=True)+ return False++def _agent_frame(agent: AgentRecord, task: str, config: Any = None) -> str:"""The mission prompt that carries the agent's identity to a worker."""name = display_name(agent, config)@@ -1258,6 +1278,7 @@ class SocietyRuntime:async def engage_kill_switch(self) -> dict[str, Any]:await self.store.set_kill_switch(True)+ building_paused = _pause_self_build()halted = await self.scheduler.halt_all()goals_paused = await self.team_leads.halt()await self._cancel_active_society_chats()@@ -1281,6 +1302,7 @@ class SocietyRuntime:"rooms_settled": settled,"missions_cancelled": killed,"team_goals_paused": goals_paused,+ "self_build_paused": building_paused,}async def release_kill_switch(self) -> dict[str, Any]:diff --git a/dodaios/ui/web/dist/assets/customConnector-B9HX78Md.js b/dodaios/ui/web/dist/assets/customConnector-B9HX78Md.jsdeleted file mode 100644index 3a1a990df1..0000000000--- a/dodaios/ui/web/dist/assets/customConnector-B9HX78Md.js+++ /dev/null@@ -1 +0,0 @@-async function s(t){var e,o;const n=await fetch("/api/marketplace/connectors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t.name.trim(),url:t.url.trim(),auth:t.auth,header_name:((e=t.headerName)==null?void 0:e.trim())||null})});if(!n.ok){const a=(await n.json().catch(()=>({}))).detail;throw Array.isArray(a)&&((o=a[0])!=null&&o.msg)?new Error(String(a[0].msg)):new Error(typeof a=="string"?a:`HTTP ${n.status}`)}return n.json()}async function c(t){const n=await fetch(`/api/marketplace/community/plugins/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok){const o=(await n.json().catch(()=>({}))).detail;throw new Error(typeof o=="string"?o:`HTTP ${n.status}`)}}let r=null;function d(t){r=t}function u(){const t=r;return r=null,t}export{s as a,c as b,d as r,u as t};diff --git a/dodaios/ui/web/frontend/src/components/icons/sectionIcons.tsx b/dodaios/ui/web/frontend/src/components/icons/sectionIcons.tsxindex b0a3520a36..c9762157a8 100644--- a/dodaios/ui/web/frontend/src/components/icons/sectionIcons.tsx+++ b/dodaios/ui/web/frontend/src/components/icons/sectionIcons.tsx@@ -124,6 +124,16 @@ export const AgentsIcon = defineIcon(</>,);+/** A block set down beside the one it was built on: something made for you. */+export const BuiltIcon = defineIcon(+ "BuiltIcon",+ <>+ <path d="M12 3.5 19 7.5v8.5L12 20 5 16V7.5Z" />+ <path d="M5 7.5 12 11.5 19 7.5" />+ <path d="M12 11.5V20" />+ </>,+);+/** Three tiles and a fourth turned on its corner: something added on. */export const ExtensionsIcon = defineIcon("ExtensionsIcon",diff --git a/dodaios/ui/web/frontend/src/components/layout/MainView.tsx b/dodaios/ui/web/frontend/src/components/layout/MainView.tsxindex 8ae1c69ec0..a3725b19d1 100644--- a/dodaios/ui/web/frontend/src/components/layout/MainView.tsx+++ b/dodaios/ui/web/frontend/src/components/layout/MainView.tsx@@ -127,6 +127,11 @@ const MarketplaceView = lazyView(["marketplace"], () =>default: m.MarketplaceView,})),);+const SelfBuildView = lazyView(["self-build"], () =>+ import("@/views/SelfBuildView").then((m) => ({+ default: m.SelfBuildView,+ })),+);/** Quiet time before a loading section admits it is loading. */export const LOADING_HINT_MS = 400;@@ -386,6 +391,9 @@ function SwitchOnActiveSection({ active }: { active: string }) {// place, installable without leaving the app.case "marketplace":return <MarketplaceView />;+ // Built for you: every self-built thing, with keep, undo and the pause.+ case "self-build":+ return <SelfBuildView />;// Deliberately nothing: the coding workspace is rendered by the STICKY// branch in `MainView` above, which keeps it mounted across section// changes. This switch is not rendered at all while one of those ids isdiff --git a/dodaios/ui/web/frontend/src/components/layout/Sidebar.tsx b/dodaios/ui/web/frontend/src/components/layout/Sidebar.tsxindex 98acd21d0e..551195ced3 100644--- a/dodaios/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/dodaios/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -13,6 +13,7 @@ import {type NavItem,} from "@/components/layout/navGroups";import { useEventStore } from "@/store/events";+import { useSelfBuildWaiting } from "@/hooks/useSelfBuild";import { useSectionPrefetch } from "@/hooks/useSectionPrefetch";import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";import { useVoiceMode } from "@/hooks/useVoiceMode";@@ -270,6 +271,9 @@ export function Sidebar({const agentsCount = useEventStore((s) =>s.events.filter((e) => e.name === "AgentStateChange").length > 0 ? undefined : 0,);+ // Proposals that wait for the person's yes or no — a quiet number, never a+ // toast or a sound (the self-building loop does not interrupt).+ const selfBuildWaiting = useSelfBuildWaiting();// Read for the status line's connecting phase. Same resolver as the// mission-deck header and orb (`useVoiceMode`): a negotiating realtime@@ -319,7 +323,7 @@ export function Sidebar({// retired "Jarvis Tools" folder used to be — it was the only entry hiding// behind "Show more" that users reached for daily, while the tools folder// duplicated exactly what "Show more" already lists.- const primaryIds = ["chats", "agents", "dictation", "visualization", "agentic-ide", "plugins", "marketplace"];+ const primaryIds = ["chats", "agents", "self-build", "dictation", "visualization", "agentic-ide", "plugins", "marketplace"];// The Settings hub owns its entries — they live in the hub's left// navigation now, so "Show more" must not list them a second time. The set// itself is named once in `navGroups` (`SETTINGS_HUB_IDS`).@@ -336,7 +340,7 @@ export function Sidebar({const item = presentNavItem(raw, surface);return <NavRow key={item.id} item={item} label={resolveNavLabel(t, item)} compact={compact}active={item.matchIds ? item.matchIds.includes(active) : item.id === active}- badge={item.id === "agents" ? agentsCount : undefined}+ badge={item.id === "agents" ? agentsCount : item.id === "self-build" ? selfBuildWaiting : undefined}betaLabel={item.beta ? t("nav.agentic_ide_beta") : undefined}alert={item.id === "apikeys" && apikeysHasError} alertTitle={t("sidebar.apikeys_alert")}warn={item.id === "plugins" && pluginsNeedReconnect}@@ -528,6 +532,8 @@ export function Sidebar({{!railed && <span>{t("sidebar.new_chat")}</span>}</button></li>{renderRow(findItem("agents"))}+ {/* What the agents and the loop built on their own, beside them. */}+ {renderRow(findItem("self-build"))}{renderRow(findItem("dictation"))}</ul><ul className="space-y-px">diff --git a/dodaios/ui/web/frontend/src/components/layout/navGroups.ts b/dodaios/ui/web/frontend/src/components/layout/navGroups.tsindex b99f805be9..9d2a07a5a5 100644--- a/dodaios/ui/web/frontend/src/components/layout/navGroups.ts+++ b/dodaios/ui/web/frontend/src/components/layout/navGroups.ts@@ -14,6 +14,7 @@ import {AgentsIcon,ArtifactsIcon,BoardIcon,+ BuiltIcon,CaptureIcon,ChatIcon,CodeIcon,@@ -122,6 +123,14 @@ export const NAV_GROUPS: NavItem[][] = [// 1) Workspace — what the user builds with and reads back.[{ id: "agents", labelKey: "nav.agents", icon: AgentsIcon },+ // Built for you — what the self-building loop made on its own, why, and+ // the one place to keep, undo or pause it (docs/self-build.md).+ {+ id: "self-build",+ labelKey: "nav.self_build",+ icon: BuiltIcon,+ fallbackLabel: "Built for you",+ },// The compact catalog opens on Plugins; direct section navigation selects// its corresponding tab and keeps this shared row highlighted.{diff --git a/dodaios/ui/web/frontend/src/components/selfBuild/BuiltByBadge.tsx b/dodaios/ui/web/frontend/src/components/selfBuild/BuiltByBadge.tsxnew file mode 100644index 0000000000..674aa03ee2--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/selfBuild/BuiltByBadge.tsx@@ -0,0 +1,57 @@+/**+ * "Built by {name}" — the mark on an agent, a skill or a routine that the+ * self-building loop created. A click opens its build in "Built for you":+ * why it exists, how it was checked, and the undo.+ *+ * Renders nothing for anything the person (or the product) made, and nothing+ * while the ledger is not running — the join is the build's recorded artefact+ * (`GET /api/self-build/provenance`, docs/self-build.md "Artefact ids").+ */+import { BuiltIcon } from "@/components/icons/sectionIcons";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useProvenanceFor } from "@/hooks/useSelfBuild";+import { openBuild } from "@/store/selfBuildFocus";++export function BuiltByBadge({+ type,+ id,+ compact = false,+ className,+}: {+ type: "agent" | "skill" | "routine" | "memory";+ id: string | null | undefined;+ compact?: boolean;+ className?: string;+}) {+ const t = useT();+ const item = useProvenanceFor(type, id);+ if (!item) return null;+ const label = t("self_build_badge.label");+ const onTrial = item.state === "trial";+ return (+ <button+ type="button"+ data-testid="built-by-badge"+ data-build-id={item.build_id}+ data-state={item.state}+ title={`${t("self_build_badge.title")}${onTrial ? ` (${t("self_build_badge.trial")})` : ""}${item.title ? ` — ${item.title}` : ""}`}+ aria-label={label}+ onClick={(event) => {+ event.stopPropagation();+ openBuild(item.build_id);+ }}+ className={cn(+ "inline-flex shrink-0 items-center gap-1 rounded-full border border-border text-xs text-muted-foreground transition-colors",+ "hover:border-border-strong hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ compact ? "h-5 px-1.5" : "h-6 px-2",+ className,+ )}+ >+ <BuiltIcon aria-hidden className="h-3 w-3" strokeWidth={1.8} />+ {!compact && <span className="truncate">{label}</span>}+ {onTrial && !compact && <span className="text-accent">· {t("self_build_badge.trial")}</span>}+ {onTrial && compact && <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-accent" />}+ </button>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsxindex bdafba18eb..6b23066ccb 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx@@ -10,6 +10,7 @@ import { WebhookConnection } from "./WebhookConnection";import { TriggerBuilder } from "./TriggerBuilder";import { SourceControls } from "./SourceControls";import { AgentRoutineDetail } from "./AgentRoutineDetail";+import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";export interface AgentRoutinesListProps { agentId: string; sampleRoutines?: AgentRoutine[]; variant?: "rail" | "sheet"; className?: string; onDetailOpenChange?: (open: boolean) => void; }export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", className, onDetailOpenChange }: AgentRoutinesListProps) {@@ -54,6 +55,7 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", cconst active = ["scheduled", "active", "enabled", ""].includes(routine.state);const trigger = routine.trigger as { type?: string; source?: { kind: string } } | null;return <li key={routine.id} className="rounded-md">+ <div className="flex items-start gap-1"><button type="button" aria-label={displayRoutineTitle(routine.title)} className="flex w-full cursor-pointer select-none items-start gap-2 rounded-md px-0.5 py-1.5 text-left hover:bg-secondary/60 focus-visible:outline focus-visible:outline-ring" onClick={() => setSelected(routine.id)}><Clock size={16} aria-hidden className={cn("mt-0.5 shrink-0", active ? "text-success" : "text-muted-foreground")} /><span className="min-w-0 flex-1">@@ -62,6 +64,9 @@ export function AgentRoutinesList({ agentId, sampleRoutines, variant = "rail", c{routine.dueMs && active ? <span className="block text-[11px] text-muted-foreground">{t("society.card.next_run")}: {new Date(routine.dueMs).toLocaleString(locale, { timeZoneName: "short" })}</span> : null}</span></button>+ {/* Outside the row button: the badge is a link of its own. */}+ <BuiltByBadge compact type="routine" id={routine.id} className="mt-1.5" />+ </div>{trigger?.type === "webhook" && <div className="pl-6"><WebhookConnection key={routine.id} taskId={routine.id} /></div>}{trigger?.type === "source" && trigger.source && <div className="pl-6"><SourceControls key={routine.id} taskId={routine.id} source={trigger.source} /></div>}</li>;diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsxindex b4dab31cbd..907c3344a3 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx@@ -66,6 +66,7 @@ import { ComputerPicker } from "../create/ComputerPicker";import { LeadBrain, LeadInstructions } from "./LeadSections";import "./agentCard.css";+import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";/** How far up the three-step ladder a ceiling sits. `block` never reaches a card. */const CEILING_STEP: Record<PermissionCeiling, number> = { safe: 1, monitor: 2, ask: 3 };@@ -297,6 +298,7 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP<span className="truncate">{remoteComputer.name}</span></span>) : null}+ <BuiltByBadge type="agent" id={agent.agentId} /><span className={cn("ac-dot", STATE_FILL[agent.state])} data-state={agent.state} aria-hidden /><span className="shrink-0 text-xs text-muted-foreground">{activeRuns > 0diff --git a/dodaios/ui/web/frontend/src/hooks/useSelfBuild.ts b/dodaios/ui/web/frontend/src/hooks/useSelfBuild.tsnew file mode 100644index 0000000000..3655bae246--- /dev/null+++ b/dodaios/ui/web/frontend/src/hooks/useSelfBuild.ts@@ -0,0 +1,162 @@+/**+ * React Query hooks for "Built for you" (the self-building ledger).+ *+ * Nothing here polls fast: the backend publishes `SelfBuildChanged` on every+ * committed change and the WebSocket invalidates `selfBuildKeys.all`+ * (hooks/useWebSocket.ts), so the view repaints when a build moves. The slow+ * interval only covers a dropped socket. Every action writes its answer into+ * the cached list, so a click paints before the refetch lands.+ */+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ selfBuildApi,+ societyKillSwitchApi,+ type Build,+ type BuildList,+ type ProvenanceItem,+ type SelfBuildSettings,+ type SelfBuildSettingsPayload,+} from "@/lib/selfBuildApi";++export const selfBuildKeys = {+ all: ["self-build"] as const,+ list: () => ["self-build", "list"] as const,+ detail: (id: string) => ["self-build", "detail", id] as const,+ digest: (hours: number) => ["self-build", "digest", hours] as const,+ settings: () => ["self-build", "settings"] as const,+ provenance: () => ["self-build", "provenance"] as const,+ societyKill: () => ["society", "kill-switch"] as const,+};++const SAFETY_POLL_MS = 5 * 60_000;++export function useSelfBuildList() {+ return useQuery({+ queryKey: selfBuildKeys.list(),+ queryFn: ({ signal }) => selfBuildApi.list(signal),+ refetchInterval: SAFETY_POLL_MS,+ retry: false,+ });+}++/** How many proposals wait for the person — the quiet number on the nav row. */+export function useSelfBuildWaiting(): number | undefined {+ const { data } = useSelfBuildList();+ if (!Array.isArray(data?.builds)) return undefined;+ return data.builds.filter((b) => b.state === "proposed").length;+}++export function useSelfBuildDetail(id: string | null) {+ return useQuery({+ queryKey: selfBuildKeys.detail(id ?? ""),+ queryFn: ({ signal }) => selfBuildApi.detail(id ?? "", signal),+ enabled: Boolean(id),+ retry: false,+ });+}++export function useSelfBuildDigest(hours = 24) {+ return useQuery({+ queryKey: selfBuildKeys.digest(hours),+ queryFn: ({ signal }) => selfBuildApi.digest(hours, signal),+ refetchInterval: SAFETY_POLL_MS,+ retry: false,+ });+}++function patchList(list: BuildList | undefined, build: Build): BuildList | undefined {+ if (!list) return list;+ const builds = list.builds.some((b) => b.id === build.id)+ ? list.builds.map((b) => (b.id === build.id ? build : b))+ : [build, ...list.builds];+ return { ...list, builds };+}++export type BuildAction = "accept" | "keep" | "undo";++export function useBuildAction() {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({ id, action }: { id: string; action: BuildAction }) =>+ action === "accept"+ ? selfBuildApi.accept(id)+ : action === "keep"+ ? selfBuildApi.keep(id)+ : selfBuildApi.undo(id),+ onSuccess: ({ build }) => {+ client.setQueryData<BuildList>(selfBuildKeys.list(), (old) => patchList(old, build));+ void client.invalidateQueries({ queryKey: selfBuildKeys.all });+ },+ });+}++export function useSelfBuildPause() {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (paused: boolean) => selfBuildApi.pause(paused),+ onSuccess: (status) => {+ client.setQueryData<BuildList>(selfBuildKeys.list(), (old) =>+ old ? { ...old, status } : old,+ );+ void client.invalidateQueries({ queryKey: selfBuildKeys.list() });+ },+ });+}++export function useSelfBuildSettings() {+ return useQuery({+ queryKey: selfBuildKeys.settings(),+ queryFn: ({ signal }) => selfBuildApi.settings(signal),+ retry: false,+ });+}++export function useSaveSelfBuildSettings() {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (patch: Partial<SelfBuildSettings>) => selfBuildApi.saveSettings(patch),+ onSuccess: (payload) => {+ client.setQueryData<SelfBuildSettingsPayload>(selfBuildKeys.settings(), payload);+ // The status block (autonomy per kind) is derived from the same section.+ void client.invalidateQueries({ queryKey: selfBuildKeys.list() });+ },+ });+}++/** Every artefact a build created, keyed `"<type>:<id>"`; one shared query for every badge. */+export function useProvenance() {+ return useQuery({+ queryKey: selfBuildKeys.provenance(),+ queryFn: async ({ signal }) => (await selfBuildApi.provenance(undefined, signal)).items,+ staleTime: 60_000,+ retry: false,+ });+}++export function useProvenanceFor(type: string, id: string | null | undefined): ProvenanceItem | null {+ const { data } = useProvenance();+ if (!data || !id) return null;+ return data[`${type}:${id}`] ?? null;+}++export function useSocietyKillSwitch() {+ return useQuery({+ queryKey: selfBuildKeys.societyKill(),+ queryFn: ({ signal }) => societyKillSwitchApi.status(signal),+ refetchInterval: SAFETY_POLL_MS,+ retry: false,+ });+}++export function useSetSocietyKillSwitch() {+ const client = useQueryClient();+ return useMutation({+ mutationFn: (engaged: boolean) => societyKillSwitchApi.set(engaged),+ onSuccess: (_void, engaged) => {+ client.setQueryData(selfBuildKeys.societyKill(), engaged);+ // Engaging it pauses the loop too (dodaios/society/runtime.py).+ void client.invalidateQueries({ queryKey: selfBuildKeys.list() });+ void client.invalidateQueries({ queryKey: ["society"] });+ },+ });+}diff --git a/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts b/dodaios/ui/web/frontend/src/hooks/useWebSocket.tsindex c65ee3eff7..512b3e63ed 100644--- a/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts@@ -352,6 +352,13 @@ export function useWebSocket(): void {void queryClient.invalidateQueries({ queryKey: ["society", "roster"] });}+ // A build in the self-building ledger opened or moved: "Built for+ // you", its nav count and the "built by" badges re-read the ledger.+ // Never a toast — the loop does not interrupt (docs/self-build.md).+ if (env.event_name === "SelfBuildChanged") {+ void queryClient.invalidateQueries({ queryKey: ["self-build"] });+ }+// The desktop pet's pen: the backend already raised this window; land// on an empty typed chat with the caret in the composer. A detached// solo window is pinned to its section and stays where it is.diff --git a/dodaios/ui/web/frontend/src/i18n/index.ts b/dodaios/ui/web/frontend/src/i18n/index.tsindex 215ce6e0c7..2ad6825a6d 100644--- a/dodaios/ui/web/frontend/src/i18n/index.ts+++ b/dodaios/ui/web/frontend/src/i18n/index.ts@@ -123,7 +123,8 @@ export type LocaleChunk =| "providers"| "pane_review"| "memory"- | "ship";+ | "ship"+ | "self_build";const SHIP_LOCALES = import.meta.glob("./locales/ship/*.json");@@ -222,6 +223,14 @@ const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknowzh: () => import("./locales/memory/zh.json"),pt: () => import("./locales/memory/pt.json"),},+ // "Built for you": what the self-building loop made, opened from its nav row.+ self_build: {+ en: () => import("./locales/self_build/en.json"),+ de: () => import("./locales/self_build/de.json"),+ es: () => import("./locales/self_build/es.json"),+ zh: () => import("./locales/self_build/zh.json"),+ pt: () => import("./locales/self_build/pt.json"),+ },};const EXTRA: Record<UiLanguage, Record<string, unknown>[]> = { en: [], de: [], es: [], zh: [], pt: [] };diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex b74c5d5966..21ed921929 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -343,7 +343,8 @@"voice_language": "Sprache","voice_api_keys": "API-Keys","shortcuts": "Tastenkürzel",- "pets": "Meine Pets"+ "pets": "Meine Pets",+ "self_build": "Für dich gebaut"},"assistant_view": {"header_named": "Dein Assistent in {0}, geweckt mit „{1}“.",@@ -3170,7 +3171,8 @@"music": "Musik","keybinds": "Tastenkürzel","more": "Weiteres",- "overlay_taskbar": "Overlay & Taskleiste"+ "overlay_taskbar": "Overlay & Taskleiste",+ "self_build": "Selbstbau"},"languages_group_title": "Sprachen","sections": {@@ -3515,7 +3517,43 @@"system_now_dark": "Folgt Ihrem System, das derzeit dunkel ist.","system_now_light": "Folgt Ihrem System, das derzeit hell ist."},- "invalid_setting": "Ungültige Einstellung"+ "invalid_setting": "Ungültige Einstellung",+ "self_build": {+ "title": "Selbstbau",+ "description": "Wie weit {name} gehen darf, wenn es von sich aus Dinge für dich baut.",+ "open_view": "„Für dich gebaut“ öffnen",+ "enabled_title": "Von sich aus bauen",+ "enabled_description": "Bemerken, was du immer wieder tust, und bauen, was es dir abnimmt. Aus: Nichts wird bemerkt oder gebaut.",+ "autonomy_title": "Wie weit, je Art",+ "autonomy_description": "Aus: nie. Vorschlagen: Eine Karte fragt zuerst. Probe: gebaut, geprüft und live, mit Rückgängig per Klick. Voll: wie Probe, und eine genutzte Probe wird von selbst behalten.",+ "levels": {+ "off": "Aus",+ "suggest": "Vorschlagen",+ "trial": "Probe",+ "full": "Voll"+ },+ "kinds": {+ "memory": "Erinnerungen",+ "skill": "Skills",+ "routine": "Routinen",+ "agent": "Agenten",+ "code": "Code-Änderungen"+ },+ "limits_title": "Grenzen",+ "limits_description": "Feste Obergrenzen, die die Schleife nie überschreitet, egal was sie entscheidet.",+ "limits": {+ "max_builds_per_day": "Bauten pro Tag",+ "max_open_trials": "Gleichzeitige Proben",+ "max_agents_per_week": "Neue Agenten pro Woche",+ "max_code_runs_per_day": "Code-Läufe pro Tag",+ "trial_days": "Probedauer in Tagen",+ "trial_uses": "Probedauer in Nutzungen",+ "max_rejections": "Nach so vielen Absagen nicht mehr anbieten",+ "silent_days": "Ruhige erste Tage"+ },+ "save_error": "Speichern fehlgeschlagen: {detail}",+ "unavailable": "Diese Einstellungen konnten nicht geladen werden."+ }},"telephony_view": {"title": "Telefonie (experimentell)",@@ -10110,5 +10148,10 @@"objections_one": "{count} Einwand","objections_other": "{count} Einwände"}+ },+ "self_build_badge": {+ "label": "Gebaut von {name}",+ "title": "{name} hat das von sich aus gebaut. Zum Bau öffnen.",+ "trial": "auf Probe"}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 7d37775b43..fd8f1ea3c2 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -343,7 +343,8 @@"voice_language": "Language","voice_api_keys": "API Keys","shortcuts": "Keyboard shortcuts",- "pets": "My Pets"+ "pets": "My Pets",+ "self_build": "Built for you"},"assistant_view": {"header_named": "Your assistant in {0}, woken by “{1}”.",@@ -3170,7 +3171,8 @@"music": "Music","keybinds": "Keyboard shortcuts","more": "More",- "overlay_taskbar": "Overlay & taskbar"+ "overlay_taskbar": "Overlay & taskbar",+ "self_build": "Self-building"},"languages_group_title": "Languages","sections": {@@ -3515,7 +3517,43 @@"system_now_dark": "Following your system, which is currently dark.","system_now_light": "Following your system, which is currently light."},- "invalid_setting": "Invalid setting"+ "invalid_setting": "Invalid setting",+ "self_build": {+ "title": "Self-building",+ "description": "How far {name} may go when it builds things for you on its own.",+ "open_view": "Open Built for you",+ "enabled_title": "Build on its own",+ "enabled_description": "Notice what you keep doing and build what would take it off you. Off: nothing is noticed or built.",+ "autonomy_title": "How far, per kind",+ "autonomy_description": "Off: never. Suggest: a card asks first. Trial: built, checked and live with one-click undo. Full: like trial, and a trial that was used is kept on its own.",+ "levels": {+ "off": "Off",+ "suggest": "Suggest",+ "trial": "Trial",+ "full": "Full"+ },+ "kinds": {+ "memory": "Memories",+ "skill": "Skills",+ "routine": "Routines",+ "agent": "Agents",+ "code": "Code changes"+ },+ "limits_title": "Limits",+ "limits_description": "Hard caps the loop never passes, whatever it decides.",+ "limits": {+ "max_builds_per_day": "Builds per day",+ "max_open_trials": "Open trials at once",+ "max_agents_per_week": "New agents per week",+ "max_code_runs_per_day": "Code runs per day",+ "trial_days": "Trial length in days",+ "trial_uses": "Trial length in uses",+ "max_rejections": "Stop offering after this many no's",+ "silent_days": "Quiet first days"+ },+ "save_error": "Could not save: {detail}",+ "unavailable": "These settings could not be loaded."+ }},"telephony_view": {"title": "Telephony (experimental)",@@ -10110,5 +10148,10 @@"objections_one": "{count} objection","objections_other": "{count} objections"}+ },+ "self_build_badge": {+ "label": "Built by {name}",+ "title": "{name} built this on its own. Open its build.",+ "trial": "on trial"}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex 4c9b040ab2..3cac0898f5 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -343,7 +343,8 @@"voice_language": "Idioma","voice_api_keys": "Claves API","shortcuts": "Atajos de teclado",- "pets": "Mis mascotas"+ "pets": "Mis mascotas",+ "self_build": "Hecho para ti"},"assistant_view": {"header_named": "Tu asistente en {0}, se despierta con «{1}».",@@ -3170,7 +3171,8 @@"music": "Música","keybinds": "Atajos de teclado","more": "Más",- "overlay_taskbar": "Overlay y barra de tareas"+ "overlay_taskbar": "Overlay y barra de tareas",+ "self_build": "Autoconstrucción"},"languages_group_title": "Idiomas","sections": {@@ -3515,7 +3517,43 @@"system_now_dark": "Sigue a su sistema, que actualmente está en modo oscuro.","system_now_light": "Sigue a su sistema, que actualmente está en modo claro."},- "invalid_setting": "Ajuste no válido"+ "invalid_setting": "Ajuste no válido",+ "self_build": {+ "title": "Autoconstrucción",+ "description": "Hasta dónde puede llegar {name} cuando construye cosas para ti por su cuenta.",+ "open_view": "Abrir Hecho para ti",+ "enabled_title": "Construir por su cuenta",+ "enabled_description": "Notar lo que haces una y otra vez y construir lo que te lo quite de encima. Desactivado: no se nota ni se construye nada.",+ "autonomy_title": "Hasta dónde, por tipo",+ "autonomy_description": "Desactivado: nunca. Sugerir: una tarjeta pregunta primero. Prueba: construido, comprobado y activo, con deshacer en un clic. Completo: como prueba, y una prueba que se usó se conserva sola.",+ "levels": {+ "off": "Desactivado",+ "suggest": "Sugerir",+ "trial": "Prueba",+ "full": "Completo"+ },+ "kinds": {+ "memory": "Recuerdos",+ "skill": "Habilidades",+ "routine": "Rutinas",+ "agent": "Agentes",+ "code": "Cambios de código"+ },+ "limits_title": "Límites",+ "limits_description": "Topes fijos que el ciclo nunca supera, decida lo que decida.",+ "limits": {+ "max_builds_per_day": "Construcciones por día",+ "max_open_trials": "Pruebas abiertas a la vez",+ "max_agents_per_week": "Agentes nuevos por semana",+ "max_code_runs_per_day": "Ejecuciones de código por día",+ "trial_days": "Duración de la prueba en días",+ "trial_uses": "Duración de la prueba en usos",+ "max_rejections": "Dejar de ofrecer tras tantos noes",+ "silent_days": "Primeros días en silencio"+ },+ "save_error": "No se pudo guardar: {detail}",+ "unavailable": "No se pudieron cargar estos ajustes."+ }},"telephony_view": {"title": "Telefonía",@@ -10110,5 +10148,10 @@"objections_one": "{count} objeción","objections_other": "{count} objeciones"}+ },+ "self_build_badge": {+ "label": "Hecho por {name}",+ "title": "{name} lo construyó por su cuenta. Abrir su construcción.",+ "trial": "en prueba"}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 9e145e881d..5608b849e8 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -343,7 +343,8 @@"voice_language": "Idioma","voice_api_keys": "Chaves de API","shortcuts": "Atalhos de teclado",- "pets": "Os meus Pets"+ "pets": "Os meus Pets",+ "self_build": "Feito para si"},"assistant_view": {"header_named": "O teu assistente em {0}, despertado por “{1}”.",@@ -3170,7 +3171,8 @@"music": "Música","keybinds": "Atalhos de teclado","more": "Mais",- "overlay_taskbar": "Overlay e barra de tarefas"+ "overlay_taskbar": "Overlay e barra de tarefas",+ "self_build": "Autoconstrução"},"languages_group_title": "Idiomas","sections": {@@ -3515,7 +3517,43 @@"system_now_dark": "A seguir o teu sistema, que de momento está escuro.","system_now_light": "A seguir o teu sistema, que de momento está claro."},- "invalid_setting": "Definição inválida"+ "invalid_setting": "Definição inválida",+ "self_build": {+ "title": "Autoconstrução",+ "description": "Até onde {name} pode ir quando constrói coisas para si por iniciativa própria.",+ "open_view": "Abrir Feito para si",+ "enabled_title": "Construir por iniciativa própria",+ "enabled_description": "Reparar no que faz repetidamente e construir o que lhe tira esse trabalho. Desligado: nada é notado nem construído.",+ "autonomy_title": "Até onde, por tipo",+ "autonomy_description": "Desligado: nunca. Sugerir: um cartão pergunta primeiro. Ensaio: construído, verificado e ativo, com anulação num clique. Total: como ensaio, e um ensaio que foi usado é mantido sozinho.",+ "levels": {+ "off": "Desligado",+ "suggest": "Sugerir",+ "trial": "Ensaio",+ "full": "Total"+ },+ "kinds": {+ "memory": "Memórias",+ "skill": "Competências",+ "routine": "Rotinas",+ "agent": "Agentes",+ "code": "Alterações de código"+ },+ "limits_title": "Limites",+ "limits_description": "Tetos fixos que o ciclo nunca ultrapassa, decida o que decidir.",+ "limits": {+ "max_builds_per_day": "Construções por dia",+ "max_open_trials": "Ensaios abertos em simultâneo",+ "max_agents_per_week": "Novos agentes por semana",+ "max_code_runs_per_day": "Execuções de código por dia",+ "trial_days": "Duração do ensaio em dias",+ "trial_uses": "Duração do ensaio em utilizações",+ "max_rejections": "Deixar de propor após tantas recusas",+ "silent_days": "Primeiros dias em silêncio"+ },+ "save_error": "Não foi possível guardar: {detail}",+ "unavailable": "Não foi possível carregar estas definições."+ }},"telephony_view": {"title": "Telefonia (experimental)",@@ -10110,5 +10148,10 @@"objections_one": "{count} objeção","objections_other": "{count} objeções"}+ },+ "self_build_badge": {+ "label": "Feito por {name}",+ "title": "{name} construiu isto por iniciativa própria. Abrir a construção.",+ "trial": "em ensaio"}}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/self_build/de.json b/dodaios/ui/web/frontend/src/i18n/locales/self_build/de.jsonnew file mode 100644index 0000000000..5fb33aa991--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/self_build/de.json@@ -0,0 +1,134 @@+{+ "self_build": {+ "title": "Für dich gebaut",+ "subtitle": "Was {name} von sich aus gebaut hat, warum, und wie du es zurücknimmst.",+ "loading": "Bauten werden geladen…",+ "status": {+ "running": "Baut von sich aus",+ "paused": "Pausiert",+ "silent": "Macht nur Notizen",+ "off": "Aus"+ },+ "pause": "Bauen pausieren",+ "resume": "Bauen fortsetzen",+ "pause_hint": "Hört auf zu bemerken, zu bauen und Proben abzuschließen. Alles bisher Gebaute bleibt, wie es ist.",+ "settings": "Einstellungen",+ "stop_all": "Alle Agenten stoppen",+ "stop_all_hint": "Stoppt sofort jeden laufenden Agenten, jede Mission und Routine und pausiert das Bauen.",+ "stop_confirm_title": "Jetzt alle Agenten stoppen?",+ "stop_confirm_body": "Laufende Chats, Missionen und Routinen stoppen sofort, und das Bauen pausiert ebenfalls. Nichts wird gelöscht.",+ "cancel": "Abbrechen",+ "notes": {+ "paused": "Das Bauen ist pausiert. Nichts wird bemerkt, gebaut oder abgeschlossen, bis du fortsetzt.",+ "silent": "Die ersten Tage sind ruhig: {name} notiert, was du wiederholst, und baut noch nichts.",+ "off": "Selbstbau ist aus. Nichts wird bemerkt oder gebaut.",+ "stopped": "Alle Agenten sind gestoppt. Routinen und Missionen bleiben angehalten, bis du sie freigibst.",+ "release": "Freigeben",+ "turn_on": "Einstellungen öffnen"+ },+ "digest": {+ "label": "Seit gestern",+ "built": "{count} gebaut",+ "proposed": "{count} vorgeschlagen",+ "kept": "{count} behalten",+ "archived": "{count} archiviert",+ "undone": "{count} rückgängig gemacht",+ "live": "{count} gerade live",+ "nothing": "Nichts Neues."+ },+ "shelf": {+ "waiting": "Wartet auf dich",+ "waiting_hint": "Nichts wird gebaut, bevor du Ja sagst.",+ "trial": "Auf Probe",+ "trial_hint": "Live und gekennzeichnet. Rückgängig entfernt es vollständig.",+ "working": "Wird gebaut",+ "working_hint": "Wird geprüft, bevor es live geht.",+ "kept": "Behalten",+ "kept_hint": "Hat sich bewährt. Weiter rückgängig zu machen.",+ "past": "Archiviert und rückgängig gemacht",+ "past_hint": "Archivierte Bauten lassen sich wiederherstellen."+ },+ "show_past": "{count} anzeigen",+ "hide_past": "Ausblenden",+ "kind": {+ "memory": "Erinnerung",+ "skill": "Skill",+ "routine": "Routine",+ "agent": "Agent",+ "code": "Code-Änderung"+ },+ "state": {+ "proposed": "Vorgeschlagen",+ "building": "Wird gebaut",+ "proving": "Wird geprüft",+ "trial": "Auf Probe",+ "kept": "Behalten",+ "archived": "Archiviert",+ "undone": "Rückgängig gemacht",+ "rejected": "Abgelehnt",+ "failed": "Fehlgeschlagen"+ },+ "step": {+ "proposed": "Bemerkt",+ "building": "Gebaut",+ "proving": "Geprüft",+ "trial": "Probe",+ "kept": "Behalten"+ },+ "seen": "{count}× gesehen",+ "trial_progress": "Tag {days} von {dayLimit} · {uses} von {useLimit} Nutzungen",+ "action": {+ "accept": "Bauen",+ "reject": "Nicht das",+ "keep": "Behalten",+ "restore": "Wiederherstellen",+ "undo": "Rückgängig"+ },+ "no_builder": "{name} kann diese Art noch nicht bauen. Es bleibt ein Vorschlag.",+ "detail": {+ "select": "Wähle einen Bau, um zu sehen, warum es ihn gibt, wie er geprüft wurde und was er gekostet hat.",+ "close": "Schließen",+ "why": "Warum",+ "noticed": "Was es bemerkt hat",+ "noticed_empty": "Keine Belege aufgezeichnet.",+ "proof": "Wie es geprüft wurde",+ "proof_passed": "Bestanden",+ "proof_failed": "Nicht bestanden",+ "proof_none": "Noch nicht geprüft.",+ "made": "Was es gebaut hat",+ "made_none": "Es existiert noch nichts.",+ "open_link": "Öffnen",+ "use": "Nutzung",+ "uses": "{count} Nutzungen",+ "unused": "Noch nicht genutzt.",+ "cost": "Kosten",+ "cost_none": "Nichts berechnet",+ "tokens": "{count} Tokens",+ "history": "Verlauf",+ "note": "Notiz",+ "opened": "eröffnet"+ },+ "outcome": {+ "used": "genutzt",+ "accepted": "unverändert übernommen",+ "corrected": "korrigiert",+ "ignored": "ignoriert"+ },+ "empty": {+ "title": "Noch nichts gebaut",+ "body": "{name} achtet auf Dinge, die du immer wieder von Hand tust. Wiederholt sich etwas, baut es das Kleinste, das es dir abnimmt, prüft es und lässt es dich ausprobieren, mit Rückgängig per Klick.",+ "loop": {+ "notice": "Bemerken",+ "decide": "Entscheiden",+ "build": "Bauen",+ "check": "Prüfen",+ "trial": "Probe",+ "keep": "Behalten"+ }+ },+ "error": {+ "unavailable": "Das Bau-Register läuft nicht. Starte die App neu, um es zu öffnen.",+ "action": "Das hat nicht geklappt: {detail}"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/self_build/en.json b/dodaios/ui/web/frontend/src/i18n/locales/self_build/en.jsonnew file mode 100644index 0000000000..bcb908353c--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/self_build/en.json@@ -0,0 +1,134 @@+{+ "self_build": {+ "title": "Built for you",+ "subtitle": "What {name} built on its own, why it did, and how to take it back.",+ "loading": "Loading builds…",+ "status": {+ "running": "Building on its own",+ "paused": "Paused",+ "silent": "Taking notes only",+ "off": "Off"+ },+ "pause": "Pause building",+ "resume": "Resume building",+ "pause_hint": "Stops noticing, building and settling trials. Everything built so far stays as it is.",+ "settings": "Settings",+ "stop_all": "Stop all agents",+ "stop_all_hint": "Stops every running agent, mission and routine at once, and pauses building.",+ "stop_confirm_title": "Stop every agent now?",+ "stop_confirm_body": "Running chats, missions and routines stop at once, and building pauses too. Nothing is deleted.",+ "cancel": "Cancel",+ "notes": {+ "paused": "Building is paused. Nothing is noticed, built or settled until you resume.",+ "silent": "The first days are quiet: {name} notes what you repeat and builds nothing yet.",+ "off": "Self-building is off. Nothing is noticed or built.",+ "stopped": "All agents are stopped. Routines and missions stay halted until you release them.",+ "release": "Release",+ "turn_on": "Open settings"+ },+ "digest": {+ "label": "Since yesterday",+ "built": "{count} built",+ "proposed": "{count} proposed",+ "kept": "{count} kept",+ "archived": "{count} archived",+ "undone": "{count} undone",+ "live": "{count} live now",+ "nothing": "Nothing new."+ },+ "shelf": {+ "waiting": "Waiting for you",+ "waiting_hint": "Nothing is built until you say yes.",+ "trial": "On trial",+ "trial_hint": "Live and labelled. Undo removes it completely.",+ "working": "Being built",+ "working_hint": "Checked before it goes live.",+ "kept": "Kept",+ "kept_hint": "Earned its place. Still undoable.",+ "past": "Archived and undone",+ "past_hint": "Archived builds can be restored."+ },+ "show_past": "Show {count}",+ "hide_past": "Hide",+ "kind": {+ "memory": "Memory",+ "skill": "Skill",+ "routine": "Routine",+ "agent": "Agent",+ "code": "Code change"+ },+ "state": {+ "proposed": "Proposed",+ "building": "Building",+ "proving": "Being checked",+ "trial": "On trial",+ "kept": "Kept",+ "archived": "Archived",+ "undone": "Undone",+ "rejected": "Turned down",+ "failed": "Failed"+ },+ "step": {+ "proposed": "Noticed",+ "building": "Built",+ "proving": "Checked",+ "trial": "Trial",+ "kept": "Kept"+ },+ "seen": "seen {count}×",+ "trial_progress": "Day {days} of {dayLimit} · {uses} of {useLimit} uses",+ "action": {+ "accept": "Build it",+ "reject": "Not this",+ "keep": "Keep",+ "restore": "Restore",+ "undo": "Undo"+ },+ "no_builder": "{name} cannot build this kind yet. It stays a suggestion.",+ "detail": {+ "select": "Pick a build to see why it exists, how it was checked and what it cost.",+ "close": "Close",+ "why": "Why",+ "noticed": "What it noticed",+ "noticed_empty": "No evidence recorded.",+ "proof": "How it was checked",+ "proof_passed": "Passed",+ "proof_failed": "Did not pass",+ "proof_none": "Not checked yet.",+ "made": "What it made",+ "made_none": "Nothing exists yet.",+ "open_link": "Open",+ "use": "Use",+ "uses": "{count} uses",+ "unused": "Not used yet.",+ "cost": "Cost",+ "cost_none": "Nothing billed",+ "tokens": "{count} tokens",+ "history": "History",+ "note": "Note",+ "opened": "opened"+ },+ "outcome": {+ "used": "used",+ "accepted": "accepted as is",+ "corrected": "corrected",+ "ignored": "ignored"+ },+ "empty": {+ "title": "Nothing built yet",+ "body": "{name} watches for things you keep doing by hand. When something repeats, it builds the smallest thing that takes it off you, checks it, and lets you try it with one-click undo.",+ "loop": {+ "notice": "Notice",+ "decide": "Decide",+ "build": "Build",+ "check": "Check",+ "trial": "Trial",+ "keep": "Keep"+ }+ },+ "error": {+ "unavailable": "The build ledger is not running. Restart the app to open it.",+ "action": "That did not work: {detail}"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/self_build/es.json b/dodaios/ui/web/frontend/src/i18n/locales/self_build/es.jsonnew file mode 100644index 0000000000..4ae2bb7bcf--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/self_build/es.json@@ -0,0 +1,134 @@+{+ "self_build": {+ "title": "Hecho para ti",+ "subtitle": "Lo que {name} construyó por su cuenta, por qué lo hizo y cómo deshacerlo.",+ "loading": "Cargando construcciones…",+ "status": {+ "running": "Construye por su cuenta",+ "paused": "En pausa",+ "silent": "Solo toma notas",+ "off": "Desactivado"+ },+ "pause": "Pausar la construcción",+ "resume": "Reanudar la construcción",+ "pause_hint": "Deja de notar, construir y cerrar pruebas. Todo lo construido hasta ahora se queda como está.",+ "settings": "Ajustes",+ "stop_all": "Detener todos los agentes",+ "stop_all_hint": "Detiene de inmediato cada agente, misión y rutina en marcha, y pausa la construcción.",+ "stop_confirm_title": "¿Detener ahora todos los agentes?",+ "stop_confirm_body": "Los chats, misiones y rutinas en marcha se detienen de inmediato, y la construcción también se pausa. No se borra nada.",+ "cancel": "Cancelar",+ "notes": {+ "paused": "La construcción está en pausa. No se nota, construye ni cierra nada hasta que la reanudes.",+ "silent": "Los primeros días son tranquilos: {name} anota lo que repites y todavía no construye nada.",+ "off": "La autoconstrucción está desactivada. No se nota ni se construye nada.",+ "stopped": "Todos los agentes están detenidos. Las rutinas y misiones siguen paradas hasta que las liberes.",+ "release": "Liberar",+ "turn_on": "Abrir ajustes"+ },+ "digest": {+ "label": "Desde ayer",+ "built": "{count} construidos",+ "proposed": "{count} propuestos",+ "kept": "{count} conservados",+ "archived": "{count} archivados",+ "undone": "{count} deshechos",+ "live": "{count} activos ahora",+ "nothing": "Nada nuevo."+ },+ "shelf": {+ "waiting": "Esperando por ti",+ "waiting_hint": "No se construye nada hasta que digas que sí.",+ "trial": "En prueba",+ "trial_hint": "Activo y señalado. Deshacer lo quita por completo.",+ "working": "En construcción",+ "working_hint": "Se comprueba antes de activarse.",+ "kept": "Conservados",+ "kept_hint": "Se ganó su lugar. Todavía se puede deshacer.",+ "past": "Archivados y deshechos",+ "past_hint": "Las construcciones archivadas se pueden restaurar."+ },+ "show_past": "Mostrar {count}",+ "hide_past": "Ocultar",+ "kind": {+ "memory": "Recuerdo",+ "skill": "Habilidad",+ "routine": "Rutina",+ "agent": "Agente",+ "code": "Cambio de código"+ },+ "state": {+ "proposed": "Propuesto",+ "building": "Construyendo",+ "proving": "En comprobación",+ "trial": "En prueba",+ "kept": "Conservado",+ "archived": "Archivado",+ "undone": "Deshecho",+ "rejected": "Rechazado",+ "failed": "Falló"+ },+ "step": {+ "proposed": "Notado",+ "building": "Construido",+ "proving": "Comprobado",+ "trial": "Prueba",+ "kept": "Conservado"+ },+ "seen": "visto {count}×",+ "trial_progress": "Día {days} de {dayLimit} · {uses} de {useLimit} usos",+ "action": {+ "accept": "Construirlo",+ "reject": "Esto no",+ "keep": "Conservar",+ "restore": "Restaurar",+ "undo": "Deshacer"+ },+ "no_builder": "{name} todavía no puede construir este tipo. Se queda como sugerencia.",+ "detail": {+ "select": "Elige una construcción para ver por qué existe, cómo se comprobó y cuánto costó.",+ "close": "Cerrar",+ "why": "Por qué",+ "noticed": "Lo que notó",+ "noticed_empty": "No hay pruebas registradas.",+ "proof": "Cómo se comprobó",+ "proof_passed": "Superada",+ "proof_failed": "No superada",+ "proof_none": "Todavía sin comprobar.",+ "made": "Lo que construyó",+ "made_none": "Todavía no existe nada.",+ "open_link": "Abrir",+ "use": "Uso",+ "uses": "{count} usos",+ "unused": "Todavía sin usar.",+ "cost": "Coste",+ "cost_none": "Nada facturado",+ "tokens": "{count} tokens",+ "history": "Historial",+ "note": "Nota",+ "opened": "abierto"+ },+ "outcome": {+ "used": "usado",+ "accepted": "aceptado tal cual",+ "corrected": "corregido",+ "ignored": "ignorado"+ },+ "empty": {+ "title": "Todavía no hay nada construido",+ "body": "{name} se fija en lo que haces a mano una y otra vez. Cuando algo se repite, construye lo más pequeño que te lo quite de encima, lo comprueba y te deja probarlo con deshacer en un clic.",+ "loop": {+ "notice": "Notar",+ "decide": "Decidir",+ "build": "Construir",+ "check": "Comprobar",+ "trial": "Prueba",+ "keep": "Conservar"+ }+ },+ "error": {+ "unavailable": "El registro de construcciones no está en marcha. Reinicia la app para abrirlo.",+ "action": "No funcionó: {detail}"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/self_build/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/self_build/pt.jsonnew file mode 100644index 0000000000..cce2e3f750--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/self_build/pt.json@@ -0,0 +1,134 @@+{+ "self_build": {+ "title": "Feito para si",+ "subtitle": "O que {name} construiu por iniciativa própria, porquê, e como o desfazer.",+ "loading": "A carregar construções…",+ "status": {+ "running": "Constrói por iniciativa própria",+ "paused": "Em pausa",+ "silent": "Só toma notas",+ "off": "Desligado"+ },+ "pause": "Pausar construção",+ "resume": "Retomar construção",+ "pause_hint": "Deixa de reparar, construir e concluir ensaios. Tudo o que já foi construído fica como está.",+ "settings": "Definições",+ "stop_all": "Parar todos os agentes",+ "stop_all_hint": "Para de imediato todos os agentes, missões e rotinas em curso, e pausa a construção.",+ "stop_confirm_title": "Parar já todos os agentes?",+ "stop_confirm_body": "Conversas, missões e rotinas em curso param de imediato, e a construção também pausa. Nada é apagado.",+ "cancel": "Cancelar",+ "notes": {+ "paused": "A construção está em pausa. Nada é notado, construído ou concluído até retomar.",+ "silent": "Os primeiros dias são calmos: {name} anota o que repete e ainda não constrói nada.",+ "off": "A autoconstrução está desligada. Nada é notado nem construído.",+ "stopped": "Todos os agentes estão parados. Rotinas e missões ficam paradas até as libertar.",+ "release": "Libertar",+ "turn_on": "Abrir definições"+ },+ "digest": {+ "label": "Desde ontem",+ "built": "{count} construídos",+ "proposed": "{count} propostos",+ "kept": "{count} mantidos",+ "archived": "{count} arquivados",+ "undone": "{count} anulados",+ "live": "{count} ativos agora",+ "nothing": "Nada de novo."+ },+ "shelf": {+ "waiting": "À sua espera",+ "waiting_hint": "Nada é construído antes de dizer que sim.",+ "trial": "Em ensaio",+ "trial_hint": "Ativo e assinalado. Anular remove-o por completo.",+ "working": "Em construção",+ "working_hint": "É verificado antes de ficar ativo.",+ "kept": "Mantidos",+ "kept_hint": "Mereceu o lugar. Ainda pode ser anulado.",+ "past": "Arquivados e anulados",+ "past_hint": "As construções arquivadas podem ser restauradas."+ },+ "show_past": "Mostrar {count}",+ "hide_past": "Ocultar",+ "kind": {+ "memory": "Memória",+ "skill": "Competência",+ "routine": "Rotina",+ "agent": "Agente",+ "code": "Alteração de código"+ },+ "state": {+ "proposed": "Proposto",+ "building": "Em construção",+ "proving": "Em verificação",+ "trial": "Em ensaio",+ "kept": "Mantido",+ "archived": "Arquivado",+ "undone": "Anulado",+ "rejected": "Recusado",+ "failed": "Falhou"+ },+ "step": {+ "proposed": "Notado",+ "building": "Construído",+ "proving": "Verificado",+ "trial": "Ensaio",+ "kept": "Mantido"+ },+ "seen": "visto {count}×",+ "trial_progress": "Dia {days} de {dayLimit} · {uses} de {useLimit} utilizações",+ "action": {+ "accept": "Construir",+ "reject": "Isto não",+ "keep": "Manter",+ "restore": "Restaurar",+ "undo": "Anular"+ },+ "no_builder": "{name} ainda não consegue construir este tipo. Fica como sugestão.",+ "detail": {+ "select": "Escolha uma construção para ver porque existe, como foi verificada e quanto custou.",+ "close": "Fechar",+ "why": "Porquê",+ "noticed": "O que notou",+ "noticed_empty": "Sem provas registadas.",+ "proof": "Como foi verificado",+ "proof_passed": "Aprovado",+ "proof_failed": "Não aprovado",+ "proof_none": "Ainda não verificado.",+ "made": "O que construiu",+ "made_none": "Ainda não existe nada.",+ "open_link": "Abrir",+ "use": "Utilização",+ "uses": "{count} utilizações",+ "unused": "Ainda não utilizado.",+ "cost": "Custo",+ "cost_none": "Nada cobrado",+ "tokens": "{count} tokens",+ "history": "Histórico",+ "note": "Nota",+ "opened": "aberto"+ },+ "outcome": {+ "used": "utilizado",+ "accepted": "aceite tal como estava",+ "corrected": "corrigido",+ "ignored": "ignorado"+ },+ "empty": {+ "title": "Ainda nada construído",+ "body": "{name} repara no que faz à mão vezes sem conta. Quando algo se repete, constrói a coisa mais pequena que lhe tira esse trabalho, verifica-a e deixa-o experimentá-la com anulação num clique.",+ "loop": {+ "notice": "Reparar",+ "decide": "Decidir",+ "build": "Construir",+ "check": "Verificar",+ "trial": "Ensaio",+ "keep": "Manter"+ }+ },+ "error": {+ "unavailable": "O registo de construções não está a correr. Reinicie a app para o abrir.",+ "action": "Não resultou: {detail}"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/self_build/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/self_build/zh.jsonnew file mode 100644index 0000000000..ce21d8d2da--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/self_build/zh.json@@ -0,0 +1,134 @@+{+ "self_build": {+ "title": "为你构建",+ "subtitle": "{name} 主动构建了什么、为什么构建,以及如何撤回。",+ "loading": "正在加载构建…",+ "status": {+ "running": "正在主动构建",+ "paused": "已暂停",+ "silent": "只做记录",+ "off": "关闭"+ },+ "pause": "暂停构建",+ "resume": "继续构建",+ "pause_hint": "停止留意、构建和结束试用。已构建的一切保持原样。",+ "settings": "设置",+ "stop_all": "停止所有智能体",+ "stop_all_hint": "立即停止所有正在运行的智能体、任务和例程,并暂停构建。",+ "stop_confirm_title": "现在停止所有智能体?",+ "stop_confirm_body": "正在进行的对话、任务和例程会立即停止,构建也会暂停。不会删除任何内容。",+ "cancel": "取消",+ "notes": {+ "paused": "构建已暂停。在你继续之前,不会留意、构建或结束任何东西。",+ "silent": "最初几天很安静:{name} 记录你重复的事情,暂时不构建任何东西。",+ "off": "自主构建已关闭。不留意也不构建任何东西。",+ "stopped": "所有智能体已停止。例程和任务会一直停着,直到你解除。",+ "release": "解除",+ "turn_on": "打开设置"+ },+ "digest": {+ "label": "自昨天以来",+ "built": "构建了 {count} 个",+ "proposed": "提议了 {count} 个",+ "kept": "保留了 {count} 个",+ "archived": "归档了 {count} 个",+ "undone": "撤销了 {count} 个",+ "live": "当前上线 {count} 个",+ "nothing": "没有新内容。"+ },+ "shelf": {+ "waiting": "等待你的决定",+ "waiting_hint": "在你同意之前不会构建任何东西。",+ "trial": "试用中",+ "trial_hint": "已上线并有标记。撤销会把它完全移除。",+ "working": "构建中",+ "working_hint": "上线前会先检查。",+ "kept": "已保留",+ "kept_hint": "证明了自己的价值。仍可撤销。",+ "past": "已归档和已撤销",+ "past_hint": "已归档的构建可以恢复。"+ },+ "show_past": "显示 {count} 个",+ "hide_past": "隐藏",+ "kind": {+ "memory": "记忆",+ "skill": "技能",+ "routine": "例程",+ "agent": "智能体",+ "code": "代码更改"+ },+ "state": {+ "proposed": "已提议",+ "building": "构建中",+ "proving": "检查中",+ "trial": "试用中",+ "kept": "已保留",+ "archived": "已归档",+ "undone": "已撤销",+ "rejected": "已拒绝",+ "failed": "失败"+ },+ "step": {+ "proposed": "留意到",+ "building": "已构建",+ "proving": "已检查",+ "trial": "试用",+ "kept": "已保留"+ },+ "seen": "见过 {count} 次",+ "trial_progress": "第 {days} / {dayLimit} 天 · {uses} / {useLimit} 次使用",+ "action": {+ "accept": "构建",+ "reject": "不要这个",+ "keep": "保留",+ "restore": "恢复",+ "undo": "撤销"+ },+ "no_builder": "{name} 还不能构建这种类型。它会保持为建议。",+ "detail": {+ "select": "选择一个构建,查看它为何存在、如何检查以及花费多少。",+ "close": "关闭",+ "why": "原因",+ "noticed": "它留意到了什么",+ "noticed_empty": "没有记录证据。",+ "proof": "如何检查",+ "proof_passed": "通过",+ "proof_failed": "未通过",+ "proof_none": "尚未检查。",+ "made": "它构建了什么",+ "made_none": "还没有任何东西。",+ "open_link": "打开",+ "use": "使用",+ "uses": "{count} 次使用",+ "unused": "尚未使用。",+ "cost": "费用",+ "cost_none": "未计费",+ "tokens": "{count} 个 token",+ "history": "历史",+ "note": "备注",+ "opened": "创建于"+ },+ "outcome": {+ "used": "已使用",+ "accepted": "原样接受",+ "corrected": "已修正",+ "ignored": "已忽略"+ },+ "empty": {+ "title": "还没有构建任何东西",+ "body": "{name} 会留意你一再手动去做的事情。当某件事重复出现时,它会构建能替你完成它的最小的东西,进行检查,并让你在可一键撤销的情况下试用。",+ "loop": {+ "notice": "留意",+ "decide": "决定",+ "build": "构建",+ "check": "检查",+ "trial": "试用",+ "keep": "保留"+ }+ },+ "error": {+ "unavailable": "构建记录未在运行。重启应用即可打开。",+ "action": "操作失败:{detail}"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex dcd18079c9..010d071c6c 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -343,7 +343,8 @@"voice_language": "语言","voice_api_keys": "API 密钥","shortcuts": "键盘快捷键",- "pets": "我的宠物"+ "pets": "我的宠物",+ "self_build": "为你构建"},"assistant_view": {"header_named": "你在 {0} 中的助手,用“{1}”唤醒。",@@ -3170,7 +3171,8 @@"music": "音乐","keybinds": "键盘快捷键","more": "更多",- "overlay_taskbar": "悬浮层与任务栏"+ "overlay_taskbar": "悬浮层与任务栏",+ "self_build": "自主构建"},"languages_group_title": "语言","sections": {@@ -3515,7 +3517,43 @@"system_now_dark": "正在跟随系统,当前为深色。","system_now_light": "正在跟随系统,当前为浅色。"},- "invalid_setting": "设置无效"+ "invalid_setting": "设置无效",+ "self_build": {+ "title": "自主构建",+ "description": "{name} 主动为你构建东西时可以走多远。",+ "open_view": "打开“为你构建”",+ "enabled_title": "主动构建",+ "enabled_description": "留意你反复在做的事,并构建能替你完成它的东西。关闭:不留意也不构建任何东西。",+ "autonomy_title": "每种类型的范围",+ "autonomy_description": "关闭:从不。建议:先用卡片询问。试用:构建、检查并上线,一键撤销。完全:与试用相同,被使用过的试用会自动保留。",+ "levels": {+ "off": "关闭",+ "suggest": "建议",+ "trial": "试用",+ "full": "完全"+ },+ "kinds": {+ "memory": "记忆",+ "skill": "技能",+ "routine": "例程",+ "agent": "智能体",+ "code": "代码更改"+ },+ "limits_title": "限制",+ "limits_description": "无论如何决定,循环都不会超过的硬性上限。",+ "limits": {+ "max_builds_per_day": "每天构建数",+ "max_open_trials": "同时进行的试用",+ "max_agents_per_week": "每周新智能体",+ "max_code_runs_per_day": "每天代码运行数",+ "trial_days": "试用时长(天)",+ "trial_uses": "试用时长(次)",+ "max_rejections": "被拒绝这么多次后不再提议",+ "silent_days": "最初的安静天数"+ },+ "save_error": "无法保存:{detail}",+ "unavailable": "无法加载这些设置。"+ }},"telephony_view": {"title": "电话(实验性)",@@ -10110,5 +10148,10 @@"objections_one": "{count} 条异议","objections_other": "{count} 条异议"}+ },+ "self_build_badge": {+ "label": "由 {name} 构建",+ "title": "{name} 主动构建了它。打开它的构建记录。",+ "trial": "试用中"}}diff --git a/dodaios/ui/web/frontend/src/i18n/pt-locale-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/pt-locale-parity.test.tsindex 0fa6bc57b1..fb14f00e67 100644--- a/dodaios/ui/web/frontend/src/i18n/pt-locale-parity.test.ts+++ b/dodaios/ui/web/frontend/src/i18n/pt-locale-parity.test.ts@@ -22,6 +22,8 @@ import paneReviewEn from "./locales/pane_review/en.json";import paneReviewPt from "./locales/pane_review/pt.json";import providersEn from "./locales/providers/en.json";import providersPt from "./locales/providers/pt.json";+import selfBuildEn from "./locales/self_build/en.json";+import selfBuildPt from "./locales/self_build/pt.json";import societyEn from "./locales/society/en.json";import societyPt from "./locales/society/pt.json";@@ -37,6 +39,7 @@ const PAIRS: [string, Tree, Tree][] = [["pane_review", paneReviewEn, paneReviewPt],["providers", providersEn, providersPt],["society", societyEn, societyPt],+ ["self_build", selfBuildEn, selfBuildPt],];function leaves(tree: Tree, prefix = ""): Map<string, unknown> {diff --git a/dodaios/ui/web/frontend/src/i18n/self-build-i18n-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/self-build-i18n-parity.test.tsnew file mode 100644index 0000000000..721e4d20f5--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/self-build-i18n-parity.test.ts@@ -0,0 +1,116 @@+/**+ * "Built for you" must be complete in every interface language: the lazy+ * `self_build` chunk and the blocks the main dictionary carries for it (the nav+ * row, the Settings group, the "built by" badge) hold exactly the keys English+ * holds, keep every placeholder, and every literal key the surfaces ask for+ * exists. Keys are read from the source files, so a string added without its+ * translations fails here, not in front of a person.+ */+import { readFileSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import en from "./locales/en.json";+import de from "./locales/de.json";+import es from "./locales/es.json";+import pt from "./locales/pt.json";+import zh from "./locales/zh.json";+import chunkEn from "./locales/self_build/en.json";+import chunkDe from "./locales/self_build/de.json";+import chunkEs from "./locales/self_build/es.json";+import chunkPt from "./locales/self_build/pt.json";+import chunkZh from "./locales/self_build/zh.json";++type Tree = Record<string, unknown>;++function leaves(tree: unknown, prefix = ""): Map<string, unknown> {+ const out = new Map<string, unknown>();+ if (!tree || typeof tree !== "object") return out;+ for (const [key, value] of Object.entries(tree as Tree)) {+ const path = prefix ? `${prefix}.${key}` : key;+ if (value && typeof value === "object" && !Array.isArray(value)) {+ for (const [k, v] of leaves(value, path)) out.set(k, v);+ } else {+ out.set(path, value);+ }+ }+ return out;+}++const mainBlocks = (tree: Tree) =>+ new Map([+ ["nav.self_build", (tree.nav as Tree).self_build],+ ["settings_view.nav.self_build", ((tree.settings_view as Tree).nav as Tree).self_build],+ ...leaves((tree.settings_view as Tree).self_build, "settings_view.self_build"),+ ...leaves(tree.self_build_badge, "self_build_badge"),+ ]);++const PLACEHOLDER = /\{\w+\}/g;+const placeholders = (text: unknown) =>+ typeof text === "string" ? (text.match(PLACEHOLDER) ?? []).sort() : [];++const LANGS: [string, Tree, Tree][] = [+ ["de", de as Tree, chunkDe as Tree],+ ["es", es as Tree, chunkEs as Tree],+ ["pt", pt as Tree, chunkPt as Tree],+ ["zh", zh as Tree, chunkZh as Tree],+];++describe("self-build strings", () => {+ const chunkSource = leaves(chunkEn);+ const mainSource = mainBlocks(en as Tree);++ for (const [lang, main, chunk] of LANGS) {+ it(`${lang}: the chunk carries every English key with its placeholders`, () => {+ const target = leaves(chunk);+ expect([...target.keys()].sort()).toEqual([...chunkSource.keys()].sort());+ for (const [key, text] of chunkSource) {+ expect(placeholders(target.get(key)), `${lang} ${key}`).toEqual(placeholders(text));+ expect(String(target.get(key)).trim(), `${lang} ${key}`).not.toBe("");+ }+ });++ it(`${lang}: the main dictionary carries the nav, settings and badge strings`, () => {+ const target = mainBlocks(main);+ expect([...target.keys()].sort()).toEqual([...mainSource.keys()].sort());+ for (const [key, text] of mainSource) {+ expect(typeof target.get(key), `${lang} ${key}`).toBe("string");+ expect(placeholders(target.get(key)), `${lang} ${key}`).toEqual(placeholders(text));+ }+ });+ }++ it("German uses real umlauts, never ae/oe/ue stand-ins", () => {+ const texts = [...leaves(chunkDe).values(), ...mainBlocks(de as Tree).values()].map(String);+ expect(texts.join(" ")).toMatch(/[äöüß]/);+ for (const text of texts) expect(text).not.toMatch(/\b(fuer|ueber|Rueck|zurueck|moeglich)\w*/i);+ });++ it("every literal self_build key the surfaces ask for exists in English", () => {+ const src = join(__dirname, "..");+ const files = [+ join(src, "views", "SelfBuildView.tsx"),+ join(src, "views", "settings", "SelfBuildGroup.tsx"),+ join(src, "components", "selfBuild", "BuiltByBadge.tsx"),+ ...walk(join(src, "views", "selfBuild")),+ ];+ const known = new Set([...chunkSource.keys(), ...mainSource.keys()]);+ const missing: string[] = [];+ for (const file of files) {+ const text = readFileSync(file, "utf-8");+ for (const match of text.matchAll(/t\("((?:self_build|settings_view\.self_build|self_build_badge)\.[\w.]+)"\)/g)) {+ if (!known.has(match[1])) missing.push(`${file}: ${match[1]}`);+ }+ }+ expect(missing).toEqual([]);+ });+});++function walk(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) out.push(...walk(full));+ else if (/\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) out.push(full);+ }+ return out;+}diff --git a/dodaios/ui/web/frontend/src/i18n/zh-locale-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/zh-locale-parity.test.tsindex 2c6e532fd3..5c7e6d55e3 100644--- a/dodaios/ui/web/frontend/src/i18n/zh-locale-parity.test.ts+++ b/dodaios/ui/web/frontend/src/i18n/zh-locale-parity.test.ts@@ -22,6 +22,8 @@ import paneReviewEn from "./locales/pane_review/en.json";import paneReviewZh from "./locales/pane_review/zh.json";import providersEn from "./locales/providers/en.json";import providersZh from "./locales/providers/zh.json";+import selfBuildEn from "./locales/self_build/en.json";+import selfBuildZh from "./locales/self_build/zh.json";import societyEn from "./locales/society/en.json";import societyZh from "./locales/society/zh.json";@@ -37,6 +39,7 @@ const PAIRS: [string, Tree, Tree][] = [["pane_review", paneReviewEn, paneReviewZh],["providers", providersEn, providersZh],["society", societyEn, societyZh],+ ["self_build", selfBuildEn, selfBuildZh],];function leaves(tree: Tree, prefix = ""): Map<string, unknown> {diff --git a/dodaios/ui/web/frontend/src/lib/selfBuildApi.ts b/dodaios/ui/web/frontend/src/lib/selfBuildApi.tsnew file mode 100644index 0000000000..3d263c04b5--- /dev/null+++ b/dodaios/ui/web/frontend/src/lib/selfBuildApi.ts@@ -0,0 +1,256 @@+/**+ * Typed client for the self-building ledger (dodaios/ui/web/self_build_routes.py).+ *+ * The shapes mirror `BuildRecord.to_json()` in dodaios/self_build/records.py;+ * the backend stays the authority. Errors arrive as `{detail: "..."}` and are+ * rethrown as `SelfBuildApiError` with the HTTP status, so a view can tell+ * "the ledger is not running" (503) from "this move is not allowed" (409).+ */++export type BuildKind = "memory" | "skill" | "routine" | "agent" | "code";+export type BuildState =+ | "proposed"+ | "building"+ | "proving"+ | "trial"+ | "kept"+ | "archived"+ | "undone"+ | "rejected"+ | "failed";+export type Autonomy = "off" | "suggest" | "trial" | "full";+export type BuildOutcome = "used" | "accepted" | "corrected" | "ignored";++export const BUILD_KINDS: readonly BuildKind[] = ["memory", "skill", "routine", "agent", "code"];++export interface BuildProof {+ passed?: boolean;+ judge?: string;+ detail?: string;+ [key: string]: unknown;+}++export interface BuildArtefact {+ type?: string;+ id?: string;+ label?: string;+ url?: string;+ [key: string]: unknown;+}++export interface Build {+ id: string;+ kind: BuildKind;+ state: BuildState;+ signature: string;+ /** One sentence the person reads: why this build exists. */+ title: string;+ case: string;+ evidence: string[];+ proof: BuildProof;+ artefact: BuildArtefact;+ uses: number;+ outcomes: Partial<Record<BuildOutcome, number>>;+ note: string;+ created_ms: number;+ updated_ms: number;+ trial_started_ms: number;+ last_used_ms: number;+ undoable: boolean;+}++export interface SelfBuildStatus {+ enabled: boolean;+ paused: boolean;+ silent: boolean;+ autonomy: Record<BuildKind, Autonomy>;+ /** Kinds a builder is registered for; a proposal of another kind cannot be built yet. */+ builders: BuildKind[];+}++export interface BuildList {+ builds: Build[];+ status: SelfBuildStatus;+}++export interface BuildHistoryEntry {+ ts_ms: number;+ from: string;+ to: string;+ note: string;+}++export interface BuildDetail {+ build: Build;+ history: BuildHistoryEntry[];+ cost: { tokens: number; usd: number };+}++export interface BuildDigest {+ since_ms: number;+ until_ms: number;+ counts: Partial<Record<BuildState, number>>;+ live: number;+ items: Build[];+}++export interface SelfBuildSettings {+ enabled: boolean;+ silent_days: number;+ memory: Autonomy;+ skill: Autonomy;+ routine: Autonomy;+ agent: Autonomy;+ code: Autonomy;+ trial_days: number;+ trial_uses: number;+ max_builds_per_day: number;+ max_agents_per_week: number;+ max_open_trials: number;+ max_code_runs_per_day: number;+ max_rejections: number;+}++export interface SelfBuildSettingsPayload {+ settings: SelfBuildSettings;+ levels: Autonomy[];+ bounds: Partial<Record<keyof SelfBuildSettings, { min: number | null; max: number | null }>>;+}++export interface ProvenanceItem {+ build_id: string;+ type: string;+ id: string;+ state: BuildState;+ title: string;+}++export class SelfBuildApiError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "SelfBuildApiError";+ }+}++const BASE = "/api/self-build";++async function call<T>(path: string, init?: RequestInit): Promise<T> {+ const res = await fetch(`${BASE}${path}`, {+ ...init,+ headers: init?.body ? { "Content-Type": "application/json", ...init.headers } : init?.headers,+ });+ if (!res.ok) {+ let detail = `HTTP ${res.status}`;+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (typeof body.detail === "string") detail = body.detail;+ } catch {+ /* not JSON */+ }+ throw new SelfBuildApiError(detail, res.status);+ }+ return (await res.json()) as T;+}++const post = <T>(path: string, body?: unknown) =>+ call<T>(path, { method: "POST", body: body === undefined ? undefined : JSON.stringify(body) });++export const selfBuildApi = {+ list: (signal?: AbortSignal) => call<BuildList>("", { signal }),+ detail: (id: string, signal?: AbortSignal) =>+ call<BuildDetail>(`/${encodeURIComponent(id)}`, { signal }),+ digest: (hours = 24, signal?: AbortSignal) =>+ call<BuildDigest>(`/digest?hours=${hours}`, { signal }),+ accept: (id: string) => post<{ build: Build }>(`/${encodeURIComponent(id)}/accept`),+ keep: (id: string) => post<{ build: Build }>(`/${encodeURIComponent(id)}/keep`),+ undo: (id: string, note = "") =>+ post<{ build: Build }>(`/${encodeURIComponent(id)}/undo`, { note }),+ pause: (paused: boolean) => post<SelfBuildStatus>("/pause", { paused }),+ settings: (signal?: AbortSignal) => call<SelfBuildSettingsPayload>("/settings", { signal }),+ saveSettings: (patch: Partial<SelfBuildSettings>) =>+ call<SelfBuildSettingsPayload>("/settings", { method: "PUT", body: JSON.stringify(patch) }),+ provenance: (type?: string, signal?: AbortSignal) =>+ call<{ items: Record<string, ProvenanceItem> }>(+ `/provenance${type ? `?type=${encodeURIComponent(type)}` : ""}`,+ { signal },+ ),+};++/** The society kill switch (dodaios/ui/web/society_routes.py): stops every agent. */+export const societyKillSwitchApi = {+ async status(signal?: AbortSignal): Promise<boolean> {+ const res = await fetch("/api/society/status", { signal });+ if (!res.ok) throw new SelfBuildApiError(`HTTP ${res.status}`, res.status);+ const body = (await res.json()) as { kill_switch?: unknown };+ return Boolean(body.kill_switch);+ },+ async set(engaged: boolean): Promise<void> {+ const res = await fetch(`/api/society/kill-switch${engaged ? "" : "/release"}`, {+ method: "POST",+ });+ if (!res.ok) throw new SelfBuildApiError(`HTTP ${res.status}`, res.status);+ },+};++// ------------------------------------------------------------------ reading a build++const LIFECYCLE: readonly BuildState[] = ["proposed", "building", "proving", "trial", "kept"];++/** The path a build walks, for the lifecycle rail: the five forward steps. */+export function lifecycleSteps(): readonly BuildState[] {+ return LIFECYCLE;+}++/**+ * How far along the forward path a build got: the index of its last reached+ * step. An off-path end state (archived, undone, rejected, failed) reports the+ * step it left from, read from its history when there is one.+ */+export function reachedStep(build: Build, history?: BuildHistoryEntry[]): number {+ const direct = LIFECYCLE.indexOf(build.state);+ if (direct >= 0) return direct;+ const last = history?.filter((h) => LIFECYCLE.includes(h.from as BuildState)).at(-1);+ if (last) return LIFECYCLE.indexOf(last.from as BuildState);+ if (build.state === "archived") return 3;+ if (build.state === "rejected") return 0;+ return build.trial_started_ms ? 3 : 0;+}++/** Which shelf of the view a build sits on — what, if anything, it asks of the person. */+export type Shelf = "waiting" | "trial" | "working" | "kept" | "past";++export function shelfOf(build: Build): Shelf {+ switch (build.state) {+ case "proposed":+ return "waiting";+ case "trial":+ return "trial";+ case "building":+ case "proving":+ return "working";+ case "kept":+ return "kept";+ default:+ return "past";+ }+}++export const DAY_MS = 86_400_000;++/** Days and uses of a trial against its limits; `null` when the build is not on trial. */+export function trialProgress(+ build: Build,+ limits: { trial_days: number; trial_uses: number } | undefined,+ now = Date.now(),+): { days: number; dayLimit: number; uses: number; useLimit: number; share: number } | null {+ if (build.state !== "trial" || !build.trial_started_ms || !limits) return null;+ const days = Math.max(0, Math.floor((now - build.trial_started_ms) / DAY_MS));+ const share = Math.min(+ 1,+ Math.max(days / Math.max(1, limits.trial_days), build.uses / Math.max(1, limits.trial_uses)),+ );+ return { days, dayLimit: limits.trial_days, uses: build.uses, useLimit: limits.trial_uses, share };+}diff --git a/dodaios/ui/web/frontend/src/store/events.ts b/dodaios/ui/web/frontend/src/store/events.tsindex b55a0b419e..37b6c44755 100644--- a/dodaios/ui/web/frontend/src/store/events.ts+++ b/dodaios/ui/web/frontend/src/store/events.ts@@ -112,7 +112,11 @@ export type SectionId =// The Jarvis Marketplace, in the app: everything the community published —// plugins and skills — browsable and installable in one place instead of// scattered across unrelated sections.- | "marketplace";+ | "marketplace"+ // Built for you: everything Dodaios built on its own initiative (the+ // self-building loop, docs/self-build.md) — why, how it was checked, what it+ // cost — with keep, undo and the loop's pause in one place.+ | "self-build";export const SECTION_IDS = ["chats",@@ -154,6 +158,7 @@ export const SECTION_IDS = ["chat-workspace","agentic-ide-classic","marketplace",+ "self-build",] as const satisfies readonly SectionId[];export function isSectionId(value: unknown): value is SectionId {@@ -250,6 +255,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {"chat-workspace": "Chat","agentic-ide-classic": "Terminal grid",marketplace: "Marketplace",+ "self-build": "Built for you",};/*** i18n keys for `SECTION_LABELS`, for user-facing readbacks (the voice-navigation@@ -293,6 +299,7 @@ export const SECTION_LABEL_KEYS: Record<SectionId, string> = {"chat-workspace": "nav.chat_workspace","agentic-ide-classic": "quick_switch.terminal_grid",marketplace: "nav.marketplace",+ "self-build": "nav.self_build",};export interface EventItem {diff --git a/dodaios/ui/web/frontend/src/store/selfBuildFocus.ts b/dodaios/ui/web/frontend/src/store/selfBuildFocus.tsnew file mode 100644index 0000000000..e151d359e0--- /dev/null+++ b/dodaios/ui/web/frontend/src/store/selfBuildFocus.ts@@ -0,0 +1,32 @@+/**+ * The build "Built for you" should open on, requested from OUTSIDE the view.+ *+ * A "built by" badge on an agent, a skill or a routine links to the build that+ * made it. The view may not be mounted yet, so the request is parked here, the+ * section opens, and the view takes the id over on mount — a one-shot hand-off+ * like `settingsJump`.+ */+import { create } from "zustand";+import { useEventStore } from "@/store/events";++interface SelfBuildFocusState {+ buildId: string | null;+ request: (buildId: string) => void;+ take: () => string | null;+}++export const useSelfBuildFocus = create<SelfBuildFocusState>((set, get) => ({+ buildId: null,+ request: (buildId) => set({ buildId }),+ take: () => {+ const { buildId } = get();+ if (buildId !== null) set({ buildId: null });+ return buildId;+ },+}));++/** Open "Built for you" on one build. */+export function openBuild(buildId: string): void {+ useSelfBuildFocus.getState().request(buildId);+ useEventStore.getState().setActiveSection("self-build");+}diff --git a/dodaios/ui/web/frontend/src/views/SelfBuildView.test.tsx b/dodaios/ui/web/frontend/src/views/SelfBuildView.test.tsxnew file mode 100644index 0000000000..0c31356a3b--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/SelfBuildView.test.tsx@@ -0,0 +1,237 @@+/**+ * "Built for you": builds sit on the shelf of what they ask of the person, a+ * proposal is built or turned down in one click, a trial is kept or undone in+ * one click, the pause and the society stop reach their routes, a build opens+ * into its case file, and the "built by" badge links back to its build.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";++import { SelfBuildView } from "@/views/SelfBuildView";+import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";+import { loadLocaleChunk, setUiLanguage } from "@/i18n";+import { useEventStore } from "@/store/events";+import { useSelfBuildFocus } from "@/store/selfBuildFocus";+import type { Build, SelfBuildStatus } from "@/lib/selfBuildApi";++const NOW = Date.now();++function build(overrides: Partial<Build>): Build {+ return {+ id: "b",+ kind: "skill",+ state: "proposed",+ signature: "s",+ title: "A build",+ case: "",+ evidence: [],+ proof: {},+ artefact: {},+ uses: 0,+ outcomes: {},+ note: "",+ created_ms: NOW - 3_600_000,+ updated_ms: NOW - 3_600_000,+ trial_started_ms: 0,+ last_used_ms: 0,+ undoable: true,+ ...overrides,+ };+}++const BUILDS: Build[] = [+ build({ id: "p1", title: "Rename invoice PDFs", evidence: ["t1", "t2", "t3"] }),+ build({ id: "p2", kind: "agent", title: "A release-notes writer" }),+ build({+ id: "t1",+ kind: "routine",+ state: "trial",+ title: "A standup digest",+ trial_started_ms: NOW - 3 * 86_400_000,+ uses: 4,+ outcomes: { accepted: 3, corrected: 1 },+ proof: { passed: true, judge: "shadow run", detail: "5 of 5" },+ artefact: { type: "routine", id: "task-1" },+ case: "You summarised the PR list every morning.",+ }),+ build({ id: "k1", state: "kept", title: "Mail humanizer", artefact: { type: "skill", id: "humanizer" } }),+ build({ id: "u1", kind: "code", state: "undone", title: "Fix the flaky test" }),+];++const STATUS: SelfBuildStatus = {+ enabled: true,+ paused: false,+ silent: false,+ autonomy: { memory: "trial", skill: "suggest", routine: "suggest", agent: "suggest", code: "suggest" },+ builders: ["skill", "routine", "memory"],+};++interface Call {+ url: string;+ method: string;+ body: unknown;+}++function installFetch(status: SelfBuildStatus = STATUS, kill = false) {+ const calls: Call[] = [];+ const routes: Record<string, (body: unknown) => unknown> = {+ "GET /api/self-build": () => ({ builds: BUILDS, status }),+ "GET /api/self-build/digest?hours=24": () => ({+ since_ms: NOW - 86_400_000,+ until_ms: NOW,+ counts: { proposed: 2, trial: 1 },+ live: 2,+ items: [],+ }),+ "GET /api/self-build/settings": () => ({+ settings: { trial_days: 14, trial_uses: 10 },+ levels: ["off", "suggest", "trial", "full"],+ bounds: {},+ }),+ "GET /api/self-build/provenance": () => ({+ items: { "skill:humanizer": { build_id: "k1", type: "skill", id: "humanizer", state: "kept", title: "Mail humanizer" } },+ }),+ "GET /api/self-build/t1": () => ({+ build: BUILDS[2],+ history: [+ { ts_ms: NOW - 5 * 86_400_000, from: "", to: "building", note: "" },+ { ts_ms: NOW - 4 * 86_400_000, from: "building", to: "proving", note: "built" },+ { ts_ms: NOW - 3 * 86_400_000, from: "proving", to: "trial", note: "proved" },+ ],+ cost: { tokens: 1200, usd: 0 },+ }),+ "GET /api/society/status": () => ({ kill_switch: kill }),+ "POST /api/self-build/p1/accept": () => ({ build: { ...BUILDS[0], state: "building" } }),+ "POST /api/self-build/p2/undo": () => ({ build: { ...BUILDS[1], state: "rejected" } }),+ "POST /api/self-build/t1/keep": () => ({ build: { ...BUILDS[2], state: "kept" } }),+ "POST /api/self-build/t1/undo": () => ({ build: { ...BUILDS[2], state: "undone" } }),+ "POST /api/self-build/pause": (body) => ({ ...status, paused: (body as { paused: boolean }).paused }),+ "POST /api/society/kill-switch": () => ({ engaged: true }),+ };+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;+ calls.push({ url, method, body });+ const handler = routes[`${method} ${url}`];+ if (!handler) return { ok: false, status: 404, json: async () => ({ detail: "nope" }) } as Response;+ const payload = handler(body);+ return { ok: true, status: 200, json: async () => payload } as Response;+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ return calls;+}++function renderWith(node: React.ReactNode) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={client}>{node}</QueryClientProvider>);+}++describe("SelfBuildView", () => {+ beforeEach(async () => {+ setUiLanguage("en");+ await loadLocaleChunk("self_build");+ });+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it("puts every build on the shelf of what it asks of the person", async () => {+ installFetch();+ renderWith(<SelfBuildView />);+ const waiting = await screen.findByTestId("shelf-waiting");+ expect(within(waiting).getAllByTestId("build-row").map((r) => r.dataset.buildId)).toEqual(["p1", "p2"]);+ expect(within(screen.getByTestId("shelf-trial")).getByText("A standup digest")).toBeTruthy();+ expect(within(screen.getByTestId("shelf-kept")).getByText("Mail humanizer")).toBeTruthy();+ // The past shelf is folded until asked for.+ const past = screen.getByTestId("shelf-past");+ expect(within(past).queryByTestId("build-row")).toBeNull();+ fireEvent.click(within(past).getByRole("button", { name: /show 1/i }));+ expect(within(past).getByText("Fix the flaky test")).toBeTruthy();+ // The digest reads as one line.+ expect(screen.getByTestId("self-build-digest").textContent).toMatch(/2 proposed/);+ expect(screen.getByTestId("self-build-digest").textContent).toMatch(/2 live now/);+ });++ it("builds a proposal or turns it down in one click; a kind without a builder cannot be built", async () => {+ const calls = installFetch();+ renderWith(<SelfBuildView />);+ const first = (await screen.findAllByTestId("build-row"))[0];+ fireEvent.click(within(first).getByTestId("build-accept"));+ await waitFor(() => expect(calls.some((c) => c.method === "POST" && c.url === "/api/self-build/p1/accept")).toBe(true));++ const agentRow = screen.getAllByTestId("build-row").find((r) => r.dataset.buildId === "p2")!;+ expect((within(agentRow).getByTestId("build-accept") as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(within(agentRow).getByTestId("build-undo"));+ await waitFor(() => expect(calls.some((c) => c.url === "/api/self-build/p2/undo")).toBe(true));+ });++ it("opens a build into its case file and keeps or undoes a trial", async () => {+ const calls = installFetch();+ renderWith(<SelfBuildView />);+ const row = (await screen.findAllByTestId("build-row")).find((r) => r.dataset.buildId === "t1")!;+ fireEvent.click(row);+ const detail = await screen.findByTestId("build-detail");+ expect(within(detail).getByText("You summarised the PR list every morning.")).toBeTruthy();+ expect(within(detail).getByText("Passed")).toBeTruthy();+ expect(within(detail).getByText(/Day 3 of 14 · 4 of 10 uses/)).toBeTruthy();+ expect(within(detail).getByTestId("build-rail").dataset.reached).toBe("3");+ await waitFor(() => expect(within(detail).getAllByText(/Trial|On trial/).length).toBeGreaterThan(0));+ await waitFor(() => expect(within(detail).getByTestId("build-history").children.length).toBe(3));+ fireEvent.click(within(detail).getByTestId("build-keep"));+ await waitFor(() => expect(calls.some((c) => c.url === "/api/self-build/t1/keep")).toBe(true));+ });++ it("pauses the loop, and stops every agent only after a confirm", async () => {+ const calls = installFetch();+ renderWith(<SelfBuildView />);+ fireEvent.click(await screen.findByTestId("self-build-pause"));+ await waitFor(() =>+ expect(calls.find((c) => c.url === "/api/self-build/pause")?.body).toEqual({ paused: true }),+ );+ fireEvent.click(screen.getByTestId("society-stop-all"));+ expect(calls.some((c) => c.url === "/api/society/kill-switch")).toBe(false);+ fireEvent.click(screen.getByTestId("stop-all-ok"));+ await waitFor(() => expect(calls.some((c) => c.method === "POST" && c.url === "/api/society/kill-switch")).toBe(true));+ });++ it("says plainly when building is paused, quiet or every agent is stopped", async () => {+ installFetch({ ...STATUS, paused: true }, true);+ renderWith(<SelfBuildView />);+ expect(await screen.findByTestId("note-paused")).toBeTruthy();+ expect(await screen.findByTestId("note-stopped")).toBeTruthy();+ expect(screen.queryByTestId("society-stop-all")).toBeNull();+ // Accepting would start a build, so it waits while building is paused.+ const first = (await screen.findAllByTestId("build-row"))[0];+ expect((within(first).getByTestId("build-accept") as HTMLButtonElement).disabled).toBe(true);+ });++ it("opens on the build a badge asked for", async () => {+ installFetch();+ useSelfBuildFocus.getState().request("t1");+ renderWith(<SelfBuildView />);+ expect((await screen.findByTestId("build-detail")).dataset.buildId).toBe("t1");+ });+});++describe("BuiltByBadge", () => {+ beforeEach(() => setUiLanguage("en"));+ afterEach(() => cleanup());++ it("marks only what a build made, and links to that build", async () => {+ installFetch();+ renderWith(+ <>+ <BuiltByBadge type="skill" id="humanizer" />+ <BuiltByBadge type="skill" id="my-own-skill" />+ </>,+ );+ const badge = await screen.findByTestId("built-by-badge");+ expect(screen.getAllByTestId("built-by-badge")).toHaveLength(1);+ fireEvent.click(badge);+ expect(useEventStore.getState().activeSection).toBe("self-build");+ expect(useSelfBuildFocus.getState().buildId).toBe("k1");+ });+});diff --git a/dodaios/ui/web/frontend/src/views/SelfBuildView.tsx b/dodaios/ui/web/frontend/src/views/SelfBuildView.tsxnew file mode 100644index 0000000000..c372245e13--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/SelfBuildView.tsx@@ -0,0 +1,635 @@+/**+ * "Built for you" — everything the self-building loop made on its own.+ *+ * The person is no longer asked about every build, so this page is the+ * counterweight: every build is on it with the one sentence it exists for,+ * where it stands, and the action that applies to it. The page is organised+ * by what each build asks of the person — waiting for a yes, on trial, being+ * built, kept, gone — not as a table of rows. A build opens into its case file+ * on the right (`BuildDetail`).+ *+ * It never interrupts: no toast, no sound, no voice. New builds show up here,+ * as a quiet count on the nav row, and in the one-line digest at the top.+ * Live through `SelfBuildChanged` (hooks/useWebSocket.ts). docs/self-build.md.+ */+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { ChevronDown, Loader2, Pause, Play, Settings2, OctagonX } from "lucide-react";+import { fill, useLocaleChunk, useT } from "@/i18n";+import { useRunLocale } from "@/components/runs/format";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { useSettingsJump } from "@/store/settingsJump";+import { useSelfBuildFocus } from "@/store/selfBuildFocus";+import {+ useBuildAction,+ useSelfBuildDigest,+ useSelfBuildList,+ useSelfBuildPause,+ useSelfBuildSettings,+ useSetSocietyKillSwitch,+ useSocietyKillSwitch,+ type BuildAction,+} from "@/hooks/useSelfBuild";+import {+ SelfBuildApiError,+ reachedStep,+ shelfOf,+ trialProgress,+ type Build,+ type BuildDigest,+ type SelfBuildStatus,+ type Shelf,+} from "@/lib/selfBuildApi";+import { BuildActions } from "./selfBuild/BuildActions";+import { BuildDetail } from "./selfBuild/BuildDetail";+import { KindIcon, LifecycleRail, relativeTime } from "./selfBuild/shared";++const SHELVES: readonly Shelf[] = ["waiting", "trial", "working", "kept", "past"];++export function SelfBuildView() {+ const ready = useLocaleChunk("self_build");+ const t = useT();+ const list = useSelfBuildList();+ const digest = useSelfBuildDigest(24);+ const settings = useSelfBuildSettings();+ const act = useBuildAction();+ const [selectedId, setSelectedId] = useState<string | null>(() => useSelfBuildFocus.getState().take());+ const [error, setError] = useState<string | null>(null);+ const focusRequest = useSelfBuildFocus((s) => s.buildId);++ // A badge elsewhere asked for a build while this view was already open.+ useEffect(() => {+ if (focusRequest) setSelectedId(useSelfBuildFocus.getState().take());+ }, [focusRequest]);++ const builds = list.data?.builds ?? [];+ const status = list.data?.status;+ const selected = builds.find((b) => b.id === selectedId) ?? null;+ const limits = settings.data?.settings;+ // Accepting starts a build, so it waits while building is paused.+ const canBuild = (build: Build) => Boolean(status?.builders.includes(build.kind)) && !status?.paused;+ const blockedTitle = (build: Build) =>+ status?.paused ? t("self_build.notes.paused") : !status?.builders.includes(build.kind) ? t("self_build.no_builder") : undefined;++ const onAction = (build: Build, action: BuildAction) => {+ setError(null);+ act.mutate(+ { id: build.id, action },+ { onError: (err) => setError(fill(t("self_build.error.action"), { detail: err.message })) },+ );+ };++ if (!ready) return <Centered><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden /></Centered>;++ const unavailable = list.error instanceof SelfBuildApiError && list.error.status === 503;++ return (+ <div data-testid="self-build-view" className="flex h-full min-h-0 flex-col overflow-y-auto">+ <div className="mx-auto flex w-full max-w-[1240px] flex-1 flex-col px-6 pb-16 pt-10 sm:px-10">+ <Header status={status} />+ <Notes status={status} />+ <DigestLine digest={digest.data} />+ {error && (+ <p role="alert" className="mt-4 rounded-lg border border-destructive/40 px-3 py-2 text-sm text-destructive">+ {error}+ </p>+ )}++ {list.isPending ? (+ <Centered><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-label={t("self_build.loading")} /></Centered>+ ) : unavailable || list.error ? (+ <p role="alert" className="mt-10 text-base text-muted-foreground">{t("self_build.error.unavailable")}</p>+ ) : builds.length === 0 ? (+ <EmptyLoop />+ ) : (+ <div className="mt-8 grid min-h-0 flex-1 grid-cols-1 items-start gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(360px,440px)]">+ <div className="min-w-0 space-y-9" data-testid="self-build-shelves">+ {SHELVES.map((shelf) => (+ <ShelfSection+ key={shelf}+ shelf={shelf}+ builds={builds.filter((b) => shelfOf(b) === shelf)}+ selectedId={selectedId}+ onSelect={(b) => setSelectedId(b.id === selectedId ? null : b.id)}+ canBuild={canBuild}+ blockedTitle={blockedTitle}+ busyId={act.isPending ? act.variables?.id ?? null : null}+ onAction={onAction}+ limits={limits}+ />+ ))}+ </div>+ <aside className="min-w-0 lg:sticky lg:top-6 lg:max-h-[calc(100vh-7rem)] lg:min-h-[420px] lg:[&>article]:max-h-[calc(100vh-7rem)]">+ {selected ? (+ <BuildDetail+ key={selected.id}+ build={selected}+ limits={limits}+ canBuild={canBuild(selected)}+ blockedTitle={blockedTitle(selected)}+ busy={act.isPending && act.variables?.id === selected.id}+ onAction={onAction}+ onClose={() => setSelectedId(null)}+ />+ ) : (+ <PickHint />+ )}+ </aside>+ </div>+ )}+ </div>+ </div>+ );+}++// ------------------------------------------------------------------ header++function Header({ status }: { status: SelfBuildStatus | undefined }) {+ const t = useT();+ const pause = useSelfBuildPause();+ const setActive = useEventStore((s) => s.setActiveSection);+ const [confirmStop, setConfirmStop] = useState(false);+ const kill = useSocietyKillSwitch();+ const setKill = useSetSocietyKillSwitch();+ const paused = Boolean(status?.paused);+ const tone = !status ? "idle" : !status.enabled ? "off" : paused ? "paused" : status.silent ? "silent" : "running";++ const openSettings = () => {+ useSettingsJump.getState().request("self-build");+ setActive("settings");+ };++ return (+ <header className="flex flex-wrap items-end gap-x-6 gap-y-4">+ <div className="min-w-0 flex-1">+ <h1 className="font-display text-2xl font-semibold text-foreground-strong">{t("self_build.title")}</h1>+ <p className="mt-1 max-w-xl text-base text-muted-foreground">{t("self_build.subtitle")}</p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {status && (+ <span+ data-testid="self-build-status"+ data-tone={tone}+ className="mr-1 inline-flex items-center gap-2 text-sm text-muted-foreground"+ >+ <span+ aria-hidden+ className={cn(+ "h-2 w-2 rounded-full",+ tone === "running" && "bg-success",+ tone === "paused" && "bg-warning",+ tone === "silent" && "bg-info",+ tone === "off" && "bg-border-strong",+ )}+ />+ {t(`self_build.status.${tone === "idle" ? "running" : tone}`)}+ </span>+ )}+ {status?.enabled && (+ <button+ type="button"+ data-testid="self-build-pause"+ aria-pressed={paused}+ title={t("self_build.pause_hint")}+ disabled={pause.isPending}+ onClick={() => pause.mutate(!paused)}+ className={cn(+ "inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ paused ? "bg-primary text-primary-foreground hover:bg-primary/90" : "border border-border-strong text-foreground hover:bg-secondary",+ )}+ >+ {paused ? <Play className="h-3.5 w-3.5" aria-hidden /> : <Pause className="h-3.5 w-3.5" aria-hidden />}+ {paused ? t("self_build.resume") : t("self_build.pause")}+ </button>+ )}+ <button+ type="button"+ onClick={openSettings}+ aria-label={t("self_build.settings")}+ title={t("self_build.settings")}+ data-testid="self-build-settings"+ className="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Settings2 className="h-4 w-4" aria-hidden />+ </button>+ {kill.data !== true && (+ <button+ type="button"+ data-testid="society-stop-all"+ title={t("self_build.stop_all_hint")}+ onClick={() => setConfirmStop(true)}+ className="inline-flex h-8 items-center gap-1.5 rounded-md px-2.5 text-sm text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <OctagonX className="h-4 w-4" aria-hidden />+ {t("self_build.stop_all")}+ </button>+ )}+ </div>+ {confirmStop && (+ <ConfirmStop+ busy={setKill.isPending}+ onCancel={() => setConfirmStop(false)}+ onConfirm={() => setKill.mutate(true, { onSettled: () => setConfirmStop(false) })}+ />+ )}+ </header>+ );+}++function Notes({ status }: { status: SelfBuildStatus | undefined }) {+ const t = useT();+ const kill = useSocietyKillSwitch();+ const setKill = useSetSocietyKillSwitch();+ const setActive = useEventStore((s) => s.setActiveSection);+ const notes: ReactNode[] = [];+ if (kill.data === true) {+ notes.push(+ <Note key="stopped" tone="destructive" testId="note-stopped"+ action={{ label: t("self_build.notes.release"), onClick: () => setKill.mutate(false), busy: setKill.isPending }}>+ {t("self_build.notes.stopped")}+ </Note>,+ );+ }+ if (status && !status.enabled) {+ notes.push(+ <Note key="off" tone="muted" testId="note-off"+ action={{+ label: t("self_build.notes.turn_on"),+ onClick: () => {+ useSettingsJump.getState().request("self-build");+ setActive("settings");+ },+ }}>+ {t("self_build.notes.off")}+ </Note>,+ );+ } else if (status?.paused) {+ notes.push(+ // The resume button sits in the header right above; the note only says why.+ <Note key="paused" tone="warning" testId="note-paused">+ {t("self_build.notes.paused")}+ </Note>,+ );+ } else if (status?.silent) {+ notes.push(<Note key="silent" tone="muted" testId="note-silent">{t("self_build.notes.silent")}</Note>);+ }+ if (!notes.length) return null;+ return <div className="mt-6 space-y-2">{notes}</div>;+}++function Note({+ tone,+ children,+ action,+ testId,+}: {+ tone: "muted" | "warning" | "destructive";+ children: ReactNode;+ action?: { label: string; onClick: () => void; busy?: boolean };+ testId: string;+}) {+ return (+ <div+ data-testid={testId}+ className={cn(+ "flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg border px-4 py-2.5 text-sm",+ tone === "muted" && "border-border text-muted-foreground",+ tone === "warning" && "border-warning/40 text-foreground",+ tone === "destructive" && "border-destructive/40 text-foreground",+ )}+ >+ <span+ aria-hidden+ className={cn(+ "h-1.5 w-1.5 shrink-0 rounded-full",+ tone === "muted" && "bg-border-strong",+ tone === "warning" && "bg-warning",+ tone === "destructive" && "bg-destructive",+ )}+ />+ <span className="min-w-0 flex-1">{children}</span>+ {action && (+ <button+ type="button"+ onClick={action.onClick}+ disabled={action.busy}+ className="shrink-0 rounded-md px-2 py-1 text-sm font-medium text-foreground underline-offset-4 hover:underline disabled:opacity-50"+ >+ {action.label}+ </button>+ )}+ </div>+ );+}++// ------------------------------------------------------------------ digest++/**+ * The daily glance as one sentence-like line, not a row of stat tiles: what+ * changed since yesterday, and how much is live now.+ */+function DigestLine({ digest }: { digest: BuildDigest | undefined }) {+ const t = useT();+ if (!digest) return null;+ const counts = digest.counts;+ const built = (counts.trial ?? 0) + (counts.building ?? 0) + (counts.proving ?? 0);+ const parts: [string, number][] = [+ ["built", built],+ ["proposed", counts.proposed ?? 0],+ ["kept", counts.kept ?? 0],+ ["archived", counts.archived ?? 0],+ ["undone", counts.undone ?? 0],+ ];+ const shown = parts.filter(([, n]) => n > 0);+ return (+ <p data-testid="self-build-digest" className="mt-6 flex flex-wrap items-baseline gap-x-3 gap-y-1 border-y border-border py-3 text-base">+ <span className="text-sm font-medium text-muted-foreground">{t("self_build.digest.label")}</span>+ {shown.length === 0 ? (+ <span className="text-muted-foreground">{t("self_build.digest.nothing")}</span>+ ) : (+ shown.map(([key, n], index) => (+ <span key={key} className="text-foreground">+ {index > 0 && <span aria-hidden className="mr-3 text-border-strong">·</span>}+ <Count text={fill(t(`self_build.digest.${key}`), { count: n })} n={n} />+ </span>+ ))+ )}+ <span className="ml-auto text-sm text-muted-foreground">+ <Count text={fill(t("self_build.digest.live"), { count: digest.live })} n={digest.live} />+ </span>+ </p>+ );+}++/** Puts the number of a "{count} built" string in strong ink, wherever the locale placed it. */+function Count({ text, n }: { text: string; n: number }) {+ const digits = String(n);+ const at = text.indexOf(digits);+ if (at < 0) return <>{text}</>;+ return (+ <>+ {text.slice(0, at)}+ <span className="font-semibold tabular-nums text-foreground-strong">{digits}</span>+ {text.slice(at + digits.length)}+ </>+ );+}++// ------------------------------------------------------------------ shelves++function ShelfSection({+ shelf,+ builds,+ selectedId,+ onSelect,+ canBuild,+ blockedTitle,+ busyId,+ onAction,+ limits,+}: {+ shelf: Shelf;+ builds: Build[];+ selectedId: string | null;+ onSelect: (build: Build) => void;+ canBuild: (build: Build) => boolean;+ blockedTitle: (build: Build) => string | undefined;+ busyId: string | null;+ onAction: (build: Build, action: BuildAction) => void;+ limits: { trial_days: number; trial_uses: number } | undefined;+}) {+ const t = useT();+ const collapsible = shelf === "past";+ const [open, setOpen] = useState(!collapsible);+ const holdsSelection = builds.some((b) => b.id === selectedId);+ if (!builds.length) return null;+ const expanded = open || holdsSelection;+ return (+ <section data-testid={`shelf-${shelf}`} aria-labelledby={`shelf-${shelf}-title`}>+ <div className="mb-3 flex items-baseline gap-3">+ <h2 id={`shelf-${shelf}-title`} className="text-base font-semibold text-foreground-strong">+ {t(`self_build.shelf.${shelf}`)}+ <span className="ml-2 font-normal tabular-nums text-muted-foreground">{builds.length}</span>+ </h2>+ <span className="truncate text-sm text-muted-foreground">{t(`self_build.shelf.${shelf}_hint`)}</span>+ {collapsible && (+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={expanded}+ className="ml-auto inline-flex shrink-0 items-center gap-1 text-sm text-muted-foreground hover:text-foreground"+ >+ {expanded ? t("self_build.hide_past") : fill(t("self_build.show_past"), { count: builds.length })}+ <ChevronDown className={cn("h-3.5 w-3.5 transition-transform", expanded && "rotate-180")} aria-hidden />+ </button>+ )}+ </div>+ {expanded && (+ <ul className="space-y-2">+ {builds.map((build) => (+ <BuildRow+ key={build.id}+ build={build}+ selected={build.id === selectedId}+ onSelect={() => onSelect(build)}+ canBuild={canBuild(build)}+ blockedTitle={blockedTitle(build)}+ busy={busyId === build.id}+ onAction={onAction}+ limits={limits}+ />+ ))}+ </ul>+ )}+ </section>+ );+}++function BuildRow({+ build,+ selected,+ onSelect,+ canBuild,+ blockedTitle,+ busy,+ onAction,+ limits,+}: {+ build: Build;+ selected: boolean;+ onSelect: () => void;+ canBuild: boolean;+ blockedTitle?: string;+ busy: boolean;+ onAction: (build: Build, action: BuildAction) => void;+ limits: { trial_days: number; trial_uses: number } | undefined;+}) {+ const t = useT();+ const locale = useRunLocale();+ const trial = trialProgress(build, limits);+ const quiet = shelfOf(build) === "past";+ const ref = useRef<HTMLLIElement>(null);+ useEffect(() => {+ if (selected) ref.current?.scrollIntoView?.({ block: "nearest" });+ }, [selected]);+ const meta = useMemo(() => {+ const bits = [t(`self_build.kind.${build.kind}`)];+ if (quiet) bits.push(t(`self_build.state.${build.state}`));+ if (build.evidence.length > 1) bits.push(fill(t("self_build.seen"), { count: build.evidence.length }));+ bits.push(relativeTime(build.updated_ms, locale));+ return bits.join(" · ");+ }, [build, quiet, t, locale]);+ return (+ <li ref={ref}>+ <div+ role="button"+ tabIndex={0}+ data-testid="build-row"+ data-build-id={build.id}+ data-state={build.state}+ aria-pressed={selected}+ onClick={onSelect}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onSelect();+ }+ }}+ className={cn(+ "group flex cursor-pointer items-start gap-3 rounded-lg border px-4 py-3 transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "border-border-strong bg-secondary" : "border-border bg-card hover:border-border-strong",+ quiet && !selected && "bg-transparent",+ )}+ >+ <span className={cn("mt-0.5", quiet ? "text-muted-foreground" : "text-foreground")}>+ <KindIcon kind={build.kind} />+ </span>+ <div className="min-w-0 flex-1">+ <p className={cn("line-clamp-2 text-[15px] leading-snug", quiet ? "text-muted-foreground" : "text-foreground-strong")}>+ {build.title}+ </p>+ <p className="mt-1 truncate text-sm text-muted-foreground">{meta}</p>+ {trial && (+ <div className="mt-2 flex items-center gap-3">+ <div className="h-1 w-32 overflow-hidden rounded-full bg-secondary" aria-hidden>+ <div className="h-full rounded-full bg-accent" style={{ width: `${Math.round(trial.share * 100)}%` }} />+ </div>+ <span className="truncate text-xs tabular-nums text-muted-foreground">+ {fill(t("self_build.trial_progress"), {+ days: trial.days,+ dayLimit: trial.dayLimit,+ uses: trial.uses,+ useLimit: trial.useLimit,+ })}+ </span>+ </div>+ )}+ </div>+ <div className="flex shrink-0 flex-col items-end gap-2.5">+ <LifecycleRail state={build.state} reached={reachedStep(build)} compact />+ {(build.state === "proposed" || build.state === "trial") && (+ <BuildActions build={build} canBuild={canBuild} blockedTitle={blockedTitle} busy={busy} onAction={onAction} />+ )}+ </div>+ </div>+ </li>+ );+}++// ------------------------------------------------------------------ calm states++function PickHint() {+ const t = useT();+ return (+ <div className="rounded-xl border border-dashed border-border px-6 py-10 text-center">+ <p className="mx-auto max-w-xs text-sm text-muted-foreground">{t("self_build.detail.select")}</p>+ <LoopLine className="mt-6 justify-center" />+ </div>+ );+}++const LOOP = ["notice", "decide", "build", "check", "trial", "keep"] as const;++function LoopLine({ className }: { className?: string }) {+ const t = useT();+ return (+ <ol className={cn("flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-muted-foreground", className)}>+ {LOOP.map((step, index) => (+ <li key={step} className="flex items-center gap-2">+ {index > 0 && <span aria-hidden className="text-border-strong">→</span>}+ <span>{t(`self_build.empty.loop.${step}`)}</span>+ </li>+ ))}+ </ol>+ );+}++function EmptyLoop() {+ const t = useT();+ return (+ <section data-testid="self-build-empty" className="mt-16 max-w-2xl">+ <h2 className="font-display text-xl text-foreground-strong">{t("self_build.empty.title")}</h2>+ <p className="mt-2 text-base leading-relaxed text-muted-foreground">{t("self_build.empty.body")}</p>+ <LoopLine className="mt-6" />+ </section>+ );+}++function Centered({ children }: { children: ReactNode }) {+ return <div className="flex flex-1 items-center justify-center py-24">{children}</div>;+}++function ConfirmStop({ busy, onCancel, onConfirm }: { busy: boolean; onCancel: () => void; onConfirm: () => void }) {+ const t = useT();+ const cancel = useRef<HTMLButtonElement>(null);+ useEffect(() => cancel.current?.focus(), []);+ return (+ <div+ role="presentation"+ className="fixed inset-0 z-[110] flex items-center justify-center bg-background/60 p-4"+ onPointerDown={(event) => {+ if (event.target === event.currentTarget && !busy) onCancel();+ }}+ onKeyDown={(event) => {+ if (event.key === "Escape" && !busy) onCancel();+ }}+ >+ <section+ role="alertdialog"+ aria-modal="true"+ aria-labelledby="stop-all-title"+ data-testid="stop-all-confirm"+ className="w-full max-w-sm rounded-xl border border-border bg-popover p-5 text-popover-foreground shadow-float"+ >+ <h2 id="stop-all-title" className="text-base font-semibold text-foreground-strong">+ {t("self_build.stop_confirm_title")}+ </h2>+ <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{t("self_build.stop_confirm_body")}</p>+ <div className="mt-5 flex justify-end gap-2">+ <button+ ref={cancel}+ type="button"+ disabled={busy}+ onClick={onCancel}+ className="h-8 rounded-md px-3 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("self_build.cancel")}+ </button>+ <button+ type="button"+ data-testid="stop-all-ok"+ disabled={busy}+ onClick={onConfirm}+ className="inline-flex h-8 items-center gap-1.5 rounded-md bg-destructive px-3 text-sm font-medium text-destructive-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"+ >+ {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />}+ {t("self_build.stop_all")}+ </button>+ </div>+ </section>+ </div>+ );+}++export default SelfBuildView;diff --git a/dodaios/ui/web/frontend/src/views/SettingsView.tsx b/dodaios/ui/web/frontend/src/views/SettingsView.tsxindex cce7ee0491..b50ff9560b 100644--- a/dodaios/ui/web/frontend/src/views/SettingsView.tsx+++ b/dodaios/ui/web/frontend/src/views/SettingsView.tsx@@ -10,6 +10,7 @@ import { RealtimeVoiceGroup } from "@/views/settings/RealtimeVoiceGroup";import { VolumeGroup } from "@/views/settings/VolumeGroup";import { AudioDevicesGroup } from "@/views/settings/AudioDevicesGroup";import { SystemPromptGroup } from "@/views/settings/SystemPromptGroup";+import { SelfBuildGroup } from "@/views/settings/SelfBuildGroup";import { SettingsGroupBoundary } from "@/views/settings/SettingsGroupBoundary";import { settingsInputCls } from "@/views/settings/SettingsBlock";import {@@ -136,6 +137,7 @@ const SECTIONS: readonly { id: string; render: () => React.ReactNode }[] = [{ id: "voice", render: () => <VoiceSettingsGroup /> },{ id: "wake-word", render: () => <WakeWordPanel /> },{ id: "system-prompt", render: () => <SystemPromptGroup /> },+ { id: "self-build", render: () => <SelfBuildGroup /> },{ id: "music", render: () => <MusicGroup /> },{ id: "overlay-taskbar", render: () => <OverlayTaskbarGroup /> },];diff --git a/dodaios/ui/web/frontend/src/views/SkillsView.tsx b/dodaios/ui/web/frontend/src/views/SkillsView.tsxindex 120cf64cfc..ca8e8bd684 100644--- a/dodaios/ui/web/frontend/src/views/SkillsView.tsx+++ b/dodaios/ui/web/frontend/src/views/SkillsView.tsx@@ -37,6 +37,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";import { Button } from "@/components/ui/button";import { Badge } from "@/components/ui/badge";import { MarketplaceBadge } from "@/components/MarketplaceBadge";+import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";import { Switch } from "@/components/ui/switch";import { BrandedSelect } from "@/components/ui/select";import {@@ -633,6 +634,7 @@ function SkillRow({{skill.origin?.source === "marketplace" && (<MarketplaceBadge compact publisher={skill.origin.publisher} />)}+ <BuiltByBadge compact type="skill" id={skill.name} />{skill.triggers.map((tr, i) => {const Icon = TRIGGER_ICON[tr.type];return <Icon key={i} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-label={tr.type} />;@@ -1059,6 +1061,7 @@ function SkillDetailPage({{data.origin?.source === "marketplace" && (<MarketplaceBadge compact publisher={data.origin.publisher} />)}+ <BuiltByBadge type="skill" id={data.name} /></span>}actions={diff --git a/dodaios/ui/web/frontend/src/views/selfBuild/BuildActions.tsx b/dodaios/ui/web/frontend/src/views/selfBuild/BuildActions.tsxnew file mode 100644index 0000000000..49421fe80f--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/selfBuild/BuildActions.tsx@@ -0,0 +1,108 @@+/**+ * The actions that apply to a build right now, and nothing else.+ *+ * Proposed: build it / not this. On trial: keep / undo. Kept: undo. Archived:+ * restore / undo. Undo is one click with no "are you sure": the promise of a+ * trial is that taking it back costs nothing.+ */+import { Loader2 } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import type { BuildAction } from "@/hooks/useSelfBuild";+import type { Build } from "@/lib/selfBuildApi";++export type ActionHandler = (build: Build, action: BuildAction) => void;++interface Choice {+ action: BuildAction;+ label: string;+ primary: boolean;+ disabled?: boolean;+ title?: string;+}++export function choicesFor(+ build: Build,+ canBuild: boolean,+ t: (key: string) => string,+ blockedTitle?: string,+): Choice[] {+ switch (build.state) {+ case "proposed":+ return [+ {+ action: "accept",+ label: t("self_build.action.accept"),+ primary: true,+ disabled: !canBuild,+ title: canBuild ? undefined : blockedTitle ?? t("self_build.no_builder"),+ },+ { action: "undo", label: t("self_build.action.reject"), primary: false },+ ];+ case "trial":+ return [+ { action: "keep", label: t("self_build.action.keep"), primary: true },+ { action: "undo", label: t("self_build.action.undo"), primary: false },+ ];+ case "kept":+ return [{ action: "undo", label: t("self_build.action.undo"), primary: false }];+ case "archived":+ return [+ { action: "keep", label: t("self_build.action.restore"), primary: false },+ { action: "undo", label: t("self_build.action.undo"), primary: false },+ ];+ case "building":+ case "proving":+ return [{ action: "undo", label: t("self_build.action.undo"), primary: false }];+ default:+ return [];+ }+}++export function BuildActions({+ build,+ canBuild,+ blockedTitle,+ busy,+ onAction,+ size = "sm",+}: {+ build: Build;+ canBuild: boolean;+ blockedTitle?: string;+ busy: boolean;+ onAction: ActionHandler;+ size?: "sm" | "default";+}) {+ const t = useT();+ const choices = choicesFor(build, canBuild, t, blockedTitle);+ if (!choices.length) return null;+ return (+ <div className="flex shrink-0 items-center gap-1.5" data-testid="build-actions">+ {choices.map((choice) => (+ <button+ key={choice.action}+ type="button"+ data-testid={`build-${choice.action}`}+ disabled={busy || choice.disabled}+ title={choice.title}+ onClick={(event) => {+ event.stopPropagation();+ onAction(build, choice.action);+ }}+ className={cn(+ "inline-flex items-center justify-center gap-1.5 rounded-md font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",+ size === "sm" ? "h-7 px-2.5 text-sm" : "h-8 px-3 text-sm",+ choice.primary+ ? "bg-primary text-primary-foreground hover:bg-primary/90"+ : "border border-border-strong text-foreground hover:bg-secondary",+ )}+ >+ {busy && choice.primary && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />}+ {choice.label}+ </button>+ ))}+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/views/selfBuild/BuildDetail.tsx b/dodaios/ui/web/frontend/src/views/selfBuild/BuildDetail.tsxnew file mode 100644index 0000000000..8a59225394--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/selfBuild/BuildDetail.tsx@@ -0,0 +1,265 @@+/**+ * One build, read top to bottom as its own case file: the sentence it exists+ * for, where it stands on its path, why it was built, what it noticed, how it+ * was checked, what it made, how it was used, what it cost, and every move it+ * made — with the one or two actions that apply to it right now.+ */+import type { ReactNode } from "react";+import { ExternalLink, Loader2, X } from "lucide-react";+import { fill, useT } from "@/i18n";+import { useRunLocale, fmtInt } from "@/components/runs/format";+import { cn } from "@/lib/utils";+import { useSelfBuildDetail } from "@/hooks/useSelfBuild";+import { reachedStep, trialProgress, type Build, type BuildOutcome } from "@/lib/selfBuildApi";+import { KindIcon, LifecycleRail, formatUsd, relativeTime } from "./shared";+import { BuildActions, type ActionHandler } from "./BuildActions";++const OUTCOMES: readonly BuildOutcome[] = ["accepted", "used", "corrected", "ignored"];++export function BuildDetail({+ build,+ limits,+ canBuild,+ blockedTitle,+ busy,+ onAction,+ onClose,+}: {+ build: Build;+ limits: { trial_days: number; trial_uses: number } | undefined;+ canBuild: boolean;+ blockedTitle?: string;+ busy: boolean;+ onAction: ActionHandler;+ onClose: () => void;+}) {+ const t = useT();+ const locale = useRunLocale();+ const detail = useSelfBuildDetail(build.id);+ const history = detail.data?.history;+ const cost = detail.data?.cost;+ // The list row may be newer than the detail fetch (a socket event landed).+ const current = detail.data && detail.data.build.updated_ms > build.updated_ms ? detail.data.build : build;+ const reached = reachedStep(current, history);+ const trial = trialProgress(current, limits);+ const railLabels: Record<string, string> = {+ proposed: t("self_build.step.proposed"),+ building: t("self_build.step.building"),+ proving: t("self_build.step.proving"),+ trial: t("self_build.step.trial"),+ kept: t("self_build.step.kept"),+ [`end:${current.state}`]: t(`self_build.state.${current.state}`),+ };+ const proof = current.proof ?? {};+ const hasProof = typeof proof.passed === "boolean";+ const artefact = current.artefact ?? {};+ const outcomes = OUTCOMES.filter((o) => (current.outcomes[o] ?? 0) > 0);++ return (+ <article+ data-testid="build-detail"+ data-build-id={current.id}+ className="flex min-h-0 flex-col rounded-xl border border-border bg-card"+ >+ <header className="border-b border-border px-6 pb-5 pt-5">+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <KindIcon kind={current.kind} />+ <span>{t(`self_build.kind.${current.kind}`)}</span>+ <span aria-hidden>·</span>+ <span>{t(`self_build.state.${current.state}`)}</span>+ <span aria-hidden>·</span>+ <span title={new Date(current.created_ms).toLocaleString(locale)}>+ {t("self_build.detail.opened")} {relativeTime(current.created_ms, locale)}+ </span>+ <button+ type="button"+ onClick={onClose}+ aria-label={t("self_build.detail.close")}+ className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <X className="h-4 w-4" aria-hidden />+ </button>+ </div>+ <h2 className="mt-3 font-display text-xl leading-snug text-foreground-strong">{current.title}</h2>+ <div className="mt-6">+ <LifecycleRail state={current.state} reached={reached} labels={railLabels} />+ </div>+ {trial && (+ <div className="mt-4">+ <div className="h-1 overflow-hidden rounded-full bg-secondary" aria-hidden>+ <div className="h-full rounded-full bg-accent" style={{ width: `${Math.round(trial.share * 100)}%` }} />+ </div>+ <p className="mt-1.5 text-xs tabular-nums text-muted-foreground">+ {fill(t("self_build.trial_progress"), {+ days: trial.days,+ dayLimit: trial.dayLimit,+ uses: trial.uses,+ useLimit: trial.useLimit,+ })}+ </p>+ </div>+ )}+ <div className="mt-5">+ <BuildActions build={current} canBuild={canBuild} blockedTitle={blockedTitle} busy={busy} onAction={onAction} size="default" />+ </div>+ </header>++ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ <dl className="space-y-6">+ {current.case && (+ <Section label={t("self_build.detail.why")}>+ <p className="whitespace-pre-line text-base leading-relaxed text-foreground">{current.case}</p>+ </Section>+ )}++ <Section label={t("self_build.detail.noticed")}>+ {current.evidence.length ? (+ <ul className="space-y-1">+ {current.evidence.map((ref, index) => (+ <li key={`${ref}-${index}`} className="truncate font-mono text-xs text-muted-foreground" title={ref}>+ {ref}+ </li>+ ))}+ </ul>+ ) : (+ <Quiet>{t("self_build.detail.noticed_empty")}</Quiet>+ )}+ </Section>++ <Section label={t("self_build.detail.proof")}>+ {hasProof ? (+ <div className="space-y-1">+ <p className="flex items-center gap-2 text-base text-foreground">+ <span+ aria-hidden+ className={cn("h-2 w-2 rounded-full", proof.passed ? "bg-success" : "bg-destructive")}+ />+ {proof.passed ? t("self_build.detail.proof_passed") : t("self_build.detail.proof_failed")}+ {proof.judge && <span className="text-sm text-muted-foreground">· {proof.judge}</span>}+ </p>+ {proof.detail && <p className="text-sm leading-relaxed text-muted-foreground">{proof.detail}</p>}+ </div>+ ) : (+ <Quiet>{t("self_build.detail.proof_none")}</Quiet>+ )}+ </Section>++ <Section label={t("self_build.detail.made")}>+ {artefact.type && artefact.id ? (+ <p className="flex min-w-0 items-center gap-2 text-base text-foreground">+ <span className="truncate">{artefact.label || artefact.id}</span>+ <span className="shrink-0 text-sm text-muted-foreground">{artefact.type}</span>+ {typeof artefact.url === "string" && /^https?:\/\//.test(artefact.url) && (+ <a+ href={artefact.url}+ target="_blank"+ rel="noreferrer"+ className="inline-flex shrink-0 items-center gap-1 text-sm text-accent hover:underline"+ >+ {t("self_build.detail.open_link")}+ <ExternalLink className="h-3.5 w-3.5" aria-hidden />+ </a>+ )}+ </p>+ ) : (+ <Quiet>{t("self_build.detail.made_none")}</Quiet>+ )}+ </Section>++ <div className="grid grid-cols-2 gap-6">+ <Section label={t("self_build.detail.use")}>+ {current.uses > 0 ? (+ <div className="space-y-0.5">+ <p className="text-base tabular-nums text-foreground">+ {fill(t("self_build.detail.uses"), { count: fmtInt(current.uses, locale) })}+ </p>+ {outcomes.length > 0 && (+ <p className="text-sm text-muted-foreground">+ {outcomes+ .map((o) => `${fmtInt(current.outcomes[o] ?? 0, locale)} ${t(`self_build.outcome.${o}`)}`)+ .join(" · ")}+ </p>+ )}+ {current.last_used_ms > 0 && (+ <p className="text-xs text-muted-foreground">{relativeTime(current.last_used_ms, locale)}</p>+ )}+ </div>+ ) : (+ <Quiet>{t("self_build.detail.unused")}</Quiet>+ )}+ </Section>+ <Section label={t("self_build.detail.cost")}>+ {cost === undefined ? (+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />+ ) : cost.usd > 0 || cost.tokens > 0 ? (+ <div className="space-y-0.5">+ <p className="text-base tabular-nums text-foreground">{formatUsd(cost.usd, locale)}</p>+ <p className="text-sm tabular-nums text-muted-foreground">+ {fill(t("self_build.detail.tokens"), { count: fmtInt(cost.tokens, locale) })}+ </p>+ </div>+ ) : (+ <Quiet>{t("self_build.detail.cost_none")}</Quiet>+ )}+ </Section>+ </div>++ {/* The last move's note explains an ending ("archived: not used+ enough"); on a live build it only repeats the history. */}+ {current.note && ["archived", "undone", "rejected", "failed"].includes(current.state) && (+ <Section label={t("self_build.detail.note")}>+ <p className="text-sm text-muted-foreground">{current.note}</p>+ </Section>+ )}++ <Section label={t("self_build.detail.history")}>+ {history === undefined ? (+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />+ ) : (+ <ol className="relative space-y-3 border-l border-border pl-4" data-testid="build-history">+ {[...history].reverse().map((entry, index) => (+ <li key={`${entry.ts_ms}-${index}`} className="relative">+ <span+ aria-hidden+ className={cn(+ "absolute -left-[21px] top-1.5 h-2 w-2 rounded-full border border-card",+ index === 0 ? "bg-foreground-strong" : "bg-border-strong",+ )}+ />+ <p className="text-sm text-foreground">+ {entry.from ? `${stateLabel(t, entry.from)} → ` : ""}+ <span className="font-medium">{stateLabel(t, entry.to)}</span>+ </p>+ <p className="text-xs text-muted-foreground" title={new Date(entry.ts_ms).toLocaleString(locale)}>+ {relativeTime(entry.ts_ms, locale)}+ {entry.note ? ` · ${entry.note}` : ""}+ </p>+ </li>+ ))}+ </ol>+ )}+ </Section>+ </dl>+ </div>+ </article>+ );+}++function stateLabel(t: (key: string) => string, state: string): string {+ const key = `self_build.state.${state}`;+ const label = t(key);+ return label === key ? state : label;+}++function Section({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div>+ <dt className="mb-1.5 text-sm font-medium text-muted-foreground">{label}</dt>+ <dd>{children}</dd>+ </div>+ );+}++function Quiet({ children }: { children: ReactNode }) {+ return <p className="text-sm text-muted-foreground">{children}</p>;+}diff --git a/dodaios/ui/web/frontend/src/views/selfBuild/shared.tsx b/dodaios/ui/web/frontend/src/views/selfBuild/shared.tsxnew file mode 100644index 0000000000..8fdc09da17--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/selfBuild/shared.tsx@@ -0,0 +1,165 @@+/**+ * Pieces "Built for you" shares between its list and its detail: the glyph+ * per kind, the lifecycle rail, and short relative times.+ */+import { Clock } from "lucide-react";+import { AgentsIcon, CodeIcon, SkillIcon, WikiIcon } from "@/components/icons/sectionIcons";+import { cn } from "@/lib/utils";+import {+ lifecycleSteps,+ type BuildKind,+ type BuildState,+} from "@/lib/selfBuildApi";++const KIND_ICON = {+ memory: WikiIcon,+ skill: SkillIcon,+ routine: Clock,+ agent: AgentsIcon,+ code: CodeIcon,+} as const;++export function KindIcon({ kind, className }: { kind: BuildKind; className?: string }) {+ const Icon = KIND_ICON[kind] ?? SkillIcon;+ return <Icon aria-hidden strokeWidth={1.6} className={cn("h-4 w-4 shrink-0", className)} />;+}++/** The states that end a build off the forward path, and the ink each one carries. */+const END_TONE: Partial<Record<BuildState, string>> = {+ archived: "text-muted-foreground",+ undone: "text-muted-foreground",+ rejected: "text-muted-foreground",+ failed: "text-destructive",+};++/**+ * Where a build stands on the path Noticed → Built → Checked → Trial → Kept.+ *+ * Reached steps are filled, the step the build stands on carries a ring, the+ * rest are hollow. A build that left the path (archived, undone, turned down,+ * failed) keeps its reached steps and ends in a short branch with the end+ * state's name, so "how far did it get before it stopped" stays readable.+ */+export function LifecycleRail({+ state,+ reached,+ labels,+ compact = false,+}: {+ state: BuildState;+ reached: number;+ labels?: Record<string, string>;+ compact?: boolean;+}) {+ const steps = lifecycleSteps();+ const onPath = steps.includes(state);+ const endLabel = !onPath && labels ? labels[`end:${state}`] : undefined;+ if (!compact) {+ // Five equal columns over one track: the filled part of the track runs+ // from the first step to the last one reached.+ const span = steps.length - 1;+ const filled = Math.max(0, Math.min(reached, span)) / span;+ return (+ <div className="flex items-start gap-3" data-testid="build-rail" data-state={state} data-reached={reached}>+ <div className="relative grid min-w-0 flex-1 grid-cols-5">+ <span aria-hidden className="absolute left-[10%] right-[10%] top-[5px] h-px bg-border-strong" />+ <span+ aria-hidden+ className={cn("absolute left-[10%] top-[5px] h-px", onPath ? "bg-foreground-strong" : "bg-muted-foreground")}+ style={{ width: `${filled * 80}%` }}+ />+ {steps.map((step, index) => {+ const done = index <= reached;+ const here = onPath && index === reached;+ const live = here && state !== "kept" && state !== "proposed";+ return (+ <div key={step} className="relative flex min-w-0 flex-col items-center">+ <span+ aria-hidden+ className={cn(+ "block h-[11px] w-[11px] rounded-full border-2 transition-colors",+ done+ ? onPath+ ? "border-foreground-strong bg-foreground-strong"+ : "border-muted-foreground bg-muted-foreground"+ : "border-border-strong bg-card",+ here && "ring-4 ring-accent/25",+ live && "motion-safe:animate-pulse",+ )}+ />+ {labels && (+ <span+ className={cn(+ "mt-2 max-w-full truncate text-xs",+ here ? "font-medium text-foreground-strong" : done ? "text-foreground" : "text-muted-foreground",+ )}+ >+ {labels[step]}+ </span>+ )}+ </div>+ );+ })}+ </div>+ {!onPath && endLabel && (+ <span+ className={cn(+ "-mt-1 shrink-0 rounded-full border border-border px-2 py-0.5 text-xs",+ END_TONE[state] ?? "text-muted-foreground",+ )}+ data-testid="build-rail-end"+ >+ {endLabel}+ </span>+ )}+ </div>+ );+ }+ // The row's mini rail: five dots and four short rules, no labels.+ return (+ <div className="flex items-center gap-1" data-testid="build-rail-mini" data-state={state} data-reached={reached}>+ {steps.map((step, index) => {+ const done = index <= reached;+ return (+ <div key={step} className="flex items-center gap-1">+ <span+ aria-hidden+ className={cn(+ "block h-1.5 w-1.5 rounded-full border",+ done+ ? onPath+ ? "border-foreground-strong bg-foreground-strong"+ : "border-muted-foreground bg-muted-foreground"+ : "border-border-strong bg-transparent",+ )}+ />+ {index < steps.length - 1 && (+ <span aria-hidden className={cn("block h-px w-2", index < reached && onPath ? "bg-foreground-strong" : "bg-border-strong")} />+ )}+ </div>+ );+ })}+ </div>+ );+}++/** "3 hours ago", "yesterday" — short, in the interface language. */+export function relativeTime(ms: number, locale: string, now = Date.now()): string {+ if (!ms) return "";+ const seconds = Math.round((ms - now) / 1000);+ const abs = Math.abs(seconds);+ const format = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });+ if (abs < 60) return format.format(Math.round(seconds), "second");+ if (abs < 3_600) return format.format(Math.round(seconds / 60), "minute");+ if (abs < 86_400) return format.format(Math.round(seconds / 3_600), "hour");+ if (abs < 30 * 86_400) return format.format(Math.round(seconds / 86_400), "day");+ return new Date(ms).toLocaleDateString(locale, { day: "numeric", month: "short", year: "numeric" });+}++export function formatUsd(usd: number, locale: string): string {+ return new Intl.NumberFormat(locale, {+ style: "currency",+ currency: "USD",+ maximumFractionDigits: usd < 1 ? 3 : 2,+ }).format(usd);+}diff --git a/dodaios/ui/web/frontend/src/views/settings/SelfBuildGroup.test.tsx b/dodaios/ui/web/frontend/src/views/settings/SelfBuildGroup.test.tsxnew file mode 100644index 0000000000..27873b1bfa--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/settings/SelfBuildGroup.test.tsx@@ -0,0 +1,87 @@+/**+ * Settings → Self-building: the switch, the level per kind and a cap each+ * write one PUT with only what changed; an out-of-range number is clamped to+ * the range the backend reported.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";++import { SelfBuildGroup } from "@/views/settings/SelfBuildGroup";+import { setUiLanguage } from "@/i18n";++const SETTINGS = {+ enabled: true,+ silent_days: 7,+ memory: "trial",+ skill: "suggest",+ routine: "suggest",+ agent: "suggest",+ code: "suggest",+ trial_days: 14,+ trial_uses: 10,+ max_builds_per_day: 3,+ max_agents_per_week: 1,+ max_open_trials: 5,+ max_code_runs_per_day: 1,+ max_rejections: 2,+};++function installFetch() {+ const puts: unknown[] = [];+ let current = { ...SETTINGS };+ const payload = () => ({+ settings: current,+ levels: ["off", "suggest", "trial", "full"],+ bounds: { max_builds_per_day: { min: 0, max: 50 } },+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url === "/api/self-build/settings" && init?.method === "PUT") {+ const body = JSON.parse(String(init.body));+ puts.push(body);+ current = { ...current, ...body };+ } else if (url !== "/api/self-build/settings") {+ return { ok: false, status: 404, json: async () => ({}) } as Response;+ }+ return { ok: true, status: 200, json: async () => payload() } as Response;+ }) as unknown as typeof fetch;+ return puts;+}++function renderGroup() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(+ <QueryClientProvider client={client}>+ <SelfBuildGroup />+ </QueryClientProvider>,+ );+}++describe("SelfBuildGroup", () => {+ beforeEach(() => setUiLanguage("en"));+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it("writes only what changed", async () => {+ const puts = installFetch();+ renderGroup();+ const skills = await screen.findByTestId("self-build-autonomy-skill");+ fireEvent.click(within(skills).getByRole("radio", { name: "Trial" }));+ await waitFor(() => expect(puts).toEqual([{ skill: "trial" }]));++ fireEvent.click(within(screen.getByTestId("self-build-enabled")).getByRole("switch"));+ await waitFor(() => expect(puts.at(-1)).toEqual({ enabled: false }));+ });++ it("clamps a cap to the range the backend reported", async () => {+ const puts = installFetch();+ renderGroup();+ const field = within(await screen.findByTestId("self-build-limit-max_builds_per_day")).getByRole("spinbutton");+ fireEvent.change(field, { target: { value: "500" } });+ fireEvent.blur(field);+ await waitFor(() => expect(puts).toEqual([{ max_builds_per_day: 50 }]));+ });+});diff --git a/dodaios/ui/web/frontend/src/views/settings/SelfBuildGroup.tsx b/dodaios/ui/web/frontend/src/views/settings/SelfBuildGroup.tsxnew file mode 100644index 0000000000..0881af9eb4--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/settings/SelfBuildGroup.tsx@@ -0,0 +1,194 @@+/**+ * Settings → General → Self-building: `[self_build]` (docs/self-build.md).+ *+ * The master switch, how far the loop may go per kind (off / suggest / trial /+ * full), and the hard caps. Every change is one PUT to+ * `/api/self-build/settings`, written to jarvis.toml and applied at once — the+ * running loop reads the new values on its next decision, no restart.+ */+import { useEffect, useState } from "react";+import { Switch } from "@/components/ui/switch";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import { useSaveSelfBuildSettings, useSelfBuildSettings } from "@/hooks/useSelfBuild";+import {+ BUILD_KINDS,+ type Autonomy,+ type SelfBuildSettings,+ type SelfBuildSettingsPayload,+} from "@/lib/selfBuildApi";+import {+ SettingsCard,+ SettingsLinkButton,+ SettingsNote,+ SettingsRow,+ SettingsSection,+ SettingsSegmented,+} from "@/views/settings/SettingsLayout";++const LEVELS: readonly Autonomy[] = ["off", "suggest", "trial", "full"];++type NumberKey =+ | "silent_days"+ | "trial_days"+ | "trial_uses"+ | "max_builds_per_day"+ | "max_agents_per_week"+ | "max_open_trials"+ | "max_code_runs_per_day"+ | "max_rejections";++const LIMITS: readonly NumberKey[] = [+ "max_builds_per_day",+ "max_open_trials",+ "max_agents_per_week",+ "max_code_runs_per_day",+ "trial_days",+ "trial_uses",+ "max_rejections",+ "silent_days",+];++export function SelfBuildGroup() {+ const t = useT();+ const query = useSelfBuildSettings();+ const save = useSaveSelfBuildSettings();+ const setActive = useEventStore((s) => s.setActiveSection);+ const [error, setError] = useState<string | null>(null);+ const payload = query.data;++ const apply = (patch: Partial<SelfBuildSettings>) => {+ setError(null);+ save.mutate(patch, {+ onError: (err) => setError(fill(t("settings_view.self_build.save_error"), { detail: err.message })),+ });+ };++ return (+ <SettingsSection+ title={t("settings_view.self_build.title")}+ description={t("settings_view.self_build.description")}+ actions={+ <SettingsLinkButton onClick={() => setActive("self-build")}>+ {t("settings_view.self_build.open_view")}+ </SettingsLinkButton>+ }+ >+ {query.isError ? (+ <SettingsNote tone="error">{t("settings_view.self_build.unavailable")}</SettingsNote>+ ) : !payload ? (+ <SettingsCard><div className="h-24" aria-busy="true" /></SettingsCard>+ ) : (+ <SettingsCard>+ <SettingsRow+ id="settings-self-build-enabled"+ testId="self-build-enabled"+ title={t("settings_view.self_build.enabled_title")}+ description={t("settings_view.self_build.enabled_description")}+ control={+ <Switch+ checked={payload.settings.enabled}+ disabled={save.isPending}+ aria-label={t("settings_view.self_build.enabled_title")}+ onCheckedChange={(next) => apply({ enabled: next })}+ />+ }+ />+ <SettingsRow+ title={t("settings_view.self_build.autonomy_title")}+ description={t("settings_view.self_build.autonomy_description")}+ className={cn(!payload.settings.enabled && "opacity-60")}+ >+ <div className="divide-y divide-border rounded-md border border-border">+ {BUILD_KINDS.map((kind) => (+ <div key={kind} className="flex flex-wrap items-center justify-between gap-3 px-3 py-2" data-testid={`self-build-autonomy-${kind}`}>+ <span className="text-base text-foreground">{t(`settings_view.self_build.kinds.${kind}`)}</span>+ <SettingsSegmented<Autonomy>+ value={payload.settings[kind]}+ ariaLabel={t(`settings_view.self_build.kinds.${kind}`)}+ disabled={save.isPending || !payload.settings.enabled}+ options={LEVELS.map((level) => ({+ value: level,+ label: t(`settings_view.self_build.levels.${level}`),+ }))}+ onChange={(level) => apply({ [kind]: level })}+ />+ </div>+ ))}+ </div>+ </SettingsRow>+ <SettingsRow+ title={t("settings_view.self_build.limits_title")}+ description={t("settings_view.self_build.limits_description")}+ >+ <div className="grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">+ {LIMITS.map((key) => (+ <NumberField+ key={key}+ name={key}+ payload={payload}+ label={t(`settings_view.self_build.limits.${key}`)}+ disabled={save.isPending}+ onCommit={(value) => apply({ [key]: value })}+ />+ ))}+ </div>+ </SettingsRow>+ </SettingsCard>+ )}+ {error && <SettingsNote tone="error" className="mt-2">{error}</SettingsNote>}+ </SettingsSection>+ );+}++function NumberField({+ name,+ payload,+ label,+ disabled,+ onCommit,+}: {+ name: NumberKey;+ payload: SelfBuildSettingsPayload;+ label: string;+ disabled: boolean;+ onCommit: (value: number) => void;+}) {+ const current = payload.settings[name];+ const bounds = payload.bounds[name];+ const min = bounds?.min ?? 0;+ const max = bounds?.max ?? 1000;+ const [text, setText] = useState(String(current));+ useEffect(() => setText(String(current)), [current]);+ const commit = () => {+ const value = Math.round(Number(text));+ if (!Number.isFinite(value) || text.trim() === "") {+ setText(String(current));+ return;+ }+ const clamped = Math.min(max, Math.max(min, value));+ setText(String(clamped));+ if (clamped !== current) onCommit(clamped);+ };+ return (+ <label className="flex items-center justify-between gap-3" data-testid={`self-build-limit-${name}`}>+ <span className="min-w-0 text-sm text-foreground">{label}</span>+ <input+ type="number"+ inputMode="numeric"+ min={min}+ max={max}+ value={text}+ disabled={disabled}+ aria-label={label}+ onChange={(event) => setText(event.target.value)}+ onBlur={commit}+ onKeyDown={(event) => {+ if (event.key === "Enter") (event.target as HTMLInputElement).blur();+ }}+ className="h-8 w-20 shrink-0 rounded-md border border-border-strong bg-input px-2 text-right text-sm tabular-nums text-foreground focus-visible:border-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ />+ </label>+ );+}diff --git a/dodaios/ui/web/frontend/src/views/settings/settingsSearch.ts b/dodaios/ui/web/frontend/src/views/settings/settingsSearch.tsindex 2d7b2c8dc2..c43c0c787b 100644--- a/dodaios/ui/web/frontend/src/views/settings/settingsSearch.ts+++ b/dodaios/ui/web/frontend/src/views/settings/settingsSearch.ts@@ -16,6 +16,7 @@ const SEARCH_GROUPS = [{ id: "app", keys: ["app_settings_group_title", "autostart", "appearance", "jarvis_api"] },{ id: "realtime-voice", keys: ["realtime_voice"] },{ id: "system-prompt", keys: ["system_prompt"] },+ { id: "self-build", keys: ["self_build"] },{ id: "wake-word", keys: ["wake_word"] },{ id: "volume", keys: ["volume"] },{ id: "audio-devices", keys: ["audio_devices"] },diff --git a/dodaios/ui/web/self_build_routes.py b/dodaios/ui/web/self_build_routes.pyindex 444811a5e7..49fd043119 100644--- a/dodaios/ui/web/self_build_routes.py+++ b/dodaios/ui/web/self_build_routes.py@@ -9,6 +9,9 @@ Endpoints (all under ``/api/self-build``)::POST /{build_id}/accept Build a proposed buildPOST /{build_id}/keep Keep a build on trial (or restore an archived one)POST /{build_id}/undo Remove what the build created, or reject the proposal+ GET /provenance Which agents, skills and routines a build created (the badge)+ GET /settings ``[self_build]`` with each number's range+ PUT /settings Change ``[self_build]``; written to jarvis.toml, applied at onceThe ledger is opened at boot (``dodaios.self_build.service.start``)."""@@ -17,7 +20,7 @@ from __future__ import annotationsimport asyncioimport logging-from typing import Annotated, Any+from typing import Annotated, Any, Literalfrom fastapi import APIRouter, HTTPException, Query, Requestfrom pydantic import BaseModel@@ -92,6 +95,103 @@ async def pause(request: Request, body: PauseBody) -> dict[str, Any]:return await asyncio.to_thread(service.status)[email protected]("/provenance")+async def provenance(request: Request, type: str = "") -> dict[str, Any]: # noqa: A002 — the query name+ """``{"items": {"<type>:<id>": {build_id, state, title, ...}}}`` for the+ "built by Dodaios" badge. Empty (not 503) while the ledger is not running,+ so a list that asks for badges never fails because of them."""+ service = getattr(request.app.state, "self_build", None) or current_service()+ if service is None:+ return {"items": {}}+ return {"items": await asyncio.to_thread(service.provenance, type or None)}+++# ------------------------------------------------------------------ settings++_LEVELS = ("off", "suggest", "trial", "full")+++class SettingsBody(BaseModel):+ enabled: bool | None = None+ silent_days: int | None = None+ memory: Literal["off", "suggest", "trial", "full"] | None = None+ skill: Literal["off", "suggest", "trial", "full"] | None = None+ routine: Literal["off", "suggest", "trial", "full"] | None = None+ agent: Literal["off", "suggest", "trial", "full"] | None = None+ code: Literal["off", "suggest", "trial", "full"] | None = None+ trial_days: int | None = None+ trial_uses: int | None = None+ max_builds_per_day: int | None = None+ max_agents_per_week: int | None = None+ max_open_trials: int | None = None+ max_code_runs_per_day: int | None = None+ max_rejections: int | None = None+++def _config(request: Request) -> Any:+ return getattr(request.app.state, "config", None) or getattr(request.app.state, "cfg", None)+++def _settings_payload(section: Any) -> dict[str, Any]:+ from dodaios.core.config import SelfBuildConfig++ values = (section or SelfBuildConfig()).model_dump()+ bounds = {+ name: {"min": _bound(info, "ge"), "max": _bound(info, "le")}+ for name, info in SelfBuildConfig.model_fields.items()+ if info.annotation is int+ }+ keys = SelfBuildConfig.model_fields.keys()+ return {+ "settings": {key: values[key] for key in keys if key in values},+ "levels": list(_LEVELS),+ "bounds": bounds,+ }+++def _bound(info: Any, name: str) -> int | None:+ for item in info.metadata:+ value = getattr(item, name, None)+ if value is not None:+ return int(value)+ return None++[email protected]("/settings")+def get_settings(request: Request) -> dict[str, Any]:+ """``[self_build]`` as the Settings page edits it, with each number's range."""+ return _settings_payload(getattr(_config(request), "self_build", None))++[email protected]("/settings")+async def put_settings(request: Request, body: SettingsBody) -> dict[str, Any]:+ """Change ``[self_build]``: validated, written to jarvis.toml, applied now.++ The loop reads ``self.cfg`` through a getter, so replacing the in-memory+ section is the whole hot-apply. Excluded from the brain's app actions: only+ the person changes how far the loop may go (docs/self-build.md, rule 3).+ """+ from dodaios.core import config_writer+ from dodaios.core.config import SelfBuildConfig++ changes = body.model_dump(exclude_none=True)+ if not changes:+ raise HTTPException(status_code=400, detail="No settings were provided.")+ cfg = _config(request)+ current = getattr(cfg, "self_build", None) or SelfBuildConfig()+ try:+ merged = SelfBuildConfig(**{**current.model_dump(), **changes})+ except Exception as exc: # noqa: BLE001 — pydantic raises its own type+ raise HTTPException(status_code=400, detail=f"Invalid setting: {exc}") from exc+ await asyncio.to_thread(config_writer.set_self_build_settings, changes)+ if cfg is not None:+ try:+ cfg.self_build = merged+ except Exception as exc: # noqa: BLE001 — the toml write still counts after a restart+ log.warning("self_build: in-memory settings update skipped: %s", exc)+ return _settings_payload(merged)++@router.get("/{build_id}")async def get_build(request: Request, build_id: str) -> dict[str, Any]:service = _service(request)diff --git a/tests/unit/self_build/test_self_build_control.py b/tests/unit/self_build/test_self_build_control.pynew file mode 100644index 0000000000..0c98795183--- /dev/null+++ b/tests/unit/self_build/test_self_build_control.py@@ -0,0 +1,157 @@+"""Control over the self-building loop: settings, provenance and the stop."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.core import config_writer+from dodaios.core.config import SelfBuildConfig+from dodaios.self_build import Kind, SelfBuild, State+++def _client(tmp_path: Path, cfg: object) -> tuple[TestClient, SelfBuild]:+ from dodaios.ui.web.self_build_routes import router++ svc = SelfBuild(tmp_path, lambda: cfg)+ app = FastAPI()+ app.state.self_build = svc+ app.state.config = cfg+ app.include_router(router)+ return TestClient(app), svc+++def _live(svc: SelfBuild, kind: Kind, signature: str, artefact: dict[str, str]) -> str:+ record = svc.ledger.open_case(kind, signature, f"Built {signature}", state=State.BUILDING)+ svc.ledger.attach_artefact(record.id, artefact, {})+ svc.ledger.set_state(record.id, State.TRIAL, "proved")+ return record.id+++# ------------------------------------------------------------------ provenance+++def test_provenance_lists_live_and_archived_artefacts_only(tmp_path: Path) -> None:+ cfg = SimpleNamespace(self_build=SelfBuildConfig(silent_days=0))+ client, svc = _client(tmp_path, cfg)+ skill = _live(svc, Kind.SKILL, "s1", {"type": "skill", "id": "weekly-report"})+ routine = _live(svc, Kind.ROUTINE, "r1", {"type": "routine", "id": "task-7"})+ svc.ledger.set_state(routine, State.ARCHIVED, "unused")+ gone = _live(svc, Kind.AGENT, "a1", {"type": "agent", "id": "agent-3"})+ svc.ledger.set_state(gone, State.UNDONE, "undone")+ svc.ledger.open_case(Kind.SKILL, "p1", "Only proposed") # no artefact yet++ items = client.get("/api/self-build/provenance").json()["items"]+ assert set(items) == {"skill:weekly-report", "routine:task-7"}+ assert items["skill:weekly-report"]["build_id"] == skill+ assert items["routine:task-7"]["state"] == "archived"++ only_skills = client.get("/api/self-build/provenance", params={"type": "skill"}).json()+ assert set(only_skills["items"]) == {"skill:weekly-report"}+ svc.ledger.close()+++def test_provenance_is_empty_without_the_ledger() -> None:+ from dodaios.ui.web.self_build_routes import router++ app = FastAPI()+ app.state.self_build = None+ app.include_router(router)+ assert TestClient(app).get("/api/self-build/provenance").json() == {"items": {}}+++# ------------------------------------------------------------------ settings+++def test_settings_round_trip_writes_toml_and_applies_at_once(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ toml = tmp_path / "jarvis.toml"+ toml.write_text("# the person's comment\n[memory]\ndata_dir = 'x'\n", encoding="utf-8")+ real = config_writer.set_self_build_settings+ monkeypatch.setattr(+ config_writer,+ "set_self_build_settings",+ lambda values: real(values, path=toml),+ )+ cfg = SimpleNamespace(self_build=SelfBuildConfig(silent_days=0))+ client, svc = _client(tmp_path, cfg)++ got = client.get("/api/self-build/settings").json()+ assert got["settings"]["skill"] == "suggest"+ assert got["levels"] == ["off", "suggest", "trial", "full"]+ assert got["bounds"]["max_builds_per_day"] == {"min": 0, "max": 50}++ put = client.put(+ "/api/self-build/settings", json={"skill": "trial", "max_builds_per_day": 5}+ )+ assert put.status_code == 200, put.text+ assert put.json()["settings"]["skill"] == "trial"+ # Hot-applied: the running loop reads the new level through its getter.+ assert svc.status()["autonomy"]["skill"] == "trial"+ text = toml.read_text(encoding="utf-8")+ assert "# the person's comment" in text+ assert "[self_build]" in text and 'skill = "trial"' in text+ assert "max_builds_per_day = 5" in text+ svc.ledger.close()+++def test_settings_reject_out_of_range_without_writing(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ writes: list[dict[str, object]] = []+ monkeypatch.setattr(config_writer, "set_self_build_settings", writes.append)+ cfg = SimpleNamespace(self_build=SelfBuildConfig())+ client, svc = _client(tmp_path, cfg)++ assert client.put("/api/self-build/settings", json={"trial_days": 0}).status_code == 400+ assert client.put("/api/self-build/settings", json={"skill": "always"}).status_code == 422+ assert client.put("/api/self-build/settings", json={}).status_code == 400+ assert writes == []+ assert cfg.self_build.trial_days == 14+ svc.ledger.close()+++def test_writer_refuses_unknown_keys(tmp_path: Path) -> None:+ toml = tmp_path / "jarvis.toml"+ toml.write_text("", encoding="utf-8")+ with pytest.raises(ValueError, match="unknown self_build"):+ config_writer.set_self_build_settings({"judge": "me"}, path=toml)+++# ------------------------------------------------------------------ who may change it+++def test_the_brain_cannot_loosen_the_loop() -> None:+ from dodaios.app_actions.catalog import is_excluded+ from dodaios.core.self_mod.forbidden import is_forbidden++ assert is_excluded("/api/self-build/settings")+ assert is_excluded("/api/self-build/pause")+ assert is_excluded("/api/self-build/{build_id}/accept")+ assert is_excluded("/api/self-build/{build_id}/keep")+ # Seeing what was built, and undoing it, stay reachable when asked.+ assert not is_excluded("/api/self-build")+ assert not is_excluded("/api/self-build/{build_id}/undo")+ assert is_forbidden("self_build.skill")+ assert is_forbidden("self_build.enabled")+++def test_society_kill_switch_pauses_the_loop(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from dodaios.self_build import service as service_module+ from dodaios.society import runtime++ svc = SelfBuild(tmp_path, lambda: SimpleNamespace(self_build=SelfBuildConfig()))+ monkeypatch.setattr(service_module, "_current", svc)+ assert runtime._pause_self_build() is True+ assert svc.status()["paused"] is True+ svc.ledger.close()++ monkeypatch.setattr(service_module, "_current", None)+ assert runtime._pause_self_build() is False