A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): AI-suggested ids for Projects, Agents and Benchmarks (#755)
Yaowei Zheng1da0b39beaed
diff --git a/changelog/unreleased/2026-09-16-ai-suggested-ids.md b/changelog/unreleased/2026-09-16-ai-suggested-ids.mdnew file mode 100644index 00000000..10b5d9c3--- /dev/null+++ b/changelog/unreleased/2026-09-16-ai-suggested-ids.md@@ -0,0 +1,50 @@+# Projects, Agents and Benchmarks get AI-suggested ids++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#755](https://github.com/Prism-Shadow/penguin-harness/pull/755)+- **Breaking:** yes — `POST /organizations/suggest-id` is removed; use `POST /api/projects/:p/suggest-id` with kind `"org"` (or `"channel"`)++[中文版](2026-09-16-ai-suggested-ids.zh.md)++The New Project, Create Agent and New Benchmark dialogs took the organization dialog's shape: the+name comes first, and the id field beside it carries a **Generate with AI** button that asks the+Project's default model for an English id in that kind's own shape. The id stays required,+editable and validated as before; a model that is missing or fails falls back to a transliteration+of the name, and a name nothing can transliterate gets a dated placeholder with a note asking for+a real name.++## Details++- A new route, `POST /api/projects/:projectId/suggest-id`, takes `{name, kind, taken?}` for+ `project`, `agent`, `benchmark`, `org` and `channel`. One implementation serves every kind,+ parameterized by a kind table: `project` and `agent` ids are bare snake_case, a non-admin's+ Project id is `<username>-<suffix>`, and a Benchmark id is kebab-case. No new prefix was+ introduced.+- The route avoids, on its own, every name the kind's create route refuses as taken — every+ Project id and directory on the server, the Project's Agent ids and folders, its Benchmark+ folders, a leftover folder no list shows included — with a `_2` / `-2` suffix. It reads names+ only, and never names those ids to the model. An id the kind rejects for starting with a digit+ or being one character long gets the kind's name in front (`agent_3d_viewer`).+- Asking follows the create routes: a member of the Project for a Project or Agent id, the owner+ for a Benchmark id. The New Project dialog asks the default model of the Project it was opened+ from.+- `org` and `channel` delegate to the organization service, so their proposals, prompts and+ error records are unchanged. `POST /api/projects/:projectId/organizations/suggest-id` was+ removed. A failed model ask for the three new kinds is recorded as an `id_suggest` /+ `id_suggest_failed` error.+- The shared id field and its notice moved from `features/company` to `features/semantic-id`, its+ copy moved from `company` to a `semanticId` dictionary section, and it gained a locked prefix+ for a non-admin's Project id. The Benchmark dialog no longer rewrites the id while the title is+ typed.+- The Server API reference gained the route in place of the organizations' `/suggest-id` row,+ and the Web App guide describes the three dialogs' id fields, in both languages.++## Compatibility++`POST /api/projects/:projectId/organizations/suggest-id` no longer exists. An API client that+called it sends the same body — `{name, kind, taken?}`, `kind` being `org` or `channel` — to+`POST /api/projects/:projectId/suggest-id`, which answers with the same `{id, source, reason?}`.+The Web App and the CLI need nothing: the organization and channel dialogs moved to the new route+in this change, and the CLI never called the old one.diff --git a/changelog/unreleased/2026-09-16-ai-suggested-ids.zh.md b/changelog/unreleased/2026-09-16-ai-suggested-ids.zh.mdnew file mode 100644index 00000000..0d0832aa--- /dev/null+++ b/changelog/unreleased/2026-09-16-ai-suggested-ids.zh.md@@ -0,0 +1,24 @@+# Project、Agent 与 Benchmark 的 id 可由 AI 生成++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#755](https://github.com/Prism-Shadow/penguin-harness/pull/755)+- **Breaking:** yes — 移除 `POST /organizations/suggest-id`,改用 `POST /api/projects/:p/suggest-id` 并传 kind `"org"`(或 `"channel"`)++[English](2026-09-16-ai-suggested-ids.md)++新建 Project、创建 Agent 与新建 Benchmark 三个对话框改为与新建组织相同的形态:名称在前,旁边的 id 字段带「用 AI 生成」按钮,请 Project 的默认模型按该类对象自己的 id 形状给出一个英文 id。id 仍为必填、可改写,校验不变;没有模型或调用失败时退回名称的转写,无从转写的名称则填入带日期的占位 id,并在字段下方提示改成有含义的名字。++## 细节++- 新增路由 `POST /api/projects/:projectId/suggest-id`,接受 `{name, kind, taken?}`,`kind` 为 `project`、`agent`、`benchmark`、`org` 或 `channel`。各 kind 共用同一份实现,由一张类型表参数化:`project` 与 `agent` 的 id 是不带前缀的 snake_case,非 admin 用户的 Project id 为 `<用户名>-<后缀>`,Benchmark id 为 kebab-case。没有引入新的前缀。+- 路由自行避开该 kind 的创建路由会以「已占用」拒绝的全部名称——服务器上的全部 Project id 与目录、该 Project 的 Agent id 与目录、其 Benchmark 目录,列表里看不到的残留目录也算在内——撞名时加 `_2` / `-2` 后缀。只读名称,这些 id 也不会写进给模型的提示词。以数字开头或只有一个字符、因而不合该类规则的 id,前面补上类型名(如 `agent_3d_viewer`)。+- 调用权限与各自的创建路由一致:Project 与 Agent 的 id 须是该 Project 的成员,Benchmark 的 id 须是 Owner。新建 Project 对话框以打开它的那个 Project 的默认模型提问。+- `org` 与 `channel` 转交组织服务,提议、提示词与错误记录都不变。`POST /api/projects/:projectId/organizations/suggest-id` 已移除。三个新 kind 的模型调用落空记为 `id_suggest` / `id_suggest_failed` 错误。+- 共用的 id 字段及其提示从 `features/company` 移到 `features/semantic-id`,文案从 `company` 移到词典的 `semanticId` 一节,并为非 admin 用户的 Project id 增加了锁定前缀。Benchmark 对话框不再在输入标题时改写 id。+- Server API 参考新增了该路由并删去组织的 `/suggest-id` 一行,Web App 指南补充了三个对话框的 id 字段说明,中英文同步。++## 兼容性++`POST /api/projects/:projectId/organizations/suggest-id` 已不存在。调用过它的 API 客户端改为把同样的 body——`{name, kind, taken?}`,`kind` 为 `org` 或 `channel`——发给 `POST /api/projects/:projectId/suggest-id`,答复同为 `{id, source, reason?}`。Web App 与 CLI 无需任何改动:组织与频道对话框已在本次改动中改用新路由,CLI 从未调用旧路由。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex a0be606a..df3308bd 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -161,6 +161,7 @@ Refusals decided before any ssh runs have their own codes: `409` `install_runnin| GET | /api/projects | Projects visible to the current user || POST | /api/projects | Create a Project || DELETE | /api/projects/:projectId | Delete a Project |+| POST | /api/projects/:projectId/suggest-id | A semantic id proposed for the display name of an object being created: `{name, kind, taken?}`, `kind` being `project`, `agent`, `benchmark`, `org` or `channel` and `taken` the ids the proposal must avoid → `{id, source, reason?}`. The default model of the Project in the path translates the name into one English id in the kind's spelling (`source: model`) — the New Project dialog borrows the Project it was opened from — and is asked a second time with the format spelled out when the first answer yields no id; an ASCII slug of the name answers when no model is configured or neither answer is usable (`source: fallback`); a name neither path can name gets a dated placeholder (`source: placeholder`) with a `reason` of `no_default_model`, `model_failed`, `unusable_answer` or `no_ascii`. The route never fails for a name it cannot translate — a dialog that asked for an id always gets one. Kinds differ only in the id's shape, the ids the server avoids on its own, and who may ask: `project` is snake_case for the admin and `<username>-<suffix>` for anyone else, avoiding every Project id on the server; `agent` is snake_case, avoiding the Project's Agents; `benchmark` is kebab-case, avoiding the Project's Benchmarks, owner only; `org` and `channel` carry a `co_` / `ch_` prefix, never doubled when the model's answer already has it, and answer 404 `company_mode_off` while company mode is off. Every other caller must be a member of the Project. The ids the server avoids on its own are every name the kind's create route refuses as taken — a leftover folder no list shows, such as a Benchmark directory with no config, included — and never reach the prompt, only a `_2` / `-2` suffix on a collision; an id the kind's rule rejects for starting with a digit or being one character long gets the kind's name in front (`agent_3d_viewer`); the placeholders are `project_<yyyymmdd>`, `agent_<yyyymmdd>`, `benchmark-<yyyymmdd>`, `co_org_<yyyymmdd>` and `ch_channel_<yyyymmdd>` (a non-admin's Project with the username in front). Every model dead end is recorded as an `id_suggest_failed` error, under the source `organization` for `org` / `channel` and `id_suggest` for the rest; the completion runs with thinking off and the shared meta budget, belongs to no Session and is not metered || GET | /api/projects/:projectId/members | List members || POST | /api/projects/:projectId/members | Add a member: `{userId}` || DELETE | /api/projects/:projectId/members/:userId | Remove a member |@@ -287,7 +288,6 @@ All paths below are under `/api/projects/:projectId/organizations`. Every route| Method | Path | Description || --- | --- | --- || GET / POST | / | List organizations / create one: `{orgId, mission, name?, timezone?, workspace?, model?, ceoBudget?, language?}` → 201 with the organization detail (creation makes the CEO Agent and opens its desk with an initialization run; 409 when the id or the CEO's Agent id is taken). The CEO's chart entry is written with `workspace: ceo`, a partition of the shared workspace like every other employee's. `ceoBudget` is the CEO's monthly USD budget, written as the `budget` of its `org_chart.yaml` entry — non-negative, omitted = 100; compared on the cumulative line, it is the whole company's cap. `language` is `zh` or `en`, the working language everything the organization writes is written in; omitted, it is detected from the mission |-| POST | /suggest-id | A semantic id proposed for a display name: `{name, kind}` — `kind` is `org` or `channel` — plus `taken?`, the ids the proposal must avoid → `{id, source, reason?}`. The Project's default model translates the name into one snake_case English core (`source: model`), asked a second time with the format spelled out when the first answer yields no id; an ASCII slug of the name answers when no model is configured or neither answer is usable (`source: fallback`); and a name neither path can name gets `co_org_<yyyymmdd>` / `ch_channel_<yyyymmdd>` (`source: placeholder`) with a `reason` of `no_default_model`, `model_failed`, `unusable_answer` or `no_ascii`. The route never fails for a name it cannot translate — a dialog that asked for an id always gets one — and every model dead end is recorded as an `organization` / `id_suggest_failed` error. The server then prefixes the core by kind — `co_` for `org`, `ch_` for `channel`, never doubled when the core already carries it — before capping the length and avoiding `taken`, so a proposal is always prefixed and a hand-typed id never is. The completion runs with thinking off and the shared meta budget, belongs to no Session and is not metered || GET / PATCH | /:orgId | Overview (settings, board counts, today's calendar, pending items, the all-hands channel's recent messages, `inbox`, alerts; the settings always carry the effective `language`, read from the mission when the file has none) / change name, mission, `status` (`active` / `paused` — pausing stops every automatic trigger), `approvalMode`, `timezone`, `language`, thresholds || GET | /:orgId/chart | The employee tree with live state, desk and period spend per employee || POST | /:orgId/employees | Hire: `{agentId}` for an existing Agent or `{newAgent: {agentId, name?, description?, plugins?}}`, plus `title`, `reportsTo`, `workspace?`, `budget?`, `duties?`, `model?`. `workspace` defaults to a sub-directory named after the employee's Agent id — the shared workspace's root holds the shared inputs and is nobody's desk. A relative `workspace` is normalized (`./hr` → `hr`) and created under the shared workspace, an absolute one must already exist, and one climbing out with `..` is 400 `invalid_workspace` |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 34154e3b..dd96d46d 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -161,6 +161,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \| GET | /api/projects | 当前用户可见的 Project 列表 || POST | /api/projects | 创建 Project || DELETE | /api/projects/:projectId | 删除 Project |+| POST | /api/projects/:projectId/suggest-id | 为新建对象的显示名提议一个语义 id:`{name, kind, taken?}`,`kind` 为 `project`、`agent`、`benchmark`、`org` 或 `channel`,`taken` 为提议须避开的 id → `{id, source, reason?}`。路径中 Project 的缺省 Model 把名称译成该 kind 拼写的英文 id(`source: model`)——新建 Project 的对话框借用打开它的那个 Project;首次回答拼不出 id 时,会带上「只回答标识符本身」的格式要求再问一次;未配置 Model 或两次回答都无法用时,以名称的 ASCII slug 兜底(`source: fallback`);两条路都命名不了的名称回一个带日期的占位 id(`source: placeholder`),并带上 `reason`:`no_default_model`、`model_failed`、`unusable_answer` 或 `no_ascii`。该路由不会因为「名称译不出来」而失败——问了 id 的对话框一定拿得到一个。各 kind 只在 id 的形状、服务端自行避开的 id 与调用权限上不同:`project` 在 admin 名下是 snake_case,其他用户是 `<用户名>-<后缀>`,避开服务器上已有的全部 Project id;`agent` 是 snake_case,避开该 Project 的 Agent;`benchmark` 是 kebab-case,避开该 Project 的 Benchmark,仅 Owner 可调用;`org` 与 `channel` 带 `co_` / `ch_` 前缀,模型的回答本就带前缀时不会加第二遍,公司模式关闭时回 404 `company_mode_off`。其余调用者须是该 Project 的成员。服务端自行避开的是该 kind 的创建路由会以「已占用」拒绝的全部名称——列表里看不到的残留目录(如没有配置文件的 Benchmark 目录)也算在内——它们不写进提示词,撞名时只加 `_2` / `-2` 后缀;以数字开头或只有一个字符、因而不合规则的 id 前面补上类型名(如 `agent_3d_viewer`);占位 id 为 `project_<yyyymmdd>`、`agent_<yyyymmdd>`、`benchmark-<yyyymmdd>`、`co_org_<yyyymmdd>` 与 `ch_channel_<yyyymmdd>`(非 admin 的 Project 带用户名前缀)。Model 一侧的每一次落空都记为 `id_suggest_failed` 错误,`org` / `channel` 的来源为 `organization`,其余为 `id_suggest`;该次补全关闭思考、使用共享的元请求预算,不属于任何 Session,也不计量 || GET | /api/projects/:projectId/members | 成员列表 || POST | /api/projects/:projectId/members | 添加成员:`{userId}` || DELETE | /api/projects/:projectId/members/:userId | 移除成员 |@@ -287,7 +288,6 @@ Benchmark 挂在 Project 上而非某个 Agent 上:一个 Benchmark 评测过| 方法 | 路径 | 说明 || --- | --- | --- || GET / POST | / | 列出组织 / 新建:`{orgId, mission, name?, timezone?, workspace?, model?, ceoBudget?, language?}` → 201 并返回组织详情(创建即生成 CEO Agent 并以初始化会话打开其工位;id 或 CEO 的 Agent id 已被占用则 409)。CEO 的组织图条目写入 `workspace: ceo`,与其他员工一样是公共工作区下的一个分区。`ceoBudget` 是 CEO 的月预算(美元),写入其 `org_chart.yaml` 条目的 `budget`——非负,不给则为 100;按累计线比较,即整家公司的上限。`language` 取 `zh` 或 `en`,是组织书写一切内容所用的工作语言;不给则从使命判定 |-| POST | /suggest-id | 为显示名提议一个语义 id:`{name, kind}`——`kind` 为 `org` 或 `channel`——外加 `taken?`(提议须避开的 id)→ `{id, source, reason?}`。Project 的缺省 Model 把名称译成一个 snake_case 英文词干(`source: model`);首次回答拼不出 id 时,会带上「只回答标识符本身」的格式要求再问一次;未配置 Model 或两次回答都无法用时,以名称的 ASCII slug 兜底(`source: fallback`);两条路都命名不了的名称回一个占位 id `co_org_<yyyymmdd>` / `ch_channel_<yyyymmdd>`(`source: placeholder`),并带上 `reason`:`no_default_model`、`model_failed`、`unusable_answer` 或 `no_ascii`。该路由不会因为「名称译不出来」而失败——问了 id 的对话框一定拿得到一个;Model 一侧的每一次落空都记为 `organization` / `id_suggest_failed` 错误。随后服务端按 kind 给词干加前缀——`org` 加 `co_`、`channel` 加 `ch_`,词干本就带前缀时不会加第二遍——再截长度、再避开 `taken`,因此提议出来的 id 一定带前缀,而手工输入的 id 一律按原样接受。该次补全关闭思考、使用共享的元请求预算,不属于任何 Session,也不计量 || GET / PATCH | /:orgId | 概览(设置、看板计数、今日日程、待处理、全员频道最近消息、`inbox`、告警;设置里的 `language` 一律是生效值,文件里没有该字段时从使命读出)/ 修改名称、使命、`status`(`active` / `paused`——暂停即停止一切自动触发)、`approvalMode`、`timezone`、`language` 与阈值 || GET | /:orgId/chart | 员工树,含每位员工的实况状态、工位与本周期支出 || POST | /:orgId/employees | 招募:任用已有 Agent 传 `{agentId}`,或新建 `{newAgent: {agentId, name?, description?, plugins?}}`,再加 `title`、`reportsTo`、`workspace?`、`budget?`、`duties?`、`model?`。`workspace` 不给则缺省为以该员工 Agent id 命名的子目录——公共工作区的根目录放共享输入,不是任何人的工位。相对 `workspace` 会归一化(`./hr` → `hr`)并在公共工作区下创建,绝对路径必须已经存在,用 `..` 爬出公共工作区的写法回 400 `invalid_workspace` |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 1c20051d..b5ef4772 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -110,7 +110,7 @@ Everything the Web App creates from a form — an agent, a model group, a Benchm## Agent Management (/agents)-The header carries the two buttons described under [Create with AI](#create-with-ai), and the list's call to action offers the same pair while the Project has no agent beyond `default_agent`. The dialog opens on the path you picked and stays there. **Create with AI** opens a prompt box with five examples — a jotting agent, a financial Copilot, a document RAG agent, a deep-research report agent, and the report-writing agent with the id `report-writer` that the onboarding path starts from (create it with AI, then let AI build a Benchmark for it and optimize it) — and a fixed tail that has the Project's default agent run the `agent-initialization` skill: a new agent under this Project with the id you gave or a semantic one, its AGENTS.md and name/description written, only the skills it needs copied from the plugin library, no other agent touched, and the id plus how to start a conversation reported at the end. **Create manually** opens the form, unchanged; the sidebar's "new agent" button names no path and opens it too.+The header carries the two buttons described under [Create with AI](#create-with-ai), and the list's call to action offers the same pair while the Project has no agent beyond `default_agent`. The dialog opens on the path you picked and stays there. **Create with AI** opens a prompt box with five examples — a jotting agent, a financial Copilot, a document RAG agent, a deep-research report agent, and the report-writing agent with the id `report-writer` that the onboarding path starts from (create it with AI, then let AI build a Benchmark for it and optimize it) — and a fixed tail that has the Project's default agent run the `agent-initialization` skill: a new agent under this Project with the id you gave or a semantic one, its AGENTS.md and name/description written, only the skills it needs copied from the plugin library, no other agent touched, and the id plus how to start a conversation reported at the end. **Create manually** opens the form: the name comes first, and **Generate with AI** beside the id field derives the agent id from the name (or the description while the name is empty) with the Project's default model; the sidebar's "new agent" button names no path and opens it too.The list page creates and deletes Agents — the create dialog can initialize the new agent from an exported Agent State snapshot package (name and description left empty keep the package's values, and plugin picking is unavailable then, since the package carries its own skills and hooks) — and clicking through opens the `/agents/:agentId` settings page, organized into tabs:@@ -151,7 +151,7 @@ The header carries the two create buttons (owner only). **Create with AI** handsEvery Benchmark of the Project, one card each — a Benchmark belongs to the Project, not to an agent, so the list is a flat one: the title and directory name, the description, the case and run counts, when it was last evaluated, the agents it has evaluated, a sparkline of the scoreboard, and the newest score with its change from the previous evaluation under the same label. Clicking a card, or **View**, enters that Benchmark's own page (`/benchmark/<benchmark>`) — the score chart over time, the evaluation table with per-case and per-run rows, and the case browser (the same file browser as the plugin detail: the Workspace panel's tree on the left — task materials and rubric as its two top-level folders, listed level by level — and a read-only preview on the right) — with a back button to the list. A Benchmark whose config says `status = "draft"` — the agent is still writing and calibrating it — is masked: the card dims under a notice that it is being built, **Use** and **View** are disabled, and its page shows the same notice in place of the cases and the chart; only the owner's delete icon stays live. One whose config says `status = "failed"` — its difficulty calibration never finished — is masked the same way, under a "creation failed" notice asking the user to delete the Benchmark and create it again. The mask lifts once the status is `published`. Under the title stand three separate step cards, one per step of the loop — **Create**, **Evaluate**, **Optimize** — each with its number, its title and one sentence saying where to do it: creating is the two buttons at the top right, and evaluating and optimizing are **Use** on a Benchmark followed by the matching tab. The conversations **Use** opens, and the Test Sessions an evaluation launches for every Case × Run, are filed under the session list's **Evaluations** folder.-- Two buttons sit side by side at the top right, the same pair the agent's scheduled-tasks tab uses: the magic wand goes to AI, the hand to the form. **Create with AI** asks for the Test Agent and a description of the capability and scenarios; the prompt's fixed tail hands the `benchmark-design` Skill the agent id, a desired baseline score and a pilot-iteration limit, and asks for the baseline to be taken. **Create manually** is a form — title, id, description, runs per case, and one statement plus rubric per case, with no owning agent to pick — that the server writes to disk in the layout the Skills read (`POST …/benchmarks`, owner only).+- Two buttons sit side by side at the top right, the same pair the agent's scheduled-tasks tab uses: the magic wand goes to AI, the hand to the form. **Create with AI** asks for the Test Agent and a description of the capability and scenarios; the prompt's fixed tail hands the `benchmark-design` Skill the agent id, a desired baseline score and a pilot-iteration limit, and asks for the baseline to be taken. **Create manually** is a form — title, id (which **Generate with AI** derives from the title in kebab-case), description, runs per case, and one statement plus rubric per case, with no owning agent to pick — that the server writes to disk in the layout the Skills read (`POST …/benchmarks`, owner only).- **Use**, on a card and in the Benchmark page's header, opens one dialog with two tabs over a single exit. **Evaluate** puts an agent on the frozen cases: the tested agent (the one the newest evaluation tested, by default), the evaluator agent (with a warning when it lacks the `agent-evaluation` Skill), the model of the evaluation conversation (the Project settings' own model picker, preset to the Project's default model), runs per case, and an optional note. Its prompt asks for the full Case × runs matrix through self-spawned `agent-evaluation` subagents, requires every result's agent, model pair and thinking level to agree, and appends exactly one labelled evaluation to `scoreboard.yaml` — the tested agent and the Benchmark are left untouched. **Optimize** is the optimizer form: the optimizer agent (warned the same way), the **agent under test**, the model of the optimizer's own conversation (the same picker, preset the same way), runs per case, a round limit, a target score (ten above that agent's baseline by default) and an optional focus; an agent with no baseline here is told to take one on the Evaluate tab first. Both tabs preview the full prompt and both end the same way, at **Edit in a new conversation**: the prompt is prefilled into the composer and sending it is yours to decide. The evaluation runtime is never picked in this dialog — Evaluate takes the tested agent's own configured model and thinking level, and Optimize reuses what the baseline recorded.- The chart plots time against score and draws one series per **label** — agent id, model id and thinking level — so only comparable scores share a line; a record with no label falls into a grey series. The Agent State version is deliberately not part of the label: successive versions of one agent on the same model and thinking level stay on one line, which is exactly where an improvement is supposed to become visible, and each point names the version it tested in its hover bubble. The evaluation table keeps a version column of its own, and names the agent under test in another.- Clicking a row of the evaluation table opens that **evaluation in a dialog**, in the same shape as the case dialog: the series label with the tested agent and the version at the top, the Score, cost and duration under it, the evaluation's own summary (its title and its body shown separately), and the per-case table, whose rows expand to the raw result of every Run with the Session it ran in. A case named in there opens the case dialog on top of it.@@ -210,7 +210,7 @@ The dialog walks the update through: opening it with nothing known runs a check## Projects and Members-The sidebar provides a Project switcher and supports creating new Projects. Members have two roles, owner and member: owners manage membership and exclusively edit models, Vault, and Schedules, as well as perform deletions.+The sidebar provides a Project switcher and supports creating new Projects: the display name comes first, and **Generate with AI** beside the Project id field derives the id from it with the current Project's default model (a non-admin types only what follows `<username>-`). Members have two roles, owner and member: owners manage membership and exclusively edit models, Vault, and Schedules, as well as perform deletions.## Production Deploymentdiff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex e890fa3f..34b474cb 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -109,7 +109,7 @@ Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchma## Agent 管理(/agents)-页头是[用 AI 创建](#用-ai-创建)一节所述的那两个按钮;Project 里除 `default_agent` 外还没有 Agent 时,列表末尾的空态按钮同样是这一对。弹窗按你点的那个按钮打开对应路径,并停在那里。**用 AI 创建**的提示词框带五个示例——随记智能体、金融 Copilot、文档 RAG 智能体、深度研究报告智能体,以及新手引导链(先用 AI 创建它,再让 AI 为它建 Benchmark 并优化)起点的报告写作智能体(id 为 `report-writer`)——固定尾巴让 Project 的默认 Agent 用 `agent-initialization` 技能创建:在当前 Project 下新建一个 Agent(用你给的 id,否则取语义 id),写好它的 AGENTS.md 与名称、描述,只从插件库复制它需要的技能,不动其他 Agent,最后报出 id 与开始对话的方式。**手动创建**打开原来的表单,内容不变;侧边栏那个「新建 Agent」按钮不点名路径,打开的也是它。+页头是[用 AI 创建](#用-ai-创建)一节所述的那两个按钮;Project 里除 `default_agent` 外还没有 Agent 时,列表末尾的空态按钮同样是这一对。弹窗按你点的那个按钮打开对应路径,并停在那里。**用 AI 创建**的提示词框带五个示例——随记智能体、金融 Copilot、文档 RAG 智能体、深度研究报告智能体,以及新手引导链(先用 AI 创建它,再让 AI 为它建 Benchmark 并优化)起点的报告写作智能体(id 为 `report-writer`)——固定尾巴让 Project 的默认 Agent 用 `agent-initialization` 技能创建:在当前 Project 下新建一个 Agent(用你给的 id,否则取语义 id),写好它的 AGENTS.md 与名称、描述,只从插件库复制它需要的技能,不动其他 Agent,最后报出 id 与开始对话的方式。**手动创建**打开表单:名称在前,id 字段旁的「用 AI 生成」以 Project 的默认模型按名称(名称留空时按描述)推导 Agent id;侧边栏那个「新建 Agent」按钮不点名路径,打开的也是它。列表页支持创建与删除 Agent——创建弹窗可选从导出的 Agent State 快照包直接初始化(名称与描述留空沿用包内值;此时技能选择不可用,包自带技能);点击进入 `/agents/:agentId` 设置页,按标签页组织:@@ -150,7 +150,7 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,Project 的全部 Benchmark 平铺列出,每个 Benchmark 一张卡片——Benchmark 属于 Project 而非某个 Agent,因此页面不按 Agent 分组:标题与目录名、描述、题数与每题运行次数、最近评估时间、评测过的 Agent、评分板的分数走势小折线,以及最新分数与相对同标签上一条评估的增减。点击卡片或**查看**进入这个 Benchmark 自己的页面(`/benchmark/<benchmark>`)——以时间为横轴的分数曲线、带单题与逐次运行行的评估明细表、题目浏览器(题目浏览器与插件详情共用同一个文件浏览器:左侧是 Workspace 文件面板同款的文件树——任务材料与评分标准是它的两个顶层目录,逐级懒加载——右侧是只读预览)——页头的返回按钮回到列表。配置里 `status = "draft"` 的 Benchmark(智能体仍在出题与校准)会被遮罩:卡片变淡并覆一层「构建中」提示,**使用**与**查看**禁用,其页面正文也以同样的提示代替题目与曲线;只有 owner 的删除图标仍可用。配置里 `status = "failed"` 的 Benchmark(难度校准未能完成)同样被遮罩,提示改为「创建失败」,请用户删除后重新创建。状态改为 `published` 后遮罩解除。标题下是三张独立的步骤卡片,一步一张——**出题**、**评估**、**优化**——各写序号、标题与一句话操作说明:出题用右上角的两个创建按钮,评估与优化都是在某个 Benchmark 上按**使用**再选对应的 tab。**使用**开出的对话,以及一次评估为每个 Case × Run 启动的被测会话,都归入会话列表的**评估任务**折叠夹。-- 右上并排两个按钮,与智能体设置的定时任务页是同一对:魔法棒走 AI,手掌走表单。**用 AI 创建**要求选定被测 Agent 并描述要考察的能力与场景;提示词的固定尾部把 Agent id、期望基线分与 Pilot 迭代上限交给 `benchmark-design` 技能,并要求取得基线分。**手动创建**是一张表单——标题、id、描述、每题运行次数、每道题的题干与评分细则,不再选择所属 Agent——由服务端按技能读取的目录结构落盘(`POST …/benchmarks`,仅 owner)。+- 右上并排两个按钮,与智能体设置的定时任务页是同一对:魔法棒走 AI,手掌走表单。**用 AI 创建**要求选定被测 Agent 并描述要考察的能力与场景;提示词的固定尾部把 Agent id、期望基线分与 Pilot 迭代上限交给 `benchmark-design` 技能,并要求取得基线分。**手动创建**是一张表单——标题、id(可点「用 AI 生成」按标题推导为 kebab-case)、描述、每题运行次数、每道题的题干与评分细则,不再选择所属 Agent——由服务端按技能读取的目录结构落盘(`POST …/benchmarks`,仅 owner)。- 卡片与 Benchmark 页面头部的**使用**打开同一个弹窗,顶部两个 tab 共用一个出口。**评估**把一个智能体放到已冻结的题目上:被测 Agent(缺省为最近一条评估的 Agent)、执行评估的 Agent(未装 `agent-evaluation` 技能时有提示)、评估会话使用的模型(与 Project 默认设置同一个模型选择器,缺省即当前 Project 的默认模型)、每题运行次数与可选说明。它的提示词要求经自调用的 `agent-evaluation` 子会话跑完整的 Case × runs 矩阵,校验每条结果的被测 Agent、成对模型与思考等级一致,并只向 `scoreboard.yaml` 追加一条带标签的评估——不动被测 Agent,也不动 Benchmark。**优化**是优化表单:执行优化的 Agent(同样会提示缺技能)、**被测 Agent**、优化会话自身使用的模型(同一个选择器、同样的缺省)、每题运行次数、最多轮数、目标分数(缺省比该 Agent 的基线高 10 分)与可选的优化重点;所选被测 Agent 在此还没有基线时,提示先到「评估」取得一条。两个 tab 都可折叠展开完整提示词,也都以同一个出口结束——**在新对话中编辑**:提示词预填进输入框,发不发送由你决定。评测 Runtime 不在这个弹窗里选——「评估」取被测 Agent 当前配置的模型与思考等级,「优化」沿用基线记录的那一套。- 曲线以时间为横轴、分数为纵轴,按**标签**分系列——标签为被测 Agent id、模型 id 与思考等级三者,只有同标签的分数才可比;没有标签的旧记录归入灰色系列。Agent State 版本号刻意不进标签:同一被测 Agent 在同一模型与思考等级下的历次版本连成一条线,进步正应该在这条线上看出来,版本号则标在每个点的悬停提示里。评估明细表自带一列版本号,另有一列写明被测 Agent。- 点击评估明细表的一行打开该次**评估详情弹窗**,形制与题目详情弹窗一致:顶部是系列标签、被测 Agent 与版本,其下为 Score、成本与耗时,再下是这次评估自己的说明(标题与正文分开展示)与单题得分表,题目行可展开逐次 run 的原始结果及其 Session id。在其中点开某道题,题目详情弹窗叠在它之上。@@ -209,7 +209,7 @@ Project 的全部 Benchmark 平铺列出,每个 Benchmark 一张卡片——Be## Project 与成员-侧边栏提供 Project 切换器,并支持创建新 Project。成员分为 Owner 与 Member 两种角色:Owner 负责成员管理,并独占模型、Vault、Schedule 的编辑以及各类删除操作。+侧边栏提供 Project 切换器,并支持创建新 Project:显示名在前,Project id 字段旁的「用 AI 生成」以当前 Project 的默认模型按显示名推导 id(非 admin 用户只填 `<用户名>-` 之后的部分)。成员分为 Owner 与 Member 两种角色:Owner 负责成员管理,并独占模型、Vault、Schedule 的编辑以及各类删除操作。## 生产部署diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 5626347d..21edb708 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -4509,19 +4509,31 @@ export interface OrganizationPatchRequest {}/**- * A semantic id proposed for a display name — the organization and channel dialogs let the- * user name the thing first and derive the id from that name. The server asks the Project's- * default model for a short English snake_case id (a Chinese name has no mechanical+ * What a proposed semantic id names. Each kind has its own shape — organization and channel+ * ids carry a `co_` / `ch_` prefix, a non-admin's Project id its owner's `<username>-`, a+ * Benchmark id is kebab-case — and its own set of ids to avoid.+ */+export type SemanticIdKind = "org" | "channel" | "project" | "agent" | "benchmark";++/**+ * A semantic id proposed for a display name — every create dialog that names an object with a+ * semantic id (a Project, an Agent, a Benchmark, an organization, a channel) lets the user name+ * the thing first and derive the id from that name. The server asks the Project's default+ * model for a short English id in the kind's spelling (a Chinese name has no mechanical* transliteration), falling back to an ASCII slug of the name when the model is unavailable,* and to a dated placeholder when neither can name it. The request never fails for a name it* cannot translate: a dialog that asked for an id always gets one back.*/export interface SemanticIdSuggestRequest {- /** The display name typed so far (or the mission, when nothing else names the thing). */+ /** The display name typed so far (or the mission / description, when nothing else names the thing). */name: string;- /** What the id is for: decides the prompt's examples and the fallback's prefix. */- kind: "org" | "channel";- /** Ids already in use in the target scope; the proposal avoids them. */+ /** What the id is for: decides the id's shape, the prompt's examples and the ids avoided. */+ kind: SemanticIdKind;+ /**+ * Ids already in use in the target scope; the proposal avoids them. For a Project, an Agent or+ * a Benchmark, the server also avoids, on its own, every id that kind's create route refuses+ * as taken, a leftover folder no list shows included.+ */taken?: string[];}@@ -4536,7 +4548,10 @@ export type SemanticIdSuggestReason ="no_default_model" | "model_failed" | "unusable_answer" | "no_ascii";export interface SemanticIdSuggestResponse {- /** A valid semantic id (`^[a-z][a-z0-9_]{1,63}$`), not in `taken`. */+ /**+ * An id the kind's create route accepts, not in `taken`: `^[a-z][a-z0-9_]{1,63}$` for most+ * kinds, `<username>-<suffix>` for a non-admin's Project, kebab-case for a Benchmark.+ */id: string;/** Who produced it: the model, the ASCII fallback, or the dated placeholder that names nothing. */source: "model" | "fallback" | "placeholder";diff --git a/packages/server/src/http/routes/organizations.ts b/packages/server/src/http/routes/organizations.tsindex 736a42bd..fd8d85c1 100644--- a/packages/server/src/http/routes/organizations.ts+++ b/packages/server/src/http/routes/organizations.ts@@ -1,7 +1,6 @@/*** Company-mode routes, nested under a Project:* GET|POST /api/projects/:p/organizations- * POST /api/projects/:p/organizations/suggest-id # a semantic id for a display name* GET|PATCH /api/projects/:p/organizations/:orgId* GET …/:orgId/chart* POST …/:orgId/employees # hire@@ -38,7 +37,6 @@ import type {OrgTicketPriority,OrgTicketStatus,OrganizationsResponse,- SemanticIdSuggestRequest,} from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import type { SessionVia } from "../../auth/service.js";@@ -67,7 +65,6 @@ const STATUSES: readonly OrgStatus[] = ["active", "paused"];const APPROVAL_MODES: readonly OrgApprovalMode[] = ["allow-all", "read-only", "deny-all"];const LANGUAGES: readonly OrgLanguage[] = ["zh", "en"];const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];-const ID_KINDS: readonly SemanticIdSuggestRequest["kind"][] = ["org", "channel"];function requireTicketId(raw: string | undefined): string {if (!raw || !TICKET_ID_PATTERN.test(raw)) throw badRequest("Invalid ticket id.");@@ -226,22 +223,6 @@ export function organizationRoutes(deps: OrgRouteDeps): Hono<AppEnv> {return c.json(detail, 201);});- // Before the `/:orgId` routes: a proposal needs no organization, only the Project.- app.post("/suggest-id", async (c) => {- const projectId = requireValidId(c, "projectId");- member(c, projectId);- const body = await readJson(c);- const name = requireString(body, "name", { minLen: 1, maxLen: 4000 });- const kind = requireEnum(body, "kind", ID_KINDS);- const taken = optionalStringArray(body, "taken");- const res = await deps.orgService.suggestId(projectId, {- name,- kind,- ...(taken !== undefined ? { taken } : {}),- });- return c.json(res);- });-app.get("/:orgId", async (c) => {const projectId = requireValidId(c, "projectId");const orgId = requireValidId(c, "orgId");diff --git a/packages/server/src/http/routes/suggest-id.ts b/packages/server/src/http/routes/suggest-id.tsnew file mode 100644index 00000000..c6d5c8ee--- /dev/null+++ b/packages/server/src/http/routes/suggest-id.ts@@ -0,0 +1,159 @@+/**+ * Semantic id proposals for every create dialog that names an object with a semantic id:+ * POST /api/projects/:p/suggest-id { name, kind, taken? } → { id, source, reason? }+ *+ * `kind` is `project`, `agent`, `benchmark`, `org` or `channel`. The proposal itself is the+ * shared one (services/semantic-id-suggest.ts): the default model of the Project in the path,+ * then the ASCII slug of the name, then a dated placeholder. What differs by kind is decided+ * here, beside the permission each kind's create route demands:+ *+ * | kind | who may ask | id shape | avoided on top of `taken` |+ * | ----------- | ---------------------------------------- | ---------------------------------- | ------------------------------------- |+ * | `project` | a member of `:p` | admin: plain; else `<username>-…` | every Project row and data-root entry |+ * | `agent` | a member of `:p` | snake_case | the Project's Agent rows and folders |+ * | `benchmark` | the owner of `:p` | kebab-case | the Project's Benchmark folders |+ * | `org` | a member of `:p`, company mode on | `co_…` | nothing (the dialog's list) |+ * | `channel` | a member of `:p`, company mode on | `ch_…` | nothing (the dialog's list) |+ *+ * A Project is not inside a Project, but its dialog is opened from one, and that Project's+ * default model is the model the user has configured: the path names it. Anyone signed in+ * may create a Project, so membership of the Project whose model is spent is the only gate.+ * The ids avoided are the names the kind's create route refuses with 409, read as names only —+ * not the list views, which skip a folder with no config that the create route still refuses,+ * and open every Agent and Benchmark to answer. For a Project that is every id on the server.+ * None of them reaches the prompt, only the collision suffix. `org` and `channel` delegate to+ * the organization service, recorded as the organization's.+ */+import { Hono } from "hono";+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";+import type { SemanticIdKind } from "../../api/types.js";+import type { AppEnv } from "../../auth/middleware.js";+import type { Log } from "../../hmr/capabilities.js";+import type { AgentLifecycle, Benchmarks } from "../../mechanisms/agents.js";+import type { Errors } from "../../mechanisms/observability.js";+import type { Access, ProjectConfigStore, ProjectLifecycle } from "../../mechanisms/projects.js";+import type { Settings } from "../../mechanisms/settings.js";+import type { OrgService } from "../../runtime/organization/service.js";+import type { UtilityCompletion } from "../../services/project-config-service.js";+import { SEMANTIC_ID_RULES, projectIdRule } from "../../services/semantic-id.js";+import { suggestSemanticId } from "../../services/semantic-id-suggest.js";+import { HttpError } from "../errors.js";+import {+ optionalStringArray,+ readJson,+ requireEnum,+ requireString,+ requireValidId,+} from "../validate.js";++const KINDS: readonly SemanticIdKind[] = ["project", "agent", "benchmark", "org", "channel"];++/** What this route group reaches — declared here, at the consumer. */+export interface SuggestIdRouteDeps {+ access: Pick<Access, "requireProjectAccess" | "requireProjectOwner">;+ projects: Pick<ProjectLifecycle, "takenProjectIds">;+ agents: Pick<AgentLifecycle, "takenAgentIds">;+ benchmarks: Pick<Benchmarks, "takenIds">;+ orgService: Pick<OrgService, "suggestId">;+ settings: Pick<Settings, "getCompanyMode">;+ completeOnce: (projectId: string, prompt: string) => Promise<UtilityCompletion>;+ /** One model dead end of a Project, Agent or Benchmark proposal, for the log and the errors panel. */+ recordFailure: (projectId: string, detail: string) => void;+}++export function suggestIdRoutes(deps: SuggestIdRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.post("/", async (c) => {+ const projectId = requireValidId(c, "projectId");+ const user = c.var.user;+ deps.access.requireProjectAccess(user.userId, projectId);+ const body = await readJson(c);+ // The mission or a description may stand in for a name nobody typed yet.+ const name = requireString(body, "name", { minLen: 1, maxLen: 4000 });+ const kind = requireEnum(body, "kind", KINDS);+ const taken = optionalStringArray(body, "taken");++ if (kind === "org" || kind === "channel") {+ if (!deps.settings.getCompanyMode()) {+ throw new HttpError(404, "company_mode_off", "Company mode is turned off on this server.");+ }+ return c.json(+ await deps.orgService.suggestId(projectId, {+ name,+ kind,+ ...(taken !== undefined ? { taken } : {}),+ }),+ );+ }++ // Writing a Benchmark is Project management — owner only, as its create route demands.+ if (kind === "benchmark") deps.access.requireProjectOwner(user.userId, projectId);+ const reserved =+ kind === "project"+ ? await deps.projects.takenProjectIds()+ : kind === "agent"+ ? await deps.agents.takenAgentIds(projectId)+ : await deps.benchmarks.takenIds(projectId);+ const res = await suggestSemanticId(+ { completeOnce: deps.completeOnce, recordFailure: deps.recordFailure },+ projectId,+ {+ name,+ kind,+ rule: kind === "project" ? projectIdRule(user) : SEMANTIC_ID_RULES[kind],+ taken: taken ?? [],+ reserved,+ },+ );+ return c.json(res);+ });++ return app;+}++@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "SuggestIdRoutes.routes",+ prefix: "/api/projects/:projectId/suggest-id",+ auth: "user",+ order: 146,+ },+ ],+ },+})+export class SuggestIdRoutes {+ @Use() private readonly access!: Access;+ @Use() private readonly projects!: ProjectLifecycle;+ @Use() private readonly projectConfig!: ProjectConfigStore;+ @Use() private readonly agents!: AgentLifecycle;+ @Use() private readonly benchmarks!: Benchmarks;+ @Use() private readonly orgService!: OrgService;+ @Use() private readonly settings!: Settings;+ @Use() private readonly errors!: Errors;+ @Use() private readonly log!: Log;+ @Bind("SuggestIdRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = suggestIdRoutes({+ access: this.access,+ projects: this.projects,+ agents: this.agents,+ benchmarks: this.benchmarks,+ orgService: this.orgService,+ settings: this.settings,+ completeOnce: (projectId, prompt) => this.projectConfig.completeOnce(projectId, prompt),+ recordFailure: (projectId, detail) => {+ this.log.line(`id suggestion fell back for ${projectId}: ${detail}`);+ this.errors.record({+ source: "id_suggest",+ code: "id_suggest_failed",+ kind: "expected",+ ctx: { projectId },+ err: new Error(detail),+ });+ },+ });+ }+}diff --git a/packages/server/src/mechanisms/agents.ts b/packages/server/src/mechanisms/agents.tsindex 05065830..077f41d2 100644--- a/packages/server/src/mechanisms/agents.ts+++ b/packages/server/src/mechanisms/agents.ts@@ -96,6 +96,8 @@ export abstract class Memory extends Interface<{/** Benchmarks: the mechanism BenchmarkService implements. */export abstract class Benchmarks extends Interface<{list(projectId: string): Promise<BenchmarksResponse>;+ /** Every id `create` refuses as taken, as names only, including a folder that does not list. */+ takenIds(projectId: string): Promise<string[]>;create(projectId: string, input: BenchmarkCreateInput): Promise<BenchmarkSummary>;remove(projectId: string, benchmarkId: string): Promise<void>;listCases(projectId: string, benchmarkId: string): Promise<BenchmarkCasesResponse>;@@ -119,6 +121,8 @@ export abstract class Benchmarks extends Interface<{/** AgentLifecycle: the mechanism AgentService implements. */export abstract class AgentLifecycle extends Interface<{listAgents(projectId: string): Promise<AgentListItem[]>;+ /** Every id `createAgent` refuses as taken, as names only, including a folder that does not list. */+ takenAgentIds(projectId: string): Promise<string[]>;deleteAgent(projectId: string, agentId: string): Promise<void>;createAgent(projectId: string,diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.tsindex 67437381..b03932bb 100644--- a/packages/server/src/mechanisms/projects.ts+++ b/packages/server/src/mechanisms/projects.ts@@ -88,6 +88,8 @@ export abstract class ProjectLifecycle extends Interface<{accessibleProjectIds(userId: string): string[];listProjects(userId: string): Promise<ProjectSummary[]>;createProject(owner: UserRow, projectId: string, name?: string): Promise<ProjectSummary>;+ /** Every id `createProject` refuses as taken, as names only: the rows and the data root's entries. */+ takenProjectIds(): Promise<string[]>;provisionInitialProject(user: UserRow, isAdmin: boolean): Promise<void>;renameProject(userId: string, projectId: string, name: string): Promise<ProjectSummary>;deleteProject(userId: string, projectId: string): Promise<void>;diff --git a/packages/server/src/organization/semantic-id.ts b/packages/server/src/organization/semantic-id.tsdeleted file mode 100644index cc1b3822..00000000--- a/packages/server/src/organization/semantic-id.ts+++ /dev/null@@ -1,112 +0,0 @@-/**- * A semantic id derived from a display name without a model (pure, unit tested): the ASCII- * fallback of `POST /organizations/suggest-id`, and the sanitizer every model answer passes- * through before it is offered. Diacritics are folded (`Café` → `cafe`), every run of- * anything but a letter or digit becomes one underscore, and the result is lowercased. The- * kind's prefix is then put in front — `co_` for an organization, `ch_` for a channel — so a- * suggested id says what it names and starts with a letter as the rule demands; a core that- * already carries the prefix is not prefixed twice. A name with no ASCII letters or digits- * at all (a Chinese name) yields null: nothing mechanical can name it, and that is exactly- * the case the model exists for. When the model cannot name it either, `placeholderSemanticId`- * is the floor — a valid, dated, obviously-temporary id, so the dialog is never left with- * nothing to put in the box.- */-import { SEMANTIC_ID_PATTERN } from "../services/ids.js";--export type SemanticIdKind = "org" | "channel";--/**- * The prefix every generated id carries, by kind. A convention, not a rule the server- * enforces: an id typed by hand is accepted as written, and ids that predate the convention- * keep working.- */-export const KIND_PREFIX: Record<SemanticIdKind, string> = { org: "co_", channel: "ch_" };--const MAX_LENGTH = 64;--/** The ASCII core of a name: folded, lowercased, `_`-joined; "" when nothing survives. */-function asciiCore(name: string): string {- return name- .normalize("NFKD")- .replace(/[̀-ͯ]/g, "")- .toLowerCase()- .replace(/[^a-z0-9]+/g, "_")- .replace(/^_+|_+$/g, "");-}--/** `base`, or the first `base_2`, `base_3`, … that `taken` does not hold; the suffix never pushes the id past the length cap. */-export function uniqueSemanticId(base: string, taken: Iterable<string>): string {- const used = new Set(taken);- if (!used.has(base)) return base;- for (let n = 2; ; n += 1) {- const suffix = `_${n}`;- const candidate = `${base.slice(0, MAX_LENGTH - suffix.length)}${suffix}`;- if (!used.has(candidate)) return candidate;- }-}--/** The core with its kind's prefix in front, or unchanged when it already starts with it. */-export function prefixSemanticId(core: string, kind: SemanticIdKind): string {- const prefix = KIND_PREFIX[kind];- return core.startsWith(prefix) ? core : `${prefix}${core}`;-}--/**- * A valid semantic id for a name, or null when the name carries nothing an ASCII id can be- * built from. Never returns an id in `taken`.- */-export function fallbackSemanticId(- name: string,- kind: SemanticIdKind,- taken: Iterable<string> = [],-): string | null {- const core = asciiCore(name);- if (core === "") return null;- // Prefix first, then cap: the prefix is the part that must survive a long name.- const id = prefixSemanticId(core, kind).slice(0, MAX_LENGTH).replace(/_+$/, "");- if (!SEMANTIC_ID_PATTERN.test(id)) return null;- return uniqueSemanticId(id, taken);-}--/**- * What a model's answer becomes: its first line, stripped of quotes and code marks, run- * through the same folding and prefixing as a name — so a model that answers `research_lab`- * yields `co_research_lab`, one that answers `` `Research Lab` `` yields the same, one that- * answers `co_research_lab` is not prefixed twice, and one that answers in Chinese yields- * null and the caller falls back.- */-export function sanitizeSuggestedId(- answer: string,- kind: SemanticIdKind,- taken: Iterable<string> = [],-): string | null {- const line = answer- .split("\n")- .map((l) => l.trim())- .find((l) => l !== "");- if (line === undefined) return null;- return fallbackSemanticId(line.replace(/^[`"'“”‘’]+|[`"'“”‘’.]+$/g, ""), kind, taken);-}--/** `yyyymmdd` in the host's own local date, the stamp a placeholder id carries. */-function dateStamp(now: Date): string {- const pad = (n: number): string => String(n).padStart(2, "0");- return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;-}--/**- * The id a name that neither the model nor the ASCII fallback can name gets: `co_org_<yyyymmdd>`- * / `ch_channel_<yyyymmdd>`, made unique against `taken`. It names nothing — that is the point.- * It is valid, so the dialog can go on, and it reads as temporary at a glance, so the surface- * that fills it in can ask for a meaningful name in its place. Refusing instead would leave the- * user of a Chinese-named organization with no model configured staring at a dialog that- * cannot be completed.- */-export function placeholderSemanticId(- kind: SemanticIdKind,- taken: Iterable<string> = [],- now: Date = new Date(),-): string {- const core = kind === "org" ? "org" : "channel";- return uniqueSemanticId(prefixSemanticId(`${core}_${dateStamp(now)}`, kind), taken);-}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex a2387d07..fe37d68b 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -115,6 +115,7 @@ import { HmrRoutes } from "./hmr/routes.js";import { EventsRoutes } from "./http/routes/events.js";import { PluginRegistryRoutes, PluginRoutes } from "./http/routes/plugins.js";import { InstalledPluginRoutes } from "./http/routes/plugins-installed.js";+import { SuggestIdRoutes } from "./http/routes/suggest-id.js";import { TerminalModule } from "./terminal/manager.js";import { SessionApiRoutes } from "./http/routes/sessions.js";import { Admin, Auth, AuthSessions, Users } from "./mechanisms/identity.js";@@ -388,6 +389,7 @@ export class CompanyModule {}PluginRoutes,PluginRegistryRoutes,InstalledPluginRoutes,+ SuggestIdRoutes,],exports: [Http, WebShell, UpdateCheck],})diff --git a/packages/server/src/runtime/error-recorder.ts b/packages/server/src/runtime/error-recorder.tsindex 2d74342a..5a59d1bd 100644--- a/packages/server/src/runtime/error-recorder.ts+++ b/packages/server/src/runtime/error-recorder.ts@@ -70,7 +70,8 @@ export type ErrorSource =| "subagent"| "process"| "schedule"- | "messaging";+ | "messaging"+ | "id_suggest";/** Error classification: see file header — the criterion is "does a human need to step in". */export type ErrorKind = "expected" | "unexpected";diff --git a/packages/server/src/runtime/organization/service.ts b/packages/server/src/runtime/organization/service.tsindex 3ff8e89c..d1002bcc 100644--- a/packages/server/src/runtime/organization/service.ts+++ b/packages/server/src/runtime/organization/service.ts@@ -11,7 +11,6 @@ import type {OrgCalendarResponse,OrgCalendarUpsertRequest,OrgCalendarWriteResponse,- SemanticIdSuggestReason,SemanticIdSuggestRequest,SemanticIdSuggestResponse,OrgChannelCreateRequest,@@ -106,11 +105,8 @@ import {userPrincipal,} from "../../organization/principal.js";import { isValidTimeZone, zonedDate, zonedDayRange } from "../../organization/zoned.js";-import {- fallbackSemanticId,- placeholderSemanticId,- sanitizeSuggestedId,-} from "../../organization/semantic-id.js";+import { SEMANTIC_ID_RULES } from "../../services/semantic-id.js";+import { suggestSemanticId } from "../../services/semantic-id-suggest.js";import { SEMANTIC_ID_PATTERN } from "../../services/ids.js";import { enabledMessagingChannel } from "../messaging/enabled-channel.js";import { latestSlotAt, nextSlotAfter, slotInWindow } from "../schedule-file.js";@@ -220,70 +216,31 @@ export class OrganizationService {/*** A semantic id for a display name (the organization and channel dialogs name the thing- * first and derive the id). The Project's default model translates the name into one- * snake_case English identifier — the common case is a Chinese name, which nothing- * mechanical can transliterate — and the ASCII slug of the name answers whenever the model- * is unavailable, refuses or answers with something no id can be built from. A name that- * neither path can name gets a dated placeholder and the reason it fell that far: the- * dialog fills the box and asks for a meaningful name in its place, which is a better- * answer than a refusal that leaves the box empty and the user with nothing to type.+ * first and derive the id): the shared proposal (semantic-id-suggest.ts) with the kind's+ * prefix, the ids the dialog passed in to avoid, and every model dead end recorded as the+ * organization's.*/async suggestId(projectId: string,req: SemanticIdSuggestRequest,): Promise<SemanticIdSuggestResponse> {- const taken = req.taken ?? [];- // No model bound at all: nothing more specific can be said than what the name itself lacks.- let reason: SemanticIdSuggestReason = "no_ascii";- const complete = this.deps.completeOnce;- if (complete !== undefined) {- const proposed = await this.modelSemanticId(complete, projectId, req, taken);- if (proposed.id !== undefined) return { id: proposed.id, source: "model" };- reason = proposed.reason;- }- const id = fallbackSemanticId(req.name, req.kind, taken);- if (id !== null) return { id, source: "fallback" };- return { id: placeholderSemanticId(req.kind, taken), source: "placeholder", reason };- }-- /**- * The model half of a proposal: the id it produced, or the reason there is none. An answer- * that does not sanitize to an id buys one retry with the format rule spelled out — a model- * that explained itself the first time usually complies when told to answer with the- * identifier alone — while a request that failed outright is not repeated, since nothing- * about the second ask would go differently. Every dead end is recorded, so the errors panel- * can say why the button produced a placeholder instead of a name.- */- private async modelSemanticId(- complete: NonNullable<OrgDeps["completeOnce"]>,- projectId: string,- req: SemanticIdSuggestRequest,- taken: readonly string[],- ): Promise<- { id: string; reason?: undefined } | { id?: undefined; reason: SemanticIdSuggestReason }- > {- const base = semanticIdPrompt(req);- let lastAnswer = "";- for (const prompt of [base, `${base} ${SEMANTIC_ID_RETRY_RULE}`]) {- const res = await complete(projectId, prompt);- if (!res.ok) {- this.recordIdSuggestFailure(projectId, `${req.kind} id for "${req.name}": ${res.error}`);- return { reason: res.cause === "no_model" ? "no_default_model" : "model_failed" };- }- const id = sanitizeSuggestedId(res.text, req.kind, taken);- if (id !== null) return { id };- lastAnswer = res.text;- }- this.recordIdSuggestFailure(+ return suggestSemanticId(+ {+ completeOnce: this.deps.completeOnce,+ recordFailure: (p, detail) => this.recordIdSuggestFailure(p, detail),+ },projectId,- `${req.kind} id for "${req.name}": no id could be built from the model's answer: ${lastAnswer.trim()}`,+ {+ name: req.name,+ kind: req.kind,+ rule: SEMANTIC_ID_RULES[req.kind],+ taken: req.taken ?? [],+ },);- return { reason: "unusable_answer" };}/** One dead end of an id proposal, in the log and in the Project's errors panel. */- private recordIdSuggestFailure(projectId: string, detail: string): void {- const message = detail.slice(0, ID_SUGGEST_FAILURE_MAX);+ private recordIdSuggestFailure(projectId: string, message: string): void {this.deps.log?.(`org: id suggestion fell back for ${projectId}: ${message}`);this.deps.errors.record({source: "organization",@@ -2529,17 +2486,6 @@ function lastClosedAt(doc: TicketDoc): string | null {return null;}-/**- * Appended to the prompt on the one retry an unusable answer buys. The first ask already- * describes the format; a model that answered with prose anyway is told, in one sentence, that- * the answer IS the identifier — which is the instruction such a model complies with.- */-const SEMANTIC_ID_RETRY_RULE =- "Answer with the identifier only — ASCII lowercase letters, digits and underscores, nothing else.";--/** How much of a failed proposal's detail reaches the log and the errors panel. */-const ID_SUGGEST_FAILURE_MAX = 300;-/** The first non-empty line of a model's answer, stripped of the marks a model wraps one in. */function firstLine(answer: string): string {const line = answer@@ -2569,27 +2515,6 @@ function ticketSlugPrompt(title: string): string {].join(" ");}-/**- * The prompt behind a model-backed semantic id: the model translates a display name into- * one snake_case English identifier — the semantic core only, since `sanitizeSuggestedId`- * puts the kind's prefix (`co_` / `ch_`) in front of whatever comes back. Examples in both- * scripts, the taken ids named so the answer does not collide, and no room for prose;- * anything that does not survive the sanitizer falls back to the ASCII slug.- */-function semanticIdPrompt(req: SemanticIdSuggestRequest): string {- const taken = (req.taken ?? []).join(", ");- return [- "You produce identifiers. Given a display name, answer with ONE snake_case ASCII identifier:",- "lowercase letters, digits and underscores, starting with a letter, 2–40 characters, made of",- "English words that carry the name's meaning (translate a non-English name), no explanation,",- "nothing else. Examples: Plugin Marketplace → plugin_marketplace; 科研论文公司 →",- "research_paper_lab; 市场推广 → marketing; Site → site.",- "Do not add any prefix of your own; one is added to your answer.",- ...(taken !== "" ? [`Those answers are taken, prefix included: ${taken}.`] : []),- `Name: ${req.name}`,- ].join(" ");-}-/** The AGENTS.md written for an Agent created as an employee: who it is in this organization and where the handbook is. */export function employeeBrief(input: {orgId: string;diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.tsindex 5059c4a0..a8c377e0 100644--- a/packages/server/src/services/agent-service.ts+++ b/packages/server/src/services/agent-service.ts@@ -167,6 +167,21 @@ export class AgentService implements AgentLifecycle {);}+ /**+ * Every id `createAgent` refuses as taken, as names only: the index rows and every entry under+ * `agents/`. Unlike `listAgents`, this includes a folder with no `system_config.yaml`, and it+ * opens no Agent.+ */+ async takenAgentIds(projectId: string): Promise<string[]> {+ let entries: string[] = [];+ try {+ entries = await fs.readdir(agentsDir(this.root, projectId));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ }+ return [...new Set([...this.agents.list(projectId).map((r) => r.agentId), ...entries])];+ }+/** Number of vault keys (falls back to 0 on read failure). */private async vaultKeyCount(projectId: string, agentId: string): Promise<number> {try {diff --git a/packages/server/src/services/benchmark-service.ts b/packages/server/src/services/benchmark-service.tsindex c5df890a..7a57525b 100644--- a/packages/server/src/services/benchmark-service.ts+++ b/packages/server/src/services/benchmark-service.ts@@ -257,6 +257,20 @@ export class BenchmarkService implements Benchmarks {return { benchmarks };}+ /**+ * Every id `create` refuses as taken, as names only: each entry under `benchmarks/`. Unlike+ * `list`, this includes a directory with no `benchmark_config.toml` (the debris of one deleted+ * mid-evaluation), and it reads no config and no scoreboard.+ */+ async takenIds(projectId: string): Promise<string[]> {+ try {+ return await fs.readdir(benchmarksDir(this.root, projectId));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw error;+ }+ }+/*** Creates `benchmarks/<id>/` in the layout the evaluation Skills read: `benchmark_config.toml`* (title, description, runs, status), `scoreboard.yaml` with an empty evaluations list, anddiff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.tsindex 64500dfb..980e21f1 100644--- a/packages/server/src/services/project-service.ts+++ b/packages/server/src/services/project-service.ts@@ -174,6 +174,21 @@ export class ProjectService implements ProjectLifecycle {};}+ /**+ * Every id `createProject` refuses as taken, as names only: every row, and every name already+ * under the data root, where the Project's directory would go — a directory with no row+ * included, which no Project list shows.+ */+ async takenProjectIds(): Promise<string[]> {+ let entries: string[] = [];+ try {+ entries = await fs.readdir(this.root);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ }+ return [...new Set([...this.projects.listAll().map((p) => p.projectId), ...entries])];+ }+/*** Initial Project provisioned at signup:* the built-in admin adopts `default_project` (if the directory already exists,diff --git a/packages/server/src/services/semantic-id-suggest.ts b/packages/server/src/services/semantic-id-suggest.tsnew file mode 100644index 00000000..5940c9bb--- /dev/null+++ b/packages/server/src/services/semantic-id-suggest.ts@@ -0,0 +1,145 @@+/**+ * A semantic id for a display name, whatever kind of object the create dialog names: the one+ * proposal every `suggest-id` answer comes from. The Project's default model translates the+ * name into one English identifier in the kind's spelling — the common case is a Chinese name,+ * which nothing mechanical can transliterate — and the ASCII slug of the name answers whenever+ * the model is unavailable, refuses or answers with something no id can be built from. A name+ * that neither path can name gets a dated placeholder and the reason it fell that far: the+ * dialog fills the box and asks for a meaningful name in its place, which is a better answer+ * than a refusal that leaves the box empty and the user with nothing to type.+ *+ * The caller decides what surrounds the proposal and passes it in: the kind's rule (a+ * non-admin's Project rule depends on who asks), the ids to avoid, where a dead end is+ * recorded. The completion itself belongs to no Session and is not metered.+ */+import type {+ SemanticIdKind,+ SemanticIdSuggestReason,+ SemanticIdSuggestResponse,+} from "../api/types.js";+import type { UtilityCompletion } from "./project-config-service.js";+import { fallbackSemanticId, placeholderSemanticId, sanitizeSuggestedId } from "./semantic-id.js";+import type { SemanticIdRule } from "./semantic-id.js";++export interface SemanticIdSuggestDeps {+ /** One short completion on the Project's default model; absent when nothing can be asked at all. */+ completeOnce?: ((projectId: string, prompt: string) => Promise<UtilityCompletion>) | undefined;+ /** Records one dead end of the model half (already truncated), for the log and the errors panel. */+ recordFailure: (projectId: string, detail: string) => void;+}++export interface SemanticIdSuggestInput {+ /** The display name (or whatever else names the thing yet). */+ name: string;+ /** For the failure record: which kind of id was asked for. */+ kind: SemanticIdKind;+ rule: SemanticIdRule;+ /** Ids to avoid that the prompt also names: the few a dialog passed in. */+ taken: readonly string[];+ /**+ * Ids to avoid that the prompt does not name: the server's own view of what exists, which+ * may be long and is not the model's business (every Project id on the server, say).+ */+ reserved?: Iterable<string>;+}++/**+ * Appended to the prompt on the one retry an unusable answer buys. The first ask already+ * describes the format; a model that answered with prose anyway is told, in one sentence, that+ * the answer IS the identifier — which is the instruction such a model complies with.+ */+const SEMANTIC_ID_RETRY_RULE = {+ _: "Answer with the identifier only — ASCII lowercase letters, digits and underscores, nothing else.",+ "-": "Answer with the identifier only — ASCII lowercase letters, digits and hyphens, nothing else.",+} as const;++/** How much of a failed proposal's detail reaches the log and the errors panel. */+const ID_SUGGEST_FAILURE_MAX = 300;++export async function suggestSemanticId(+ deps: SemanticIdSuggestDeps,+ projectId: string,+ input: SemanticIdSuggestInput,+): Promise<SemanticIdSuggestResponse> {+ const avoid = [...input.taken, ...(input.reserved ?? [])];+ // No model bound at all: nothing more specific can be said than what the name itself lacks.+ let reason: SemanticIdSuggestReason = "no_ascii";+ if (deps.completeOnce !== undefined) {+ const proposed = await modelSemanticId(deps, deps.completeOnce, projectId, input, avoid);+ if (proposed.id !== undefined) return { id: proposed.id, source: "model" };+ reason = proposed.reason;+ }+ const id = fallbackSemanticId(input.name, input.rule, avoid);+ if (id !== null) return { id, source: "fallback" };+ return { id: placeholderSemanticId(input.rule, avoid), source: "placeholder", reason };+}++/**+ * The model half of a proposal: the id it produced, or the reason there is none. An answer+ * that does not sanitize to an id buys one retry with the format rule spelled out — a model+ * that explained itself the first time usually complies when told to answer with the+ * identifier alone — while a request that failed outright is not repeated, since nothing+ * about the second ask would go differently. Every dead end is recorded, so the errors panel+ * can say why the button produced a placeholder instead of a name.+ */+async function modelSemanticId(+ deps: SemanticIdSuggestDeps,+ complete: NonNullable<SemanticIdSuggestDeps["completeOnce"]>,+ projectId: string,+ input: SemanticIdSuggestInput,+ avoid: readonly string[],+): Promise<+ { id: string; reason?: undefined } | { id?: undefined; reason: SemanticIdSuggestReason }+> {+ const record = (detail: string) =>+ deps.recordFailure(+ projectId,+ `${input.kind} id for "${input.name}": ${detail}`.slice(0, ID_SUGGEST_FAILURE_MAX),+ );+ const base = semanticIdPrompt(input);+ let lastAnswer = "";+ for (const prompt of [base, `${base} ${SEMANTIC_ID_RETRY_RULE[input.rule.separator]}`]) {+ const res = await complete(projectId, prompt);+ if (!res.ok) {+ record(res.error);+ return { reason: res.cause === "no_model" ? "no_default_model" : "model_failed" };+ }+ const id = sanitizeSuggestedId(res.text, input.rule, avoid);+ if (id !== null) return { id };+ lastAnswer = res.text;+ }+ record(`no id could be built from the model's answer: ${lastAnswer.trim()}`);+ return { reason: "unusable_answer" };+}++/**+ * The ask: one identifier in the kind's spelling, made of English words, with the kind's own+ * examples. A kind whose ids carry a prefix tells the model not to add one; the ids a dialog+ * passed in are named so the model can pick different words rather than collect a `_2`.+ */+function semanticIdPrompt(input: SemanticIdSuggestInput): string {+ const { rule } = input;+ const taken = input.taken.join(", ");+ const format =+ rule.separator === "_"+ ? [+ "You produce identifiers. Given a display name, answer with ONE snake_case ASCII identifier:",+ "lowercase letters, digits and underscores, starting with a letter, 2–40 characters, made of",+ ]+ : [+ "You produce identifiers. Given a display name, answer with ONE kebab-case ASCII identifier:",+ "lowercase letters, digits and hyphens, 2–40 characters, made of",+ ];+ return [+ ...format,+ "English words that carry the name's meaning (translate a non-English name), no explanation,",+ `nothing else. Examples: ${rule.examples}`,+ ...(rule.prefix !== ""+ ? ["Do not add any prefix of your own; one is added to your answer."]+ : []),+ ...(taken !== ""+ ? [`Those answers are taken${rule.prefix !== "" ? ", prefix included" : ""}: ${taken}.`]+ : []),+ `Name: ${input.name}`,+ ].join(" ");+}diff --git a/packages/server/src/services/semantic-id.ts b/packages/server/src/services/semantic-id.tsnew file mode 100644index 00000000..ac8f7d91--- /dev/null+++ b/packages/server/src/services/semantic-id.ts@@ -0,0 +1,227 @@+/**+ * A semantic id derived from a display name without a model (pure, unit tested): the ASCII+ * fallback of `suggest-id`, and the sanitizer every model answer passes through before it is+ * offered. Diacritics are folded (`Café` → `cafe`), every run of anything but a letter or digit+ * becomes one separator, and the result is lowercased. What the id then has to look like is+ * the kind's, and one table says it for every kind a create dialog names:+ *+ * | kind | prefix | words joined | the id the create route accepts |+ * | ----------- | -------------------- | ------------ | ---------------------------------------- |+ * | `org` | `co_` | `_` | `^[a-z][a-z0-9_]{1,63}$` |+ * | `channel` | `ch_` | `_` | `^[a-z][a-z0-9_]{1,63}$` |+ * | `project` | none (admin) | `_` | `^[a-z][a-z0-9_]{1,63}$` |+ * | `project` | `<username>-` (user) | `_` | `<username>-[a-z0-9_]+`, 64 at most |+ * | `agent` | none | `_` | `^[a-z][a-z0-9_]{1,63}$` |+ * | `benchmark` | none | `-` | letters, digits, `_` and `-`; 100 at most |+ *+ * The organization's and the channel's prefix says what an id names and makes every core a+ * valid id; a core that already carries it is not prefixed twice. A non-admin's Project id+ * lives in its owner's namespace, so that prefix is the username the route already demands,+ * not a convention. A Benchmark id is kebab-case, like the ones the evaluation Skills write.+ * The prefixes are a generator's convention, not a rule the server enforces: an id typed by+ * hand is accepted as written, and ids that predate them keep working.+ *+ * A core the kind still rejects — an unprefixed id that would start with a digit, or a+ * one-letter one — is tried once more behind the kind's noun (`3D Viewer` → `agent_3d_viewer`),+ * which keeps the words rather than discarding a name that did carry ASCII. A name with no+ * ASCII letters or digits at all (a Chinese name) yields null: nothing mechanical can name it,+ * and that is exactly the case the model exists for. When the model cannot name it either,+ * `placeholderSemanticId` is the floor — a valid, dated, obviously-temporary id, so the dialog+ * is never left with nothing to put in the box.+ */+import { isValidId } from "@prismshadow/penguin-core";+import type { SemanticIdKind } from "../api/types.js";+import { PROJECT_ID_MAX_LENGTH, PROJECT_SUFFIX_PATTERN, SEMANTIC_ID_PATTERN } from "./ids.js";++/** What a kind's id looks like: everything the generator, the sanitizer and the prompt need. */+export interface SemanticIdRule {+ /** Put in front of every generated id; "" for none. */+ prefix: string;+ /** What joins the words of an id: `_` (snake_case) or `-` (kebab-case). */+ separator: "_" | "-";+ /** The longest id the generator produces (never longer than the create route accepts). */+ maxLength: number;+ /** Whether the create route accepts an id. */+ accepts: (id: string) => boolean;+ /** The word a placeholder carries, and the word a core the rule rejects is put behind. */+ noun: string;+ /** The prompt's examples, in this kind's own spelling (see semantic-id-suggest.ts). */+ examples: string;+}++const snakeCaseId = (id: string): boolean => SEMANTIC_ID_PATTERN.test(id);++const SNAKE_EXAMPLES =+ "Plugin Marketplace → plugin_marketplace; 科研论文公司 → research_paper_lab; 市场推广 → marketing; Site → site.";++/** The kind table (see the module header); a non-admin's Project rule is {@link projectIdRule}. */+export const SEMANTIC_ID_RULES: Record<SemanticIdKind, SemanticIdRule> = {+ org: {+ prefix: "co_",+ separator: "_",+ maxLength: 64,+ accepts: snakeCaseId,+ noun: "org",+ examples: SNAKE_EXAMPLES,+ },+ channel: {+ prefix: "ch_",+ separator: "_",+ maxLength: 64,+ accepts: snakeCaseId,+ noun: "channel",+ examples: SNAKE_EXAMPLES,+ },+ project: {+ prefix: "",+ separator: "_",+ maxLength: 64,+ accepts: snakeCaseId,+ noun: "project",+ examples:+ "Plugin Marketplace → plugin_marketplace; 科研论文项目 → research_papers; 官网改版 → website_redesign; Site → site.",+ },+ agent: {+ prefix: "",+ separator: "_",+ maxLength: 64,+ accepts: snakeCaseId,+ noun: "agent",+ examples:+ "Report Writer → report_writer; 金融助手 → finance_copilot; 深度研究报告智能体 → deep_research_reporter; Notes → notes.",+ },+ benchmark: {+ prefix: "",+ separator: "-",+ maxLength: 64,+ accepts: (id) => id.length <= 100 && isValidId(id),+ noun: "benchmark",+ examples:+ "Report Writing → report-writing; 代码审查能力 → code-review; 深度研究 v2 → deep-research-v2; SQL → sql.",+ },+};++/**+ * A Project id as `userId` may create it: the admin's is a plain semantic id, anyone else's is+ * `<userId>-<suffix>` within the length cap — the rule `POST /api/projects` enforces.+ */+export function projectIdRule(user: { userId: string; isAdmin: boolean }): SemanticIdRule {+ const base = SEMANTIC_ID_RULES.project;+ if (user.isAdmin) return base;+ const prefix = `${user.userId}-`;+ return {+ ...base,+ prefix,+ maxLength: PROJECT_ID_MAX_LENGTH,+ accepts: (id) =>+ id.startsWith(prefix) &&+ PROJECT_SUFFIX_PATTERN.test(id.slice(prefix.length)) &&+ id.length <= PROJECT_ID_MAX_LENGTH,+ };+}++/** The ASCII core of a name: folded, lowercased, joined by `separator`; "" when nothing survives. */+function asciiCore(name: string, separator: "_" | "-"): string {+ return name+ .normalize("NFKD")+ .replace(/[̀-ͯ]/g, "")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, separator)+ .replace(/^[_-]+|[_-]+$/g, "");+}++/**+ * `base`, or the first `base_2`, `base_3`, … (`base-2` for a kebab-case kind) that `taken` does+ * not hold; the suffix never pushes the id past the length cap.+ */+export function uniqueSemanticId(+ base: string,+ taken: Iterable<string>,+ separator: "_" | "-",+ maxLength: number,+): string {+ const used = new Set(taken);+ if (!used.has(base)) return base;+ for (let n = 2; ; n += 1) {+ const suffix = `${separator}${n}`;+ const candidate = `${base.slice(0, maxLength - suffix.length)}${suffix}`;+ if (!used.has(candidate)) return candidate;+ }+}++/** The core with the rule's prefix in front, or unchanged when it already starts with it. */+export function prefixSemanticId(core: string, rule: SemanticIdRule): string {+ return core.startsWith(rule.prefix) ? core : `${rule.prefix}${core}`;+}++/** The prefixed core capped at the kind's length — prefix first, so it survives a long name — with no trailing separator. */+function capped(core: string, rule: SemanticIdRule): string {+ return prefixSemanticId(core, rule)+ .slice(0, rule.maxLength)+ .replace(/[_-]+$/, "");+}++/**+ * A valid semantic id for a name, or null when the name carries nothing an ASCII id can be+ * built from. Never returns an id in `taken`.+ */+export function fallbackSemanticId(+ name: string,+ rule: SemanticIdRule,+ taken: Iterable<string> = [],+): string | null {+ const core = asciiCore(name, rule.separator);+ if (core === "") return null;+ let id = capped(core, rule);+ if (!rule.accepts(id)) id = capped(`${rule.noun}${rule.separator}${core}`, rule);+ if (!rule.accepts(id)) return null;+ return uniqueSemanticId(id, taken, rule.separator, rule.maxLength);+}++/**+ * What a model's answer becomes: its first line, stripped of quotes and code marks, run+ * through the same folding and prefixing as a name — so a model that answers `research_lab`+ * yields `co_research_lab`, one that answers `` `Research Lab` `` yields the same, one that+ * answers `co_research_lab` is not prefixed twice, and one that answers in Chinese yields+ * null and the caller falls back.+ */+export function sanitizeSuggestedId(+ answer: string,+ rule: SemanticIdRule,+ taken: Iterable<string> = [],+): string | null {+ const line = answer+ .split("\n")+ .map((l) => l.trim())+ .find((l) => l !== "");+ if (line === undefined) return null;+ return fallbackSemanticId(line.replace(/^[`"'“”‘’]+|[`"'“”‘’.]+$/g, ""), rule, taken);+}++/** `yyyymmdd` in the host's own local date, the stamp a placeholder id carries. */+function dateStamp(now: Date): string {+ const pad = (n: number): string => String(n).padStart(2, "0");+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;+}++/**+ * The id a name that neither the model nor the ASCII fallback can name gets: the kind's noun+ * and the date behind its prefix — `co_org_<yyyymmdd>`, `ch_channel_<yyyymmdd>`,+ * `agent_<yyyymmdd>`, `benchmark-<yyyymmdd>` — made unique against `taken`. It names nothing —+ * that is the point. It is valid, so the dialog can go on, and it reads as temporary at a+ * glance, so the surface that fills it in can ask for a meaningful name in its place. Refusing+ * instead would leave the user of a Chinese-named object with no model configured staring at+ * a dialog that cannot be completed.+ */+export function placeholderSemanticId(+ rule: SemanticIdRule,+ taken: Iterable<string> = [],+ now: Date = new Date(),+): string {+ return uniqueSemanticId(+ prefixSemanticId(`${rule.noun}${rule.separator}${dateStamp(now)}`, rule),+ taken,+ rule.separator,+ rule.maxLength,+ );+}diff --git a/packages/server/test/organizations-routes.test.ts b/packages/server/test/organizations-routes.test.tsindex 618a778a..f0506c7c 100644--- a/packages/server/test/organizations-routes.test.ts+++ b/packages/server/test/organizations-routes.test.ts@@ -62,10 +62,6 @@ function fakeService(calls: Call[]): OrganizationService {return { channelId: "site", name: "Site", members: [] };case "startTicket":return { sessionId: "session-x" };- // A proposal that fell all the way through: the route must serve `reason` too, and- // must not turn a name nothing could translate into an error.- case "suggestId":- return { id: "co_org_20260909", source: "placeholder", reason: "no_default_model" };case "handbook":return "# Handbook";case "handbookFiles":@@ -256,31 +252,8 @@ describe("organization routes", () => {});});- it("validates an id proposal and carries the organization's language both ways", async () => {+ it("carries the organization's language both ways", async () => {const base = `/api/projects/${ownerProject}/organizations`;- // The proposal needs no organization, only the Project — and a kind the server knows.- expect((await owner.post(`${base}/suggest-id`, { kind: "org" })).status).toBe(400);- expect((await owner.post(`${base}/suggest-id`, { name: "科研公司" })).status).toBe(400);- expect(- (await owner.post(`${base}/suggest-id`, { name: "科研公司", kind: "team" })).status,- ).toBe(400);- expect(calls).toEqual([]);- const proposal = await owner.post(`${base}/suggest-id`, {- name: "科研公司",- kind: "org",- taken: ["research_lab"],- });- expect(proposal.status).toBe(200);- expect(await proposal.json()).toEqual({- id: "co_org_20260909",- source: "placeholder",- reason: "no_default_model",- });- expect(calls.at(-1)).toEqual({- method: "suggestId",- args: [ownerProject, { name: "科研公司", kind: "org", taken: ["research_lab"] }],- });-expect((await owner.post(base, { orgId: "acme", mission: "x", language: "fr" })).status).toBe(400,);diff --git a/packages/server/test/semantic-id.test.ts b/packages/server/test/semantic-id.test.tsindex 06c04fb3..13864b93 100644--- a/packages/server/test/semantic-id.test.ts+++ b/packages/server/test/semantic-id.test.ts@@ -1,81 +1,91 @@import { describe, expect, it } from "vitest";import {+ SEMANTIC_ID_RULES,fallbackSemanticId,placeholderSemanticId,prefixSemanticId,+ projectIdRule,sanitizeSuggestedId,uniqueSemanticId,-} from "../src/organization/semantic-id.js";+} from "../src/services/semantic-id.js";describe("fallbackSemanticId", () => {it("lowercases, folds diacritics, joins words with underscores and prefixes by kind", () => {- expect(fallbackSemanticId("Plugin Marketplace", "org")).toBe("co_plugin_marketplace");- expect(fallbackSemanticId(" Café--Site!! ", "channel")).toBe("ch_cafe_site");+ expect(fallbackSemanticId("Plugin Marketplace", SEMANTIC_ID_RULES.org)).toBe(+ "co_plugin_marketplace",+ );+ expect(fallbackSemanticId(" Café--Site!! ", SEMANTIC_ID_RULES.channel)).toBe("ch_cafe_site");});it("the prefix is what makes a name starting with a digit a valid id", () => {- expect(fallbackSemanticId("2026 plan", "org")).toBe("co_2026_plan");- expect(fallbackSemanticId("3d", "channel")).toBe("ch_3d");+ expect(fallbackSemanticId("2026 plan", SEMANTIC_ID_RULES.org)).toBe("co_2026_plan");+ expect(fallbackSemanticId("3d", SEMANTIC_ID_RULES.channel)).toBe("ch_3d");});it("a one-character name is already long enough once prefixed", () => {- expect(fallbackSemanticId("x", "org")).toBe("co_x");+ expect(fallbackSemanticId("x", SEMANTIC_ID_RULES.org)).toBe("co_x");});it("does not prefix a core that already carries the prefix", () => {- expect(fallbackSemanticId("co_acme", "org")).toBe("co_acme");- expect(fallbackSemanticId("Ch Site", "channel")).toBe("ch_site");+ expect(fallbackSemanticId("co_acme", SEMANTIC_ID_RULES.org)).toBe("co_acme");+ expect(fallbackSemanticId("Ch Site", SEMANTIC_ID_RULES.channel)).toBe("ch_site");});it("yields null for a name with no ASCII letters or digits", () => {- expect(fallbackSemanticId("科研公司", "org")).toBeNull();- expect(fallbackSemanticId(" ", "org")).toBeNull();- expect(fallbackSemanticId("!!!", "channel")).toBeNull();+ expect(fallbackSemanticId("科研公司", SEMANTIC_ID_RULES.org)).toBeNull();+ expect(fallbackSemanticId(" ", SEMANTIC_ID_RULES.org)).toBeNull();+ expect(fallbackSemanticId("!!!", SEMANTIC_ID_RULES.channel)).toBeNull();});it("keeps the ASCII part of a mixed name", () => {- expect(fallbackSemanticId("科研 Lab 2", "org")).toBe("co_lab_2");+ expect(fallbackSemanticId("科研 Lab 2", SEMANTIC_ID_RULES.org)).toBe("co_lab_2");});it("caps the length at 64 with the prefix kept, and never ends in an underscore", () => {- expect(fallbackSemanticId("a".repeat(70) + " tail words", "org")).toBe(`co_${"a".repeat(61)}`);+ expect(fallbackSemanticId("a".repeat(70) + " tail words", SEMANTIC_ID_RULES.org)).toBe(+ `co_${"a".repeat(61)}`,+ );});it("avoids taken ids with a numeric suffix, compared after prefixing", () => {- expect(fallbackSemanticId("Site", "channel", ["ch_site"])).toBe("ch_site_2");- expect(fallbackSemanticId("Site", "channel", ["ch_site", "ch_site_2"])).toBe("ch_site_3");+ expect(fallbackSemanticId("Site", SEMANTIC_ID_RULES.channel, ["ch_site"])).toBe("ch_site_2");+ expect(fallbackSemanticId("Site", SEMANTIC_ID_RULES.channel, ["ch_site", "ch_site_2"])).toBe(+ "ch_site_3",+ );// The bare core is not the id, so holding it takes nothing.- expect(fallbackSemanticId("Site", "channel", ["site"])).toBe("ch_site");+ expect(fallbackSemanticId("Site", SEMANTIC_ID_RULES.channel, ["site"])).toBe("ch_site");});});describe("prefixSemanticId", () => {it("puts the kind's prefix in front exactly once", () => {- expect(prefixSemanticId("marketing", "channel")).toBe("ch_marketing");- expect(prefixSemanticId("ch_marketing", "channel")).toBe("ch_marketing");- expect(prefixSemanticId("marketing", "org")).toBe("co_marketing");+ expect(prefixSemanticId("marketing", SEMANTIC_ID_RULES.channel)).toBe("ch_marketing");+ expect(prefixSemanticId("ch_marketing", SEMANTIC_ID_RULES.channel)).toBe("ch_marketing");+ expect(prefixSemanticId("marketing", SEMANTIC_ID_RULES.org)).toBe("co_marketing");});});describe("uniqueSemanticId", () => {it("keeps the suffix inside the length cap", () => {const base = "b".repeat(64);- expect(uniqueSemanticId(base, [base])).toBe("b".repeat(62) + "_2");+ expect(uniqueSemanticId(base, [base], "_", 64)).toBe("b".repeat(62) + "_2");});});describe("sanitizeSuggestedId", () => {it("takes the first non-empty line, strips quotes and code marks, and prefixes it", () => {- expect(sanitizeSuggestedId("\n`research_lab`\n", "org")).toBe("co_research_lab");- expect(sanitizeSuggestedId('"Research Lab".', "org")).toBe("co_research_lab");+ expect(sanitizeSuggestedId("\n`research_lab`\n", SEMANTIC_ID_RULES.org)).toBe(+ "co_research_lab",+ );+ expect(sanitizeSuggestedId('"Research Lab".', SEMANTIC_ID_RULES.org)).toBe("co_research_lab");});it("does not double a prefix the model added itself", () => {- expect(sanitizeSuggestedId("co_research_lab", "org")).toBe("co_research_lab");+ expect(sanitizeSuggestedId("co_research_lab", SEMANTIC_ID_RULES.org)).toBe("co_research_lab");});it("returns null for an answer that carries no ASCII", () => {- expect(sanitizeSuggestedId("科研实验室", "org")).toBeNull();+ expect(sanitizeSuggestedId("科研实验室", SEMANTIC_ID_RULES.org)).toBeNull();});});@@ -83,18 +93,95 @@ describe("placeholderSemanticId", () => {const day = new Date(2026, 8, 9); // 2026-09-09, local — the stamp is the host's own date.it("is a valid, dated, obviously-temporary id, prefixed by kind", () => {- expect(placeholderSemanticId("org", [], day)).toBe("co_org_20260909");- expect(placeholderSemanticId("channel", [], day)).toBe("ch_channel_20260909");+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.org, [], day)).toBe("co_org_20260909");+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.channel, [], day)).toBe("ch_channel_20260909");});it("pads a single-digit month and day", () => {- expect(placeholderSemanticId("org", [], new Date(2026, 0, 3))).toBe("co_org_20260103");+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.org, [], new Date(2026, 0, 3))).toBe(+ "co_org_20260103",+ );});it("avoids the ids already taken, so pressing the button twice gives two ids", () => {- expect(placeholderSemanticId("org", ["co_org_20260909"], day)).toBe("co_org_20260909_2");- expect(placeholderSemanticId("org", ["co_org_20260909", "co_org_20260909_2"], day)).toBe(- "co_org_20260909_3",+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.org, ["co_org_20260909"], day)).toBe(+ "co_org_20260909_2",+ );+ expect(+ placeholderSemanticId(SEMANTIC_ID_RULES.org, ["co_org_20260909", "co_org_20260909_2"], day),+ ).toBe("co_org_20260909_3");+ });+});++describe("the kind table", () => {+ const day = new Date(2026, 8, 9);+ const alice = projectIdRule({ userId: "alice", isAdmin: false });++ it("gives Projects and Agents a bare snake_case id, repaired behind the noun when it would start with a digit or be one letter", () => {+ expect(fallbackSemanticId("Plugin Marketplace", SEMANTIC_ID_RULES.project)).toBe(+ "plugin_marketplace",+ );+ expect(fallbackSemanticId("Report Writer", SEMANTIC_ID_RULES.agent)).toBe("report_writer");+ expect(fallbackSemanticId("3D Viewer", SEMANTIC_ID_RULES.agent)).toBe("agent_3d_viewer");+ expect(fallbackSemanticId("x", SEMANTIC_ID_RULES.agent)).toBe("agent_x");+ expect(fallbackSemanticId("2026 Plan", SEMANTIC_ID_RULES.project)).toBe("project_2026_plan");+ expect(fallbackSemanticId("报告写手", SEMANTIC_ID_RULES.agent)).toBeNull();+ for (const kind of ["project", "agent"] as const) {+ expect(SEMANTIC_ID_RULES[kind].prefix).toBe("");+ expect(SEMANTIC_ID_RULES[kind].accepts("report_writer")).toBe(true);+ expect(SEMANTIC_ID_RULES[kind].accepts("2026_plan")).toBe(false);+ }+ });++ it("gives a Benchmark a kebab-case id, suffixed with a hyphen", () => {+ expect(fallbackSemanticId("Report Writing (hard) v1", SEMANTIC_ID_RULES.benchmark)).toBe(+ "report-writing-hard-v1",+ );+ // A model that answers in snake_case is folded into the kind's spelling.+ expect(sanitizeSuggestedId("`report_writing`", SEMANTIC_ID_RULES.benchmark)).toBe(+ "report-writing",+ );+ // Nothing to repair: a Benchmark id may start with a digit.+ expect(fallbackSemanticId("2026 eval", SEMANTIC_ID_RULES.benchmark)).toBe("2026-eval");+ expect(+ fallbackSemanticId("Report Writing", SEMANTIC_ID_RULES.benchmark, ["report-writing"]),+ ).toBe("report-writing-2");+ expect(uniqueSemanticId("a".repeat(64), ["a".repeat(64)], "-", 64)).toBe(`${"a".repeat(62)}-2`);+ expect(SEMANTIC_ID_RULES.benchmark.accepts("Report_writing-v1")).toBe(true);+ expect(SEMANTIC_ID_RULES.benchmark.accepts("../escape")).toBe(false);+ });++ it("puts a non-admin's Project in the owner's namespace, and leaves the admin's bare", () => {+ expect(projectIdRule({ userId: "root", isAdmin: true })).toBe(SEMANTIC_ID_RULES.project);+ expect(fallbackSemanticId("Research Lab", alice)).toBe("alice-research_lab");+ // The suffix may start with a digit: the namespace already starts the id with a letter.+ expect(fallbackSemanticId("2026 Plan", alice)).toBe("alice-2026_plan");+ expect(sanitizeSuggestedId("research_lab", alice, ["alice-research_lab"])).toBe(+ "alice-research_lab_2",+ );+ // The whole id stays within the Project id's cap, namespace included.+ const long = fallbackSemanticId("word ".repeat(30), alice);+ expect(long?.startsWith("alice-")).toBe(true);+ expect(long?.length).toBeLessThanOrEqual(64);+ expect(alice.accepts(long!)).toBe(true);+ expect(alice.accepts("bob-research_lab")).toBe(false);+ expect(alice.accepts("research_lab")).toBe(false);+ });++ it("dates a placeholder behind every kind's own noun and prefix", () => {+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.project, [], day)).toBe("project_20260909");+ expect(placeholderSemanticId(alice, [], day)).toBe("alice-project_20260909");+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.agent, ["agent_20260909"], day)).toBe(+ "agent_20260909_2",+ );+ expect(placeholderSemanticId(SEMANTIC_ID_RULES.benchmark, ["benchmark-20260909"], day)).toBe(+ "benchmark-20260909-2",);+ for (const kind of ["org", "channel", "project", "agent", "benchmark"] as const) {+ expect(+ SEMANTIC_ID_RULES[kind].accepts(placeholderSemanticId(SEMANTIC_ID_RULES[kind], [], day)),+ kind,+ ).toBe(true);+ }});});diff --git a/packages/server/test/suggest-id-routes.test.ts b/packages/server/test/suggest-id-routes.test.tsnew file mode 100644index 00000000..ac5c00b9--- /dev/null+++ b/packages/server/test/suggest-id-routes.test.ts@@ -0,0 +1,302 @@+/**+ * `POST /api/projects/:p/suggest-id` over the real app: one route proposes the id of every+ * kind a create dialog names. Each kind gets the id shape its create route accepts (a+ * non-admin's Project in the caller's namespace, a kebab-case Benchmark), steps around every+ * name that create route refuses (every Project, the Project's Agents, its Benchmarks — a+ * folder no list shows included), asks only whoever that create route admits, and falls+ * through model → slug → placeholder. `org` and `channel` delegate to the organization+ * service. The model is never reached: the Project's utility completion is replaced by a+ * scripted one for every case.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { agentsDir, benchmarksDir } from "@prismshadow/penguin-core";+import type {+ AgentsResponse,+ BenchmarkCreateRequest,+ BenchmarksResponse,+ ProjectsResponse,+ SemanticIdSuggestResponse,+} from "../src/api/types.js";+import type { UtilityCompletion } from "../src/services/project-config-service.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const answered = (text: string): UtilityCompletion => ({ ok: true, text });+const failed = (error: string): UtilityCompletion => ({ ok: false, cause: "failed", error });+const NO_MODEL: UtilityCompletion = {+ ok: false,+ cause: "no_model",+ error: "the Project names no default model",+};++/** Today's `yyyymmdd`, which is what a placeholder carries. */+function stamp(): string {+ const now = new Date();+ const pad = (n: number) => String(n).padStart(2, "0");+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;+}++const benchmarkBody = (id: string): BenchmarkCreateRequest => ({+ id,+ title: "Report writing",+ runs: 1,+ cases: [{ id: "CASE-001-x", title: "X", statement: "Do X.", rubric: "- 100 pts: X." }],+});++describe("suggest-id routes", () => {+ let t: TestApp;+ let completion: { prompts: string[]; answers: UtilityCompletion[] };+ let owner: ReturnType<typeof apiClient>;+ const project = "olivia-default_project";+ const url = `/api/projects/${project}/suggest-id`;++ const suggest = async (+ client: ReturnType<typeof apiClient>,+ body: unknown,+ route = url,+ ): Promise<SemanticIdSuggestResponse> => {+ const res = await client.post(route, body);+ expect(res.status, await res.clone().text()).toBe(200);+ return (await res.json()) as SemanticIdSuggestResponse;+ };++ beforeEach(async () => {+ t = await createTestApp();+ completion = { prompts: [], answers: [] };+ // Every proposal in this suite goes through here; nothing reaches a provider.+ t.deps.projectConfigService.completeOnce = async (_projectId, prompt) => {+ completion.prompts.push(prompt);+ return completion.answers.shift() ?? NO_MODEL;+ };+ owner = apiClient(t.app, (await provisionUser(t.app, "olivia")).cookie);+ });++ afterEach(async () => {+ await t.cleanup();+ });++ it("proposes an Agent id from the model's answer and steps around the Project's Agents", async () => {+ completion.answers = [answered("`report_writer`\n")];+ expect(await suggest(owner, { name: "报告写手", kind: "agent" })).toEqual({+ id: "report_writer",+ source: "model",+ });+ // No prefix to warn about, and the ask names the name.+ expect(completion.prompts[0]).toContain("snake_case");+ expect(completion.prompts[0]).toContain("Name: 报告写手");+ expect(completion.prompts[0]).not.toContain("prefix");++ expect(+ (await owner.post(`/api/projects/${project}/agents`, { agentId: "report_writer" })).status,+ ).toBe(201);+ completion.answers = [answered("report_writer")];+ expect(await suggest(owner, { name: "报告写手", kind: "agent" })).toEqual({+ id: "report_writer_2",+ source: "model",+ });+ // The Project's own Agents are avoided without being read out to the model.+ expect(completion.prompts[1]).not.toContain("taken");+ });++ it("asks again with the format spelled out, then falls back to the slug and records why", async () => {+ completion.answers = [answered("我建议叫「报告写手」"), answered("report_writer")];+ expect(await suggest(owner, { name: "Report Writer", kind: "agent" })).toEqual({+ id: "report_writer",+ source: "model",+ });+ expect(completion.prompts[1]).toContain("Answer with the identifier only");+ expect(t.deps.errorsRepo.recent(project)).toEqual([]);++ completion.answers = [failed("401 invalid api key")];+ expect(await suggest(owner, { name: "Report Writer", kind: "agent" })).toEqual({+ id: "report_writer",+ source: "fallback",+ });+ // A request that failed outright is not repeated.+ expect(completion.prompts).toHaveLength(3);+ const recorded = t.deps.errorsRepo.recent(project);+ expect(recorded).toHaveLength(1);+ expect(recorded[0]).toMatchObject({ source: "id_suggest", code: "id_suggest_failed" });+ expect(recorded[0]?.message).toContain('agent id for "Report Writer": 401 invalid api key');+ });++ it("answers a dated placeholder for a name neither the model nor the slug can name", async () => {+ // No default model: nothing is asked twice, and the reason says so.+ expect(await suggest(owner, { name: "报告写手", kind: "agent" })).toEqual({+ id: `agent_${stamp()}`,+ source: "placeholder",+ reason: "no_default_model",+ });+ completion.answers = [answered("报告写手"), answered("写手")];+ expect(await suggest(owner, { name: "官网改版", kind: "project" })).toEqual({+ id: `olivia-project_${stamp()}`,+ source: "placeholder",+ reason: "unusable_answer",+ });+ // A name that carries ASCII is repaired rather than discarded: an Agent id starts with a letter.+ expect(await suggest(owner, { name: "3D Viewer", kind: "agent" })).toEqual({+ id: "agent_3d_viewer",+ source: "fallback",+ });+ });++ it("a Benchmark id is kebab-case, owner-only, and avoids the Project's Benchmarks", async () => {+ completion.answers = [answered("report_writing")];+ expect(await suggest(owner, { name: "报告写作", kind: "benchmark" })).toEqual({+ id: "report-writing",+ source: "model",+ });+ expect(completion.prompts[0]).toContain("kebab-case");+ expect(+ (await owner.post(`/api/projects/${project}/benchmarks`, benchmarkBody("report-writing")))+ .status,+ ).toBe(201);+ completion.answers = [answered("我不知道"), answered("还是不知道")];+ expect(completion.prompts).toHaveLength(1);+ expect(await suggest(owner, { name: "Report Writing", kind: "benchmark" })).toEqual({+ id: "report-writing-2",+ source: "fallback",+ });+ expect(completion.prompts[2]).toContain("digits and hyphens, nothing else");+ expect(await suggest(owner, { name: "报告写作", kind: "benchmark" })).toEqual({+ id: `benchmark-${stamp()}`,+ source: "placeholder",+ reason: "no_default_model",+ });++ // A member may create Agents but not Benchmarks, and is refused the proposal the same way.+ const mia = await provisionUser(t.app, "mia");+ expect((await owner.post(`/api/projects/${project}/members`, { userId: "mia" })).status).toBe(+ 201,+ );+ const member = apiClient(t.app, mia.cookie);+ const asked = completion.prompts.length;+ expect((await member.post(url, { name: "Report", kind: "benchmark" })).status).toBe(403);+ expect((await member.post(url, { name: "Report", kind: "agent" })).status).toBe(200);+ expect(completion.prompts).toHaveLength(asked + 1);+ });++ it("a Project id lives in the caller's namespace and avoids every Project on the server", async () => {+ completion.answers = [answered("research_lab")];+ expect(await suggest(owner, { name: "科研实验室", kind: "project" })).toEqual({+ id: "olivia-research_lab",+ source: "model",+ });+ // The namespace is added to the answer, so the model is told not to add one.+ expect(completion.prompts[0]).toContain("Do not add any prefix of your own");+ expect((await owner.post("/api/projects", { projectId: "olivia-research_lab" })).status).toBe(+ 201,+ );+ expect(await suggest(owner, { name: "Research Lab", kind: "project" })).toEqual({+ id: "olivia-research_lab_2",+ source: "fallback",+ });++ // The admin's ids are plain, and another owner's Project is still avoided.+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ completion.answers = [answered("default_project")];+ expect(+ await suggest(+ admin,+ { name: "Default project", kind: "project" },+ "/api/projects/default_project/suggest-id",+ ),+ ).toEqual({ id: "default_project_2", source: "model" });+ });++ it("steps around a folder the create route refuses even when no list shows it", async () => {+ // A Benchmark deleted mid-evaluation leaves its directory without a config, an Agent folder+ // can lack system_config.yaml, and a Project directory its row.+ await fs.mkdir(path.join(benchmarksDir(t.root, project), "report-writing", "CASE-001-x"), {+ recursive: true,+ });+ await fs.mkdir(path.join(agentsDir(t.root, project), "report_writer"));+ await fs.mkdir(path.join(t.root, "olivia-research_lab"));+ const benchmarks = (await (+ await owner.get(`/api/projects/${project}/benchmarks`)+ ).json()) as BenchmarksResponse;+ expect(benchmarks.benchmarks.map((b) => b.id)).not.toContain("report-writing");+ const agents = (await (+ await owner.get(`/api/projects/${project}/agents`)+ ).json()) as AgentsResponse;+ expect(agents.agents.map((a) => a.agentId)).not.toContain("report_writer");+ const projects = (await (await owner.get("/api/projects")).json()) as ProjectsResponse;+ expect(projects.projects.map((p) => p.projectId)).not.toContain("olivia-research_lab");+ // None of them lists, yet every create route refuses the name.+ expect(+ (await owner.post(`/api/projects/${project}/benchmarks`, benchmarkBody("report-writing")))+ .status,+ ).toBe(409);+ expect(+ (await owner.post(`/api/projects/${project}/agents`, { agentId: "report_writer" })).status,+ ).toBe(409);+ expect((await owner.post("/api/projects", { projectId: "olivia-research_lab" })).status).toBe(+ 409,+ );++ expect(await suggest(owner, { name: "Report Writing", kind: "benchmark" })).toEqual({+ id: "report-writing-2",+ source: "fallback",+ });+ expect(await suggest(owner, { name: "Report Writer", kind: "agent" })).toEqual({+ id: "report_writer_2",+ source: "fallback",+ });+ expect(await suggest(owner, { name: "Research Lab", kind: "project" })).toEqual({+ id: "olivia-research_lab_2",+ source: "fallback",+ });+ });++ it("validates the body, and asks nothing of a Project the caller cannot reach", async () => {+ expect((await owner.post(url, { kind: "agent" })).status).toBe(400);+ expect((await owner.post(url, { name: "", kind: "agent" })).status).toBe(400);+ expect((await owner.post(url, { name: "Report" })).status).toBe(400);+ expect((await owner.post(url, { name: "Report", kind: "team" })).status).toBe(400);+ expect((await owner.post(url, { name: "Report", kind: "agent", taken: "x" })).status).toBe(400);+ const stranger = apiClient(t.app, (await provisionUser(t.app, "stranger")).cookie);+ // Company mode is on, so an `org` or `channel` 404 can only be the membership check's.+ t.deps.serverSettingsRepo.setCompanyMode(true);+ for (const kind of ["project", "agent", "benchmark", "org", "channel"]) {+ const res = await stranger.post(url, { name: "Report", kind });+ expect(res.status, kind).toBe(404);+ expect(((await res.json()) as { error: { code: string } }).error.code, kind).toBe(+ "project_not_found",+ );+ }+ expect(completion.prompts).toEqual([]);+ });++ it("org and channel go through the organization service, only while company mode is on", async () => {+ const off = await owner.post(url, { name: "科研公司", kind: "org" });+ expect(off.status).toBe(404);+ expect(((await off.json()) as { error: { code: string } }).error.code).toBe("company_mode_off");+ expect(completion.prompts).toEqual([]);++ t.deps.serverSettingsRepo.setCompanyMode(true);+ completion.answers = [answered("research_lab")];+ expect(await suggest(owner, { name: "科研公司", kind: "org" })).toEqual({+ id: "co_research_lab",+ source: "model",+ });+ completion.answers = [answered("site")];+ expect(await suggest(owner, { name: "站点", kind: "channel", taken: ["ch_site"] })).toEqual({+ id: "ch_site_2",+ source: "model",+ });+ expect(completion.prompts[1]).toContain("Those answers are taken, prefix included: ch_site.");+ // A dead end of an org or channel proposal is recorded as the organization's.+ completion.answers = [failed("connect ETIMEDOUT")];+ expect(await suggest(owner, { name: "科研公司", kind: "org" })).toEqual({+ id: `co_org_${stamp()}`,+ source: "placeholder",+ reason: "model_failed",+ });+ expect(t.deps.errorsRepo.recent(project)[0]).toMatchObject({+ source: "organization",+ code: "id_suggest_failed",+ });+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 1990e734..52ead73b 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -1468,9 +1468,16 @@ export const listOrganizations = (projectId: string) =>export const createOrganization = (projectId: string, body: OrganizationCreateRequest) =>apiFetch<OrganizationDetail>(orgBase(projectId), { method: "POST", body });-/** A semantic id for a display name (organization or channel), from the Project's default model with an ASCII fallback. */+/**+ * A semantic id for a display name — a Project's, an Agent's, a Benchmark's, an organization's or+ * a channel's, by `kind` — from the default model of the Project in the path, with an ASCII+ * fallback and a dated placeholder behind it.+ */export const suggestSemanticId = (projectId: string, body: SemanticIdSuggestRequest) =>- apiFetch<SemanticIdSuggestResponse>(`${orgBase(projectId)}/suggest-id`, { method: "POST", body });+ apiFetch<SemanticIdSuggestResponse>(`/api/projects/${encodeURIComponent(projectId)}/suggest-id`, {+ method: "POST",+ body,+ });export const getOrganization = (projectId: string, orgId: string) =>apiFetch<OrganizationDetail>(orgBase(projectId, orgId));diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex e455452a..3d445800 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -43,6 +43,7 @@ import { Modal } from "../ui/modal";import { ConfirmModal } from "../ui/confirm-modal";import { Badge } from "../ui/badge";import { InfoPopover } from "../ui/info-popover";+import { SemanticIdField } from "../../features/semantic-id/semantic-id-field";/** Approval modes offered by the new-chat-defaults select, in the composer menu's order. */const APPROVAL_MODES: readonly ApprovalMode[] = [@@ -62,6 +63,7 @@ export function CreateProjectDialog({onCreated: (projectId: string) => void;}) {const { user } = useAuth();+ const { currentProject } = useProject();// Non-admin Project ids are forced to have a "<username>-" prefix: the input locks the prefix segment, only the rest is editable.const prefix = user && !user.isAdmin ? `${user.userId}-` : "";const [idInput, setIdInput] = useState("");@@ -124,53 +126,34 @@ export function CreateProjectDialog({}><div className="space-y-3">- {prefix ? (- <div>- <FieldLabel required>{S.project.id}</FieldLabel>- <div className="flex items-stretch">- <span className="flex shrink-0 items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-100 px-2 font-mono text-xs text-gray-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400">- {prefix}- </span>- <Input- size="sm"- className="rounded-l-none"- value={idInput}- invalid={Boolean(idError)}- onChange={(e) => {- setIdInput(e.target.value);- setIdError(undefined);- }}- autoFocus- />- </div>- {idError ? (- <FieldError>{idError}</FieldError>- ) : (- <FieldHint>{S.project.idPrefixHint}</FieldHint>- )}- </div>- ) : (- <Input- label={S.project.id}- required- size="sm"- value={idInput}- error={idError}- onChange={(e) => {- setIdInput(e.target.value);- setIdError(undefined);- }}- hint={S.project.idHint}- autoFocus- />- )}+ {/* The name comes first and the id is derived from it: an id is the harder half to+ invent, and naming the thing is where anyone starts anyway. */}<Inputlabel={S.project.displayName}hint={S.project.displayNameHint}size="sm"value={name}+ autoFocus+ disabled={busy}onChange={(e) => setName(e.target.value)}/>+ {/* A Project is not inside a Project: the one this dialog was opened from lends its+ default model to the proposal. A non-admin types only what follows "<username>-". */}+ <SemanticIdField+ projectId={currentProject?.projectId ?? null}+ kind="project"+ label={S.project.id}+ hint={prefix ? S.project.idPrefixHint : S.project.idHint}+ value={idInput}+ source={name}+ error={idError}+ disabled={busy}+ {...(prefix ? { lockedPrefix: prefix } : {})}+ onChange={(id) => {+ setIdInput(id);+ setIdError(undefined);+ }}+ /></div></Modal>);diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsxindex 26f7a34e..991104cb 100644--- a/packages/web/src/features/agents/agents-page.tsx+++ b/packages/web/src/features/agents/agents-page.tsx@@ -52,6 +52,7 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";import { GlyphIcon } from "../../components/ui/glyph-icon";import { UpdatePill } from "../../components/ui/update-dot";import { TodoNotice } from "../../components/ui/todo-notice";+import { SemanticIdField } from "../semantic-id/semantic-id-field";import {CloseIcon,GEAR_ICON,@@ -723,25 +724,30 @@ export function AgentsPage() {}><div className="space-y-3">- <Input- label={S.agent.id}- required- size="sm"- value={agentId}- onChange={(e) => {- setAgentId(e.target.value);- setIdError(undefined);- }}- error={idError}- hint={S.agent.idHint}- autoFocus- />+ {/* The name comes first and the id is derived from it: an id is the harder half to+ invent, and naming the Agent is where anyone starts anyway. */}<Inputlabel={S.common.name}size="sm"value={name}onChange={(e) => setName(e.target.value)}hint={S.agent.nameHint}+ autoFocus+ />+ <SemanticIdField+ projectId={projectId ?? null}+ kind="agent"+ label={S.agent.id}+ hint={S.agent.idHint}+ generateHint={S.agent.idGenerateHint}+ value={agentId}+ source={name.trim() || description}+ error={idError}+ disabled={busy}+ onChange={(id) => {+ setAgentId(id);+ setIdError(undefined);+ }}/><Textarealabel={S.agent.description}diff --git a/packages/web/src/features/benchmark/benchmark-prompts.ts b/packages/web/src/features/benchmark/benchmark-prompts.tsindex d3314e5c..d5e376d5 100644--- a/packages/web/src/features/benchmark/benchmark-prompts.ts+++ b/packages/web/src/features/benchmark/benchmark-prompts.ts@@ -156,18 +156,6 @@ export function benchmarkPath(benchmarkId: string): string {return `benchmarks/${benchmarkId}`;}-/**- * A directory-name proposal from a title: ASCII letters and digits kept (lowercased), any run- * of other characters folded into one hyphen, edges trimmed. A title with no ASCII word — a- * Chinese one — yields "", and the form then asks for an id outright.- */-export function slugFromTitle(title: string): string {- return title- .toLowerCase()- .replace(/[^a-z0-9]+/g, "-")- .replace(/^-+|-+$/g, "");-}-/** `CASE-NNN-<slug>`: the case directory name from its 1-based position and slug. */export function caseId(index: number, slug: string): string {return `CASE-${String(index).padStart(3, "0")}-${slug}`;diff --git a/packages/web/src/features/benchmark/create-benchmark-modal.tsx b/packages/web/src/features/benchmark/create-benchmark-modal.tsxindex 91fccc04..d9f364de 100644--- a/packages/web/src/features/benchmark/create-benchmark-modal.tsx+++ b/packages/web/src/features/benchmark/create-benchmark-modal.tsx@@ -23,7 +23,8 @@ import { Input, Textarea } from "../../components/ui/input";import { Modal } from "../../components/ui/modal";import { TRASH_ICON } from "../../components/ui/session-row-menu";import { toastSuccess } from "../../components/ui/toast";-import { ID_PATTERN, caseId, isValidRuns, slugFromTitle } from "./benchmark-prompts";+import { SemanticIdField } from "../semantic-id/semantic-id-field";+import { ID_PATTERN, caseId, isValidRuns } from "./benchmark-prompts";interface CaseDraft {/** Stable React key, independent of position, so removing a case keeps the others' state. */@@ -71,8 +72,6 @@ function CreateBenchmarkDialog({ onClose, projectId, onCreated }: CreateBenchmar});const [title, setTitle] = useState("");const [id, setId] = useState("");- // The id follows the title until it is edited by hand.- const [idTouched, setIdTouched] = useState(false);const [description, setDescription] = useState("");const [runs, setRuns] = useState("1");const [cases, setCases] = useState<CaseDraft[]>(() => [newCase()]);@@ -159,27 +158,29 @@ function CreateBenchmarkDialog({ onClose, projectId, onCreated }: CreateBenchmar><div className="space-y-4"><p className="text-sm text-gray-600 dark:text-gray-300">{S.benchmark.manualCreateIntro}</p>+ {/* The title comes first and the id is derived from it on request — by the model, so+ a Chinese title gets English words — never rewritten while the title is typed. */}<Inputlabel={S.benchmark.titleField}requiredvalue={title}- onChange={(e) => {- setTitle(e.target.value);- if (!idTouched) setId(slugFromTitle(e.target.value));- }}+ onChange={(e) => setTitle(e.target.value)}{...errorProp(errors.title)}/>- <Input+ <SemanticIdField+ projectId={projectId}+ kind="benchmark"label={S.benchmark.idField}hint={S.benchmark.idHint}- required+ generateHint={S.benchmark.idGenerateHint}value={id}- className="font-mono"- onChange={(e) => {- setIdTouched(true);- setId(e.target.value);+ source={title.trim() || description}+ error={errors.id}+ disabled={busy}+ onChange={(next) => {+ setId(next);+ setErrors((prev) => ({ ...prev, id: undefined }));}}- {...errorProp(errors.id)}/><Textarealabel={S.benchmark.descriptionField}diff --git a/packages/web/src/features/company/channel-dialogs.tsx b/packages/web/src/features/company/channel-dialogs.tsxindex 2ffe4619..f3dc1bd0 100644--- a/packages/web/src/features/company/channel-dialogs.tsx+++ b/packages/web/src/features/company/channel-dialogs.tsx@@ -21,7 +21,7 @@ import { Input, Textarea } from "../../components/ui/input";import { Modal } from "../../components/ui/modal";import { channelIdProblem } from "./channel-list";import type { ChannelIdProblem } from "./channel-list";-import { SemanticIdField } from "./semantic-id-field";+import { SemanticIdField } from "../semantic-id/semantic-id-field";import { ErrorLine } from "./shared";/** The error codes that are about the id the user typed; every other failure is the form's. */diff --git a/packages/web/src/features/company/org-dialogs.tsx b/packages/web/src/features/company/org-dialogs.tsxindex a6729b05..adf0ebb9 100644--- a/packages/web/src/features/company/org-dialogs.tsx+++ b/packages/web/src/features/company/org-dialogs.tsx@@ -62,7 +62,7 @@ import { ErrorLine, MoneyPerMonthInput, OrgStatusPill } from "./shared";import { orgCreatedTarget } from "./company-nav";import { fromStoredUsd, isBudgetText, toStoredUsd } from "./budget-input";import { ORG_EXAMPLES } from "./org-examples";-import { SemanticIdField } from "./semantic-id-field";+import { SemanticIdField } from "../semantic-id/semantic-id-field";import {EMPTY_ORG_DRAFT,clearOrgDraft,diff --git a/packages/web/src/features/company/id-suggest-notice.ts b/packages/web/src/features/semantic-id/id-suggest-notice.tssimilarity index 61%rename from packages/web/src/features/company/id-suggest-notice.tsrename to packages/web/src/features/semantic-id/id-suggest-notice.tsindex 47c71847..80944846 100644--- a/packages/web/src/features/company/id-suggest-notice.ts+++ b/packages/web/src/features/semantic-id/id-suggest-notice.ts@@ -1,7 +1,8 @@/**- * What the id field says about the id a proposal just handed it (pure, unit tested).+ * What the id field does with the id a proposal just handed it (pure, unit tested): what goes+ * in the box, and what the field says about it.*- * `POST /organizations/suggest-id` always answers with a valid id, so the field's job is not+ * `POST /suggest-id` always answers with a valid id, so the field's job is not* to report a refusal but to say how much the id it just received is worth. A model-made id* needs no note at all. A transliteration of the display name gets a quiet one, because it is* a mechanical reading of what the user typed rather than a name anyone chose. A placeholder@@ -15,8 +16,8 @@import type { SemanticIdSuggestResponse } from "@prismshadow/penguin-server/api";import type { Strings } from "../../lib/strings";-/** The field's own dictionary slice — `S.company.idSuggest`. */-export type IdSuggestStrings = Strings["company"]["idSuggest"];+/** The field's own dictionary slice — `S.semanticId.idSuggest`. */+export type IdSuggestStrings = Strings["semanticId"]["idSuggest"];/** A line under the field, with the tone it is drawn in; null when the id speaks for itself. */export interface IdSuggestNotice {@@ -36,3 +37,15 @@ export function idSuggestNotice(if (res.source === "fallback") return { tone: "muted", text: s.fromName };return null;}++/**+ * What goes in the box: the proposal, less the part the field draws in front of the box. The+ * server answers a non-admin's Project id whole (`alice-research_lab`) while the box holds only+ * what follows `alice-`; an id that does not start with the locked part is left whole, so the+ * caller's validation names the problem instead of the field hiding it.+ */+export function proposalValue(id: string, lockedPrefix: string | undefined): string {+ return lockedPrefix !== undefined && id.startsWith(lockedPrefix)+ ? id.slice(lockedPrefix.length)+ : id;+}diff --git a/packages/web/src/features/company/semantic-id-field.tsx b/packages/web/src/features/semantic-id/semantic-id-field.tsxsimilarity index 65%rename from packages/web/src/features/company/semantic-id-field.tsxrename to packages/web/src/features/semantic-id/semantic-id-field.tsxindex 637be542..b24e4900 100644--- a/packages/web/src/features/company/semantic-id-field.tsx+++ b/packages/web/src/features/semantic-id/semantic-id-field.tsx@@ -1,15 +1,17 @@/**- * The id field both create dialogs wear — an organization's and a channel's. The id is still- * required and still validated by the caller (the two have different rules and different- * error copy), but it no longer has to be invented: the field carries a "generate" button- * that asks the server to propose one from the display name (or, when nothing else names the- * thing yet, from the mission), which is why the name is the field above it.+ * The id field every create dialog that names an object with a semantic id wears — a Project's,+ * an Agent's, a Benchmark's, an organization's and a channel's. The id is still required and+ * still validated by the caller (each kind has its own rule and its own error copy), but it no+ * longer has to be invented: the field carries a "generate" button that asks the server to+ * propose one from the display name (or, when nothing else names the thing yet, from the+ * mission or the description), which is why the name is the field above it.** The proposal REPLACES whatever is in the box: the button is pressed to get an id, not to* get a suggestion beside the one already typed. It is unavailable while there is no text to* derive from and while a request is in flight, and it always comes back with an id — a name* nothing could translate gets a placeholder, and the note under the field says so and asks* for a real name, rather than a toast that would be gone by the time the user looks down.+ * Nothing is proposed on its own: typing a name never rewrites the id.** The button says what it does in words — a model is asked for the id, which is not something* a sparkles glyph on its own tells anyone — so it sits BESIDE the box rather than inside it,@@ -17,10 +19,14 @@* of is the field's `<label>`: a `<button>` is a labelable element, so a wrapping label would* name the button instead of the input (the trap field.tsx documents). Hence the label row and* the hint are drawn here and the `Input` renders bare.+ *+ * A non-admin's Project id is `<username>-<suffix>` and only the suffix is typed: the fixed part+ * is drawn as `lockedPrefix` in front of the box, and a proposal (which the server returns whole)+ * fills in the part after it.*/import { useId, useState } from "react";import type { KeyboardEvent } from "react";-import type { SemanticIdSuggestRequest } from "@prismshadow/penguin-server/api";+import type { SemanticIdKind } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";@@ -31,7 +37,7 @@ import { Input } from "../../components/ui/input";import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";import { toastError } from "../../components/ui/toast";import { GlyphIcon } from "../../components/ui/glyph-icon";-import { idSuggestNotice } from "./id-suggest-notice";+import { idSuggestNotice, proposalValue } from "./id-suggest-notice";import type { IdSuggestNotice } from "./id-suggest-notice";/** Generate (lucide sparkles): the four-pointed star with its two smaller companions. */@@ -47,13 +53,19 @@ export function SemanticIdField({source,taken,error,+ lockedPrefix,+ generateHint,disabled = false,onChange,onEnter,}: {- projectId: string;+ /**+ * The Project whose default model is asked — for a Project id, the Project the dialog was+ * opened from. Null while there is none, which leaves the button unavailable.+ */+ projectId: string | null;/** What the id is for; the server's proposal is shaped by it. */- kind: SemanticIdSuggestRequest["kind"];+ kind: SemanticIdKind;label: string;/** The id rule, which stays on screen while the user types; the generation clause is appended here. */hint: string;@@ -64,6 +76,10 @@ export function SemanticIdField({taken?: readonly string[];/** The caller's own validation message; it outranks anything the generation has to say. */error?: string | undefined;+ /** A fixed start of the id drawn in front of the box and not typed (`value` is what follows it). */+ lockedPrefix?: string;+ /** The generation clause appended to `hint`, when "the display name" is not what the dialog calls it. */+ generateHint?: string;disabled?: boolean;onChange: (id: string) => void;/** Enter inside the field, where the dialog submits on it. */@@ -81,6 +97,7 @@ export function SemanticIdField({const below = showError || notice !== null;const generate = async () => {+ if (projectId === null) return;setBusy(true);setNotice(null);try {@@ -89,8 +106,8 @@ export function SemanticIdField({kind,...(taken !== undefined && taken.length > 0 ? { taken: [...taken] } : {}),});- onChange(res.id);- setNotice(idSuggestNotice(res, S.company.idSuggest));+ onChange(proposalValue(res.id, lockedPrefix));+ setNotice(idSuggestNotice(res, S.semanticId.idSuggest));} catch (e) {// The request itself failed (offline, no permission, the mode switched off): the id is// unchanged and there is nothing to say under the field.@@ -100,42 +117,55 @@ export function SemanticIdField({}};+ const input = (+ <Input+ id={controlId}+ size="sm"+ required+ value={value}+ invalid={error !== undefined}+ className={`min-w-0 flex-1 font-mono${lockedPrefix !== undefined ? " rounded-l-none" : ""}`}+ disabled={disabled}+ {...(below ? { "aria-describedby": messageId } : {})}+ onChange={(e) => {+ setNotice(null);+ onChange(e.target.value);+ }}+ {...(onEnter !== undefined+ ? {+ onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter") {+ e.preventDefault();+ onEnter();+ }+ },+ }+ : {})}+ />+ );+return (<div><FieldLabel htmlFor={controlId} required>{label}</FieldLabel><div className="flex items-center gap-2">- <Input- id={controlId}- size="sm"- required- value={value}- invalid={error !== undefined}- className="min-w-0 flex-1 font-mono"- disabled={disabled}- {...(below ? { "aria-describedby": messageId } : {})}- onChange={(e) => {- setNotice(null);- onChange(e.target.value);- }}- {...(onEnter !== undefined- ? {- onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => {- if (e.key === "Enter") {- e.preventDefault();- onEnter();- }- },- }- : {})}- />+ {lockedPrefix === undefined ? (+ input+ ) : (+ <div className="flex min-w-0 flex-1 items-stretch">+ <span className="flex shrink-0 items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-100 px-2 font-mono text-xs text-gray-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400">+ {lockedPrefix}+ </span>+ {input}+ </div>+ )}{/* The tooltip keeps saying where the id comes from; the label only says who makes it. */}<Buttonsize="sm"- title={S.company.generateId}+ title={S.semanticId.generateId}aria-busy={busy || undefined}- disabled={disabled || busy || !derivable}+ disabled={disabled || busy || !derivable || projectId === null}onClick={() => void generate()}className="shrink-0 whitespace-nowrap">@@ -144,7 +174,7 @@ export function SemanticIdField({) : (<GlyphIcon d={SPARKLES_ICON} size={ICON_SIZE.inlineGlyph} />)}- {S.company.generateIdLabel}+ {S.semanticId.generateIdLabel}</Button></div>{showError ? (@@ -160,7 +190,7 @@ export function SemanticIdField({{/* The generation clause carries its own leading separator: what joins two clausesis punctuation, and punctuation is part of the language. The id rule stays onscreen beside a quiet note — it is what the user reads while typing. */}- <FieldHint>{`${hint}${S.company.idGenerateHint}`}</FieldHint>+ <FieldHint>{`${hint}${generateHint ?? S.semanticId.idGenerateHint}`}</FieldHint>{notice !== null && (<span id={messageId} role="status" className={`mt-1 block text-xs ${toneInk.muted}`}>{notice.text}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 0e45c969..6d990f7a 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -435,6 +435,39 @@ export const en: Strings = {time: "Time",},+ /**+ * The id field every create dialog with a semantic id wears (features/semantic-id): a Project's,+ * an Agent's, a Benchmark's, an organization's and a channel's.+ */+ semanticId: {+ /**+ * The id field's generate button — its label says who proposes the id, its tooltip says+ * what the proposal is derived from — and the clause the hint appends for it. The clause+ * carries its own leading separator: what joins two clauses is punctuation, and+ * punctuation belongs to the language.+ */+ generateIdLabel: "Generate with AI",+ generateId: "Generate an id from the name",+ idGenerateHint: "; you can also generate one from the display name",+ /** What the field says about the id a proposal just filled in (see id-suggest-notice.ts). */+ idSuggest: {+ /** Under an id transliterated from the name: quiet, because nothing went wrong. */+ fromName: "Transliterated from the name",+ /** Under a placeholder id: it names nothing, so it says why and asks for a real name. */+ placeholder: (reason: string): string =>+ `The model gave no usable id (${reason}); a placeholder was filled in — please change it to something meaningful`,+ /** Why the proposal fell through, keyed by the server's reason code. */+ reasons: {+ no_default_model: "no default model configured",+ model_failed: "the model request failed",+ unusable_answer: "the model's answer was unusable",+ no_ascii: "the name carries no ASCII to transliterate",+ },+ /** A reason a newer server named and this build does not know. */+ reasonUnknown: "reason unknown",+ },+ },+auth: {usernameHint:"2–32 chars: starts with a lowercase letter; lowercase letters, digits and underscores only",@@ -528,9 +561,9 @@ export const en: Strings = {createTitle: "New Project",id: "Project id",idHint:- "2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",+ "2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only; cannot be changed later",idPrefixHint:- "The id is prefixed with your username and a hyphen; append lowercase letters, digits or underscores. Cannot be changed later.",+ "The id is prefixed with your username and a hyphen; append lowercase letters, digits or underscores; cannot be changed later",displayName: "Display name",/** Create dialog only: leaving the name empty falls back to the id. In Project settings the saved name cannot be blanked. */displayNameHint: "Leave empty to use the Project id as the name",@@ -617,7 +650,9 @@ export const en: Strings = {createTitle: "Create agent",id: "Agent id",idHint:- "2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",+ "2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only; cannot be changed later",+ /** The id field's generation clause: the create dialog's name field is labelled Name, not display name. */+ idGenerateHint: "; you can also generate one from the name",nameHint: "Leave empty to use the agent id as the name",description: "Description",createPlugins: "Plugins",@@ -3257,6 +3292,8 @@ Scenarios:idField: "Benchmark id",idHint:"The directory name is the identifier: letters, digits, _ and - only, e.g. report-writing-v1",+ /** The id field's generation clause: a Benchmark is named by its title, not a display name. */+ idGenerateHint: "; you can also generate one from the title",idExists: "A Benchmark with this id already exists; pick another",titleField: "Title",descriptionField: "Description",@@ -3403,32 +3440,6 @@ Scenarios:orgId: "Organization id",orgIdHint:"2–64 characters: a lowercase letter, then lowercase letters, digits or underscores; also the directory name, fixed once created",- /**- * The id field's generate button — its label says who proposes the id, its tooltip says- * what the proposal is derived from — and the clause the hint appends for it. The clause- * carries its own leading separator: what joins two clauses is punctuation, and- * punctuation belongs to the language.- */- generateIdLabel: "Generate with AI",- generateId: "Generate an id from the name",- idGenerateHint: "; you can also generate one from the display name",- /** What the field says about the id a proposal just filled in (see id-suggest-notice.ts). */- idSuggest: {- /** Under an id transliterated from the name: quiet, because nothing went wrong. */- fromName: "Transliterated from the name",- /** Under a placeholder id: it names nothing, so it says why and asks for a real name. */- placeholder: (reason: string): string =>- `The model gave no usable id (${reason}); a placeholder was filled in — please change it to something meaningful`,- /** Why the proposal fell through, keyed by the server's reason code. */- reasons: {- no_default_model: "no default model configured",- model_failed: "the model request failed",- unusable_answer: "the model's answer was unusable",- no_ascii: "the name carries no ASCII to transliterate",- },- /** A reason a newer server named and this build does not know. */- reasonUnknown: "reason unknown",- },displayName: "Display name",displayNameHint: "Leave empty to use the organization id",mission: "Mission",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex d98db907..93397ab7 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -441,6 +441,39 @@ export const zh = {time: "时间",},+ /**+ * The id field every create dialog with a semantic id wears (features/semantic-id): a Project's,+ * an Agent's, a Benchmark's, an organization's and a channel's.+ */+ semanticId: {+ /**+ * The id field's generate button — its label says who proposes the id, its tooltip says+ * what the proposal is derived from — and the clause the hint appends for it. The clause+ * carries its own leading separator: what joins two clauses is punctuation, and+ * punctuation belongs to the language.+ */+ generateIdLabel: "用 AI 生成",+ generateId: "从名称生成 ID",+ idGenerateHint: ";也可以从显示名生成",+ /** What the field says about the id a proposal just filled in (see id-suggest-notice.ts). */+ idSuggest: {+ /** Under an id transliterated from the name: quiet, because nothing went wrong. */+ fromName: "按名称转写生成",+ /** Under a placeholder id: it names nothing, so it says why and asks for a real name. */+ placeholder: (reason: string): string =>+ `模型没有给出可用的 ID(${reason}),已填入占位 ID,请改成有含义的英文名`,+ /** Why the proposal fell through, keyed by the server's reason code. */+ reasons: {+ no_default_model: "未配置默认模型",+ model_failed: "模型调用失败",+ unusable_answer: "模型回答不可用",+ no_ascii: "名称里没有可转写的英文",+ },+ /** A reason a newer server named and this build does not know. */+ reasonUnknown: "原因未知",+ },+ },+auth: {usernameHint: "2~32 位:小写字母开头,仅小写字母、数字与下划线",password: "密码",@@ -618,6 +651,8 @@ export const zh = {createTitle: "创建 Agent",id: "Agent id",idHint: "2~64 位:小写字母开头,仅小写字母、数字与下划线;创建后不可修改",+ /** The id field's generation clause: the create dialog's name field is labelled Name, not display name. */+ idGenerateHint: ";也可以从名称生成",nameHint: "留空则使用 Agent id 作为名称",description: "描述",/** Create dialog's skill picker: the library skills installed into the new Agent. */@@ -3236,6 +3271,8 @@ Benchmark:"填好标题、题干与评分细则后,目录结构会按技能约定写入 Project 的 benchmarks/ 下;Benchmark 与 Agent 平级,之后可以用它评测任意智能体。",idField: "Benchmark id",idHint: "目录名即标识:仅字母、数字、_ 和 -,例如 report-writing-v1",+ /** The id field's generation clause: a Benchmark is named by its title, not a display name. */+ idGenerateHint: ";也可以从标题生成",idExists: "已有同名 Benchmark,请换一个 id",titleField: "标题",descriptionField: "描述",@@ -3376,32 +3413,6 @@ Benchmark:createTitle: "新建组织",orgId: "组织 id",orgIdHint: "2~64 位:小写字母开头,仅小写字母、数字与下划线;也是目录名,创建后不可修改",- /**- * The id field's generate button — its label says who proposes the id, its tooltip says- * what the proposal is derived from — and the clause the hint appends for it. The clause- * carries its own leading separator: what joins two clauses is punctuation, and- * punctuation belongs to the language.- */- generateIdLabel: "用 AI 生成",- generateId: "从名称生成 ID",- idGenerateHint: ";也可以从显示名生成",- /** What the field says about the id a proposal just filled in (see id-suggest-notice.ts). */- idSuggest: {- /** Under an id transliterated from the name: quiet, because nothing went wrong. */- fromName: "按名称转写生成",- /** Under a placeholder id: it names nothing, so it says why and asks for a real name. */- placeholder: (reason: string): string =>- `模型没有给出可用的 ID(${reason}),已填入占位 ID,请改成有含义的英文名`,- /** Why the proposal fell through, keyed by the server's reason code. */- reasons: {- no_default_model: "未配置默认模型",- model_failed: "模型调用失败",- unusable_answer: "模型回答不可用",- no_ascii: "名称里没有可转写的英文",- },- /** A reason a newer server named and this build does not know. */- reasonUnknown: "原因未知",- },displayName: "显示名",displayNameHint: "留空则使用组织 id",mission: "使命",diff --git a/packages/web/test/benchmark-prompts.test.ts b/packages/web/test/benchmark-prompts.test.tsindex 58828999..ba608d6a 100644--- a/packages/web/test/benchmark-prompts.test.ts+++ b/packages/web/test/benchmark-prompts.test.ts@@ -24,7 +24,6 @@ import {evaluateTail,isValidRuns,optimizeTail,- slugFromTitle,} from "../src/features/benchmark/benchmark-prompts";describe("benchmarkCreateTail", () => {@@ -268,12 +267,6 @@ describe("askCaseTail (the case dialog's Ask AI question)", () => {});describe("id helpers", () => {- it("slugFromTitle keeps ASCII words, folds separators, and yields nothing for a CJK title", () => {- expect(slugFromTitle("Report Writing (hard) v1")).toBe("report-writing-hard-v1");- expect(slugFromTitle(" 报告写作 ")).toBe("");- expect(slugFromTitle("--a__b--")).toBe("a-b");- });-it("caseId pads the position to three digits", () => {expect(caseId(1, "contradictions")).toBe("CASE-001-contradictions");expect(caseId(12, "x")).toBe("CASE-012-x");diff --git a/packages/web/test/id-suggest-notice.test.ts b/packages/web/test/id-suggest-notice.test.tsindex d53581f6..621b745a 100644--- a/packages/web/test/id-suggest-notice.test.ts+++ b/packages/web/test/id-suggest-notice.test.ts@@ -9,7 +9,7 @@ import type {SemanticIdSuggestReason,SemanticIdSuggestResponse,} from "@prismshadow/penguin-server/api";-import { idSuggestNotice } from "../src/features/company/id-suggest-notice";+import { idSuggestNotice } from "../src/features/semantic-id/id-suggest-notice";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";@@ -23,7 +23,7 @@ const REASONS = Object.keys({describe("the reason dictionaries", () => {for (const [locale, dict] of Object.entries({ zh, en })) {it(`${locale} carries a phrase for every reason the contract declares, and no other`, () => {- expect(Object.keys(dict.company.idSuggest.reasons).sort()).toEqual([...REASONS].sort());+ expect(Object.keys(dict.semanticId.idSuggest.reasons).sort()).toEqual([...REASONS].sort());});}});@@ -31,17 +31,17 @@ describe("the reason dictionaries", () => {describe("idSuggestNotice", () => {it("says nothing about an id the model produced", () => {const res: SemanticIdSuggestResponse = { id: "co_research_lab", source: "model" };- expect(idSuggestNotice(res, zh.company.idSuggest)).toBeNull();- expect(idSuggestNotice(res, en.company.idSuggest)).toBeNull();+ expect(idSuggestNotice(res, zh.semanticId.idSuggest)).toBeNull();+ expect(idSuggestNotice(res, en.semanticId.idSuggest)).toBeNull();});it("notes a transliteration quietly: nothing went wrong, it is just mechanical", () => {const res: SemanticIdSuggestResponse = { id: "co_plugin_marketplace", source: "fallback" };- expect(idSuggestNotice(res, zh.company.idSuggest)).toEqual({+ expect(idSuggestNotice(res, zh.semanticId.idSuggest)).toEqual({tone: "muted",text: "按名称转写生成",});- expect(idSuggestNotice(res, en.company.idSuggest)?.tone).toBe("muted");+ expect(idSuggestNotice(res, en.semanticId.idSuggest)?.tone).toBe("muted");});it("asks for a real name when the id is a placeholder, and names the reason", () => {@@ -51,11 +51,11 @@ describe("idSuggestNotice", () => {source: "placeholder",reason,};- const note = idSuggestNotice(res, zh.company.idSuggest);+ const note = idSuggestNotice(res, zh.semanticId.idSuggest);expect(note?.tone, reason).toBe("attention");- expect(note?.text, reason).toContain(zh.company.idSuggest.reasons[reason]);- expect(idSuggestNotice(res, en.company.idSuggest)?.text, reason).toContain(- en.company.idSuggest.reasons[reason],+ expect(note?.text, reason).toContain(zh.semanticId.idSuggest.reasons[reason]);+ expect(idSuggestNotice(res, en.semanticId.idSuggest)?.text, reason).toContain(+ en.semanticId.idSuggest.reasons[reason],);}});@@ -67,16 +67,16 @@ describe("idSuggestNotice", () => {reason: "quota_exhausted",} as unknown as SemanticIdSuggestResponse;for (const dict of [zh, en]) {- const note = idSuggestNotice(newer, dict.company.idSuggest);+ const note = idSuggestNotice(newer, dict.semanticId.idSuggest);expect(note?.tone).toBe("attention");- expect(note?.text).toContain(dict.company.idSuggest.reasonUnknown);+ expect(note?.text).toContain(dict.semanticId.idSuggest.reasonUnknown);}});it("names no reason it was not given (a placeholder with the field absent)", () => {const res = { id: "co_org_20260909", source: "placeholder" } as SemanticIdSuggestResponse;- expect(idSuggestNotice(res, en.company.idSuggest)?.text).toContain(- en.company.idSuggest.reasonUnknown,+ expect(idSuggestNotice(res, en.semanticId.idSuggest)?.text).toContain(+ en.semanticId.idSuggest.reasonUnknown,);});});diff --git a/packages/web/test/semantic-id-field.test.ts b/packages/web/test/semantic-id-field.test.tsnew file mode 100644index 00000000..a183a8ed--- /dev/null+++ b/packages/web/test/semantic-id-field.test.ts@@ -0,0 +1,105 @@+/**+ * Every create dialog that names an object with a semantic id wears the one shared id field+ * (features/semantic-id/semantic-id-field.tsx), right under the field that names the object:+ * the name is typed first and the id is derived from it on request. The check parses the real+ * JSX with the TypeScript parser, so a dialog that goes back to a bare id `Input`, asks for the+ * wrong kind, or puts the id above the name fails here, naming the file.+ *+ * Plus the one piece of the field's own logic that is not the notice: what goes in a box that+ * draws part of the id in front of itself.+ */+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import ts from "typescript";+import { proposalValue } from "../src/features/semantic-id/id-suggest-notice";++const SRC = fileURLToPath(new URL("../src", import.meta.url));++/** Each create dialog, the kind its id field asks for, and the label of the field above it. */+const DIALOGS = [+ { file: "components/layout/project-dialogs.tsx", kind: "project", name: "S.project.displayName" },+ { file: "features/agents/agents-page.tsx", kind: "agent", name: "S.common.name" },+ {+ file: "features/benchmark/create-benchmark-modal.tsx",+ kind: "benchmark",+ name: "S.benchmark.titleField",+ },+ { file: "features/company/org-dialogs.tsx", kind: "org", name: "S.company.displayName" },+ {+ file: "features/company/channel-dialogs.tsx",+ kind: "channel",+ name: "S.company.channels.nameField",+ },+] as const;++function jsxTag(node: ts.Node): string | null {+ if (ts.isJsxSelfClosingElement(node)) return node.tagName.getText();+ if (ts.isJsxElement(node)) return node.openingElement.tagName.getText();+ return null;+}++function attribute(node: ts.Node, name: string): string | null {+ const attrs = ts.isJsxSelfClosingElement(node)+ ? node.attributes+ : ts.isJsxElement(node)+ ? node.openingElement.attributes+ : null;+ const attr = attrs?.properties.find(+ (p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText() === name,+ );+ const init = attr?.initializer;+ if (init === undefined) return null;+ if (ts.isStringLiteral(init)) return init.text;+ if (ts.isJsxExpression(init) && init.expression !== undefined) return init.expression.getText();+ return null;+}++/** Every `<SemanticIdField>` in a file, with the JSX element standing right before it. */+function idFields(file: string): { kind: string | null; previousLabel: string | null }[] {+ const source = ts.createSourceFile(+ file,+ readFileSync(`${SRC}/${file}`, "utf8"),+ ts.ScriptTarget.Latest,+ /* setParentNodes */ true,+ ts.ScriptKind.TSX,+ );+ const found: { kind: string | null; previousLabel: string | null }[] = [];+ const visit = (node: ts.Node): void => {+ if (jsxTag(node) === "SemanticIdField") {+ const siblings = ts.isJsxElement(node.parent) ? node.parent.children : undefined;+ // Comments between the two are `{/* … */}` expressions with nothing in them.+ const elements = (siblings ?? []).filter((c) => jsxTag(c) !== null);+ const previous = elements[elements.indexOf(node as ts.JsxChild) - 1];+ found.push({+ kind: attribute(node, "kind"),+ previousLabel: previous !== undefined ? attribute(previous, "label") : null,+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return found;+}++describe("create dialogs with a semantic id", () => {+ for (const dialog of DIALOGS) {+ it(`${dialog.file} asks for a ${dialog.kind} id, under the field that names it`, () => {+ expect(idFields(dialog.file)).toEqual([{ kind: dialog.kind, previousLabel: dialog.name }]);+ });+ }+});++describe("proposalValue", () => {+ it("fills the box with the proposal as the server answered it", () => {+ expect(proposalValue("report_writer", undefined)).toBe("report_writer");+ });++ it("leaves out the part a non-admin's Project id box draws in front of itself", () => {+ expect(proposalValue("alice-research_lab", "alice-")).toBe("research_lab");+ });++ it("keeps an id that does not start with that part whole, for validation to name", () => {+ expect(proposalValue("research_lab", "alice-")).toBe("research_lab");+ });+});